InterpreterStackFrame.cpp 356 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLanguagePch.h"
  6. #include "RuntimeMathPch.h"
  7. #include "EHBailoutData.h"
  8. #include "Library/JavascriptRegularExpression.h"
  9. #if DBG_DUMP
  10. #include "ByteCode/OpCodeUtilAsmJs.h"
  11. #endif
  12. #include "Language/InterpreterStackFrame.h"
  13. #include "Library/JavascriptGeneratorFunction.h"
  14. #include "Library/ForInObjectEnumerator.h"
  15. #include "Library/AtomicsOperations.h"
  16. #include "../../WasmReader/WasmParseTree.h"
  17. ///----------------------------------------------------------------------------
  18. ///
  19. /// macros PROCESS_INtoOUT
  20. ///
  21. /// This set of macros defines standard patterns for processing OpCodes in
  22. /// RcInterpreter::Run(). Each macro is named for "in" - "out":
  23. /// - A: Var
  24. /// - I: Integer
  25. /// - R: Double
  26. /// - X: Nothing
  27. ///
  28. /// Examples:
  29. /// - "A2toA1" reads two registers, each storing an Var, and writes a single
  30. /// register with a new Var.
  31. /// - "A1I1toA2" reads two registers, first an Var and second an Int32, then
  32. /// writes two Var registers.
  33. ///
  34. /// Although these could use lookup tables to standard OpLayout types, this
  35. /// additional indirection would slow the main interpreter loop further by
  36. /// preventing the main 'switch' statement from using the OpCode to become a
  37. /// direct local-function jump.
  38. ///----------------------------------------------------------------------------
  39. #define PROCESS_FALLTHROUGH(name, func) \
  40. case OpCode::name:
  41. #define PROCESS_FALLTHROUGH_COMMON(name, func, suffix) \
  42. case OpCode::name:
  43. #define PROCESS_READ_LAYOUT(name, layout, suffix) \
  44. CompileAssert(OpCodeInfo<OpCode::name>::Layout == OpLayoutType::layout); \
  45. const unaligned OpLayout##layout##suffix * playout = m_reader.layout##suffix(ip); \
  46. Assert((playout != nullptr) == (Js::OpLayoutType::##layout != Js::OpLayoutType::Empty)); // Make sure playout is used
  47. #define PROCESS_NOP_COMMON(name, layout, suffix) \
  48. case OpCode::name: \
  49. { \
  50. PROCESS_READ_LAYOUT(name, layout, suffix); \
  51. break; \
  52. }
  53. #define PROCESS_NOP(name, layout) PROCESS_NOP_COMMON(name, layout,)
  54. #define PROCESS_CUSTOM_COMMON(name, func, layout, suffix) \
  55. case OpCode::name: \
  56. { \
  57. PROCESS_READ_LAYOUT(name, layout, suffix); \
  58. func(playout); \
  59. break; \
  60. }
  61. #define PROCESS_CUSTOM(name, func, layout) PROCESS_CUSTOM_COMMON(name, func, layout,)
  62. #define PROCESS_CUSTOM_L_COMMON(name, func, layout, regslot, suffix) \
  63. case OpCode::name: \
  64. { \
  65. PROCESS_READ_LAYOUT(name, layout, suffix); \
  66. func(playout); \
  67. break; \
  68. }
  69. #define PROCESS_CUSTOM_L(name, func, layout, regslot) PROCESS_CUSTOM_L_COMMON(name, func, layout, regslot,)
  70. #define PROCESS_CUSTOM_L_Arg_COMMON(name, func, suffix) PROCESS_CUSTOM_L_COMMON(name, func, Arg, Arg, suffix)
  71. #define PROCESS_CUSTOM_L_Arg2_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, Arg, suffix)
  72. #define PROCESS_CUSTOM_L_Arg(name, func) PROCESS_CUSTOM_L_COMMON(name, func, Arg, Arg,)
  73. #define PROCESS_CUSTOM_ArgNoSrc_COMMON(name, func, suffix) PROCESS_CUSTOM_COMMON(name, func, ArgNoSrc, suffix)
  74. #define PROCESS_CUSTOM_ArgNoSrc(name, func) PROCESS_CUSTOM_COMMON(name, func, ArgNoSrc,)
  75. #define PROCESS_CUSTOM_L_R0_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, R0, suffix)
  76. #define PROCESS_CUSTOM_L_R0(name, func, layout) PROCESS_CUSTOM_L_COMMON(name, func, layout, R0,)
  77. #define PROCESS_CUSTOM_L_Value_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, Value, suffix)
  78. #define PROCESS_CUSTOM_L_Value(name, func, layout) PROCESS_CUSTOM_L_COMMON(name, func, layout, Value,)
  79. #define PROCESS_TRY(name, func) \
  80. case OpCode::name: \
  81. { \
  82. PROCESS_READ_LAYOUT(name, Br,); \
  83. func(playout); \
  84. ip = m_reader.GetIP(); \
  85. break; \
  86. }
  87. #define PROCESS_EMPTY(name, func) \
  88. case OpCode::name: \
  89. { \
  90. PROCESS_READ_LAYOUT(name, Empty, ); \
  91. func(); \
  92. ip = m_reader.GetIP(); \
  93. break; \
  94. }
  95. #define PROCESS_TRYBR2_COMMON(name, func, suffix) \
  96. case OpCode::name: \
  97. { \
  98. PROCESS_READ_LAYOUT(name, BrReg2, suffix); \
  99. func((const byte*)(playout + 1), playout->RelativeJumpOffset, playout->R1, playout->R2); \
  100. ip = m_reader.GetIP(); \
  101. break; \
  102. }
  103. #define PROCESS_CALL_COMMON(name, func, layout, suffix) \
  104. case OpCode::name: \
  105. { \
  106. PROCESS_READ_LAYOUT(name, layout, suffix); \
  107. func(playout); \
  108. break; \
  109. }
  110. #define PROCESS_CALL(name, func, layout) PROCESS_CALL_COMMON(name, func, layout,)
  111. #define PROCESS_CALL_FLAGS_None_COMMON(name, func, layout, suffix) PROCESS_CALL_COMMON(name, func, layout, suffix)
  112. #define PROCESS_CALL_FLAGS_Value_COMMON(name, func, layout, suffix) PROCESS_CALL_COMMON(name, func, layout, suffix)
  113. #define PROCESS_A1toXX_ALLOW_STACK_COMMON(name, func, suffix) \
  114. case OpCode::name: \
  115. { \
  116. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  117. func(GetRegAllowStackVar(playout->R0)); \
  118. break; \
  119. }
  120. #define PROCESS_A1toXX_COMMON(name, func, suffix) \
  121. case OpCode::name: \
  122. { \
  123. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  124. func(GetReg(playout->R0)); \
  125. break; \
  126. }
  127. #define PROCESS_A1toXX(name, func) PROCESS_A1toXX_COMMON(name, func,)
  128. #define PROCESS_A1toXXMem_COMMON(name, func, suffix) \
  129. case OpCode::name: \
  130. { \
  131. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  132. func(GetReg(playout->R0), GetScriptContext()); \
  133. break; \
  134. }
  135. #define PROCESS_A1toXXMem(name, func) PROCESS_A1toXXMem_COMMON(name, func,)
  136. #define PROCESS_A1toXXMemNonVar_COMMON(name, func, type, suffix) \
  137. case OpCode::name: \
  138. { \
  139. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  140. func((type)GetNonVarReg(playout->R0), GetScriptContext()); \
  141. break; \
  142. }
  143. #define PROCESS_A1toXXMemNonVar(name, func, type) PROCESS_A1toXXMemNonVar_COMMON(name, func, type,)
  144. #define PROCESS_XXtoA1_COMMON(name, func, suffix) \
  145. case OpCode::name: \
  146. { \
  147. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  148. SetReg(playout->R0, \
  149. func()); \
  150. break; \
  151. }
  152. #define PROCESS_XXtoA1(name, func) PROCESS_XXtoA1_COMMON(name, func,)
  153. #define PROCESS_XXtoA1NonVar_COMMON(name, func, suffix) \
  154. case OpCode::name: \
  155. { \
  156. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  157. SetNonVarReg(playout->R0, \
  158. func()); \
  159. break; \
  160. }
  161. #define PROCESS_XXtoA1NonVar(name, func) PROCESS_XXtoA1NonVar_COMMON(name, func,)
  162. #define PROCESS_XXtoA1Mem_COMMON(name, func, suffix) \
  163. case OpCode::name: \
  164. { \
  165. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  166. SetReg(playout->R0, \
  167. func(GetScriptContext())); \
  168. break; \
  169. }
  170. #define PROCESS_XXtoA1Mem(name, func) PROCESS_XXtoA1Mem_COMMON(name, func,)
  171. #define PROCESS_A1toA1_ALLOW_STACK_COMMON(name, func, suffix) \
  172. case OpCode::name: \
  173. { \
  174. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  175. SetRegAllowStackVar(playout->R0, \
  176. func(GetRegAllowStackVar(playout->R1))); \
  177. break; \
  178. }
  179. #define PROCESS_A1toA1_ALLOW_STACK(name, func) PROCESS_A1toA1_ALLOW_STACK_COMMON(name, func,)
  180. #define PROCESS_A1toA1_COMMON(name, func, suffix) \
  181. case OpCode::name: \
  182. { \
  183. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  184. SetReg(playout->R0, \
  185. func(GetReg(playout->R1))); \
  186. break; \
  187. }
  188. #define PROCESS_A1toA1(name, func) PROCESS_A1toA1_COMMON(name, func,)
  189. #define PROCESS_A1toA1Profiled_COMMON(name, func, suffix) \
  190. case OpCode::name: \
  191. { \
  192. PROCESS_READ_LAYOUT(name, ProfiledReg2, suffix); \
  193. SetReg(playout->R0, \
  194. func(GetReg(playout->R1), playout->profileId)); \
  195. break; \
  196. }
  197. #define PROCESS_A1toA1Profiled(name, func) PROCESS_A1toA1Profiled_COMMON(name, func,)
  198. #define PROCESS_A1toA1CallNoArg_COMMON(name, func, layout, suffix) \
  199. case OpCode::name: \
  200. { \
  201. PROCESS_READ_LAYOUT(name, layout, suffix); \
  202. SetReg(playout->R0, \
  203. func(playout)); \
  204. break; \
  205. }
  206. #define PROCESS_A1toA1CallNoArg(name, func, layout) PROCESS_A1toA1CallNoArg_COMMON(name, func, layout,)
  207. #define PROCESS_A1toA1Mem_COMMON(name, func, suffix) \
  208. case OpCode::name: \
  209. { \
  210. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  211. SetReg(playout->R0, \
  212. func(GetReg(playout->R1),GetScriptContext())); \
  213. break; \
  214. }
  215. #define PROCESS_A1toA1Mem(name, func) PROCESS_A1toA1Mem_COMMON(name, func,)
  216. #define PROCESS_A1toA1NonVar_COMMON(name, func, suffix) \
  217. case OpCode::name: \
  218. { \
  219. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  220. SetNonVarReg(playout->R0, \
  221. func(GetNonVarReg(playout->R1))); \
  222. break; \
  223. }
  224. #define PROCESS_A1toA1NonVar(name, func) PROCESS_A1toA1NonVar_COMMON(name, func,)
  225. #define PROCESS_A1toA1MemNonVar_COMMON(name, func, suffix) \
  226. case OpCode::name: \
  227. { \
  228. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  229. SetNonVarReg(playout->R0, \
  230. func(GetNonVarReg(playout->R1),GetScriptContext())); \
  231. break; \
  232. }
  233. #define PROCESS_A1toA1MemNonVar(name, func) PROCESS_A1toA1MemNonVar_COMMON(name, func,)
  234. #define PROCESS_INNERtoA1_COMMON(name, func, suffix) \
  235. case OpCode::name: \
  236. { \
  237. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  238. SetReg(playout->R0, InnerScopeFromIndex(playout->C1)); \
  239. break; \
  240. }
  241. #define PROCESS_INNERtoA1(name, fun) PROCESS_INNERtoA1_COMMON(name, func,)
  242. #define PROCESS_U1toINNERMemNonVar_COMMON(name, func, suffix) \
  243. case OpCode::name: \
  244. { \
  245. PROCESS_READ_LAYOUT(name, Unsigned1, suffix); \
  246. SetInnerScopeFromIndex(playout->C1, func(GetScriptContext())); \
  247. break; \
  248. }
  249. #define PROCESS_U1toINNERMemNonVar(name, func) PROCESS_U1toINNERMemNonVar_COMMON(name, func,)
  250. #define PROCESS_XXINNERtoA1MemNonVar_COMMON(name, func, suffix) \
  251. case OpCode::name: \
  252. { \
  253. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  254. SetNonVarReg(playout->R0, \
  255. func(InnerScopeFromIndex(playout->C1), GetScriptContext())); \
  256. break; \
  257. }
  258. #define PROCESS_XXINNERtoA1MemNonVar(name, func) PROCESS_XXINNERtoA1MemNonVar_COMMON(name, func,)
  259. #define PROCESS_A1INNERtoA1MemNonVar_COMMON(name, func, suffix) \
  260. case OpCode::name: \
  261. { \
  262. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  263. SetNonVarReg(playout->R0, \
  264. func(InnerScopeFromIndex(playout->C1), GetNonVarReg(playout->R1), GetScriptContext())); \
  265. break; \
  266. }
  267. #define PROCESS_A1LOCALtoA1MemNonVar(name, func) PROCESS_A1LOCALtoA1MemNonVar_COMMON(name, func,)
  268. #define PROCESS_LOCALI1toA1_COMMON(name, func, suffix) \
  269. case OpCode::name: \
  270. { \
  271. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  272. SetReg(playout->R0, \
  273. func(this->localClosure, playout->C1)); \
  274. break; \
  275. }
  276. #define PROCESS_LOCALI1toA1(name, func) PROCESS_LOCALI1toA1_COMMON(name, func,)
  277. #define PROCESS_A1I1toA1_COMMON(name, func, suffix) \
  278. case OpCode::name: \
  279. { \
  280. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  281. SetReg(playout->R0, \
  282. func(GetReg(playout->R1), playout->C1)); \
  283. break; \
  284. }
  285. #define PROCESS_A1I1toA1(name, func) PROCESS_A1I1toA1_COMMON(name, func,)
  286. #define PROCESS_A1I1toA1Mem_COMMON(name, func, suffix) \
  287. case OpCode::name: \
  288. { \
  289. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  290. SetReg(playout->R0, \
  291. func(GetReg(playout->R1), playout->C1, GetScriptContext())); \
  292. break; \
  293. }
  294. #define PROCESS_A1I1toA1Mem(name, func) PROCESS_A1I1toA1Mem_COMMON(name, func,)
  295. #define PROCESS_RegextoA1_COMMON(name, func, suffix) \
  296. case OpCode::name: \
  297. { \
  298. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  299. SetReg(playout->R0, \
  300. func(this->m_functionBody->GetLiteralRegex(playout->C1), GetScriptContext())); \
  301. break; \
  302. }
  303. #define PROCESS_RegextoA1(name, func) PROCESS_RegextoA1_COMMON(name, func,)
  304. #define PROCESS_A2toXX_COMMON(name, func, suffix) \
  305. case OpCode::name: \
  306. { \
  307. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  308. func(GetReg(playout->R0), GetReg(playout->R1)); \
  309. break; \
  310. }
  311. #define PROCESS_A2toXX(name, func) PROCESS_A2toXX_COMMON(name, func,)
  312. #define PROCESS_A2toXXMemNonVar_COMMON(name, func, suffix) \
  313. case OpCode::name: \
  314. { \
  315. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  316. func(GetNonVarReg(playout->R0), GetNonVarReg(playout->R1), GetScriptContext()); \
  317. break; \
  318. }
  319. #define PROCESS_A2toXXMemNonVar(name, func) PROCESS_A2toXXMemNonVar_COMMON(name, func,)
  320. #define PROCESS_A1NonVarToA1_COMMON(name, func, suffix) \
  321. case OpCode::name: \
  322. { \
  323. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  324. SetReg(playout->R0, \
  325. func(GetNonVarReg(playout->R1))); \
  326. break; \
  327. }
  328. #define PROCESS_A2NonVarToA1Reg_COMMON(name, func, suffix) \
  329. case OpCode::name: \
  330. { \
  331. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  332. SetReg(playout->R0, \
  333. func(GetNonVarReg(playout->R1), playout->R2)); \
  334. break; \
  335. }
  336. #define PROCESS_A2toA1Mem_COMMON(name, func, suffix) \
  337. case OpCode::name: \
  338. { \
  339. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  340. SetReg(playout->R0, \
  341. func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext())); \
  342. break; \
  343. }
  344. #define PROCESS_A2toA1Mem(name, func) PROCESS_A2toA1Mem_COMMON(name, func,)
  345. #define PROCESS_A2toA1MemProfiled_COMMON(name, func, suffix) \
  346. case OpCode::name: \
  347. { \
  348. PROCESS_READ_LAYOUT(name, ProfiledReg3, suffix); \
  349. SetReg(playout->R0, \
  350. func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext(), playout->profileId)); \
  351. break; \
  352. }
  353. #define PROCESS_A2toA1MemProfiled(name, func) PROCESS_A2toA1MemProfiled_COMMON(name, func,)
  354. #define PROCESS_A2toA1NonVar_COMMON(name, func, suffix) \
  355. case OpCode::name: \
  356. { \
  357. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  358. SetNonVarReg(playout->R0, \
  359. func(GetNonVarReg(playout->R1), GetNonVarReg(playout->R2))); \
  360. break; \
  361. }
  362. #define PROCESS_A2toA1NonVar(name, func) PROCESS_A2toA1NonVar_COMMON(name, func,)
  363. #define PROCESS_A2toA1MemNonVar_COMMON(name, func, suffix) \
  364. case OpCode::name: \
  365. { \
  366. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  367. SetNonVarReg(playout->R0, \
  368. func(GetNonVarReg(playout->R1), GetNonVarReg(playout->R2),GetScriptContext())); \
  369. break; \
  370. }
  371. #define PROCESS_A2toA1MemNonVar(name, func) PROCESS_A2toA1MemNonVar_COMMON(name, func,)
  372. #define PROCESS_CMMem_COMMON(name, func, suffix) \
  373. case OpCode::name: \
  374. { \
  375. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  376. SetReg(playout->R0, \
  377. func(GetReg(playout->R1), GetReg(playout->R2), GetScriptContext()) ? JavascriptBoolean::OP_LdTrue(GetScriptContext()) : \
  378. JavascriptBoolean::OP_LdFalse(GetScriptContext())); \
  379. break; \
  380. }
  381. #define PROCESS_CMMem(name, func) PROCESS_CMMem_COMMON(name, func,)
  382. #define PROCESS_ELEM_RtU_to_XX_COMMON(name, func, suffix) \
  383. case OpCode::name: \
  384. { \
  385. PROCESS_READ_LAYOUT(name, ElementRootU, suffix); \
  386. func(playout->PropertyIdIndex); \
  387. break; \
  388. }
  389. #define PROCESS_ELEM_RtU_to_XX(name, func) PROCESS_ELEM_RtU_to_XX_COMMON(name, func,)
  390. #define PROCESS_ELEM_C2_to_XX_COMMON(name, func, suffix) \
  391. case OpCode::name: \
  392. { \
  393. PROCESS_READ_LAYOUT(name, ElementScopedC, suffix); \
  394. func(GetEnvForEvalCode(), playout->PropertyIdIndex, GetReg(playout->Value)); \
  395. break; \
  396. }
  397. #define PROCESS_ELEM_C2_to_XX(name, func) PROCESS_ELEM_C2_to_XX_COMMON(name, func,)
  398. #define PROCESS_GET_ELEM_SLOT_FB_COMMON(name, func, suffix) \
  399. case OpCode::name: \
  400. { \
  401. PROCESS_READ_LAYOUT(name, ElementSlot, suffix); \
  402. SetReg(playout->Value, \
  403. func((FrameDisplay*)GetNonVarReg(playout->Instance), this->m_functionBody->GetNestedFuncReference(playout->SlotIndex))); \
  404. break; \
  405. }
  406. #define PROCESS_GET_ELEM_SLOT_FB(name, func) PROCESS_GET_ELEM_SLOT_FB_COMMON(name, func,)
  407. #define PROCESS_GET_SLOT_FB_COMMON(name, func, suffix) \
  408. case OpCode::name: \
  409. { \
  410. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  411. SetReg(playout->Value, \
  412. func(this->GetFrameDisplayForNestedFunc(), this->m_functionBody->GetNestedFuncReference(playout->SlotIndex))); \
  413. break; \
  414. }
  415. #define PROCESS_GET_SLOT_FB(name, func) PROCESS_GET_SLOT_FB_COMMON(name, func,)
  416. #define PROCESS_GET_ELEM_IMem_COMMON(name, func, suffix) \
  417. case OpCode::name: \
  418. { \
  419. PROCESS_READ_LAYOUT(name, ElementI, suffix); \
  420. SetReg(playout->Value, \
  421. func(GetReg(playout->Instance), GetReg(playout->Element), GetScriptContext())); \
  422. break; \
  423. }
  424. #define PROCESS_GET_ELEM_IMem(name, func) PROCESS_GET_ELEM_IMem_COMMON(name, func,)
  425. #define PROCESS_GET_ELEM_IMem_Strict_COMMON(name, func, suffix) \
  426. case OpCode::name: \
  427. { \
  428. PROCESS_READ_LAYOUT(name, ElementI, suffix); \
  429. SetReg(playout->Value, \
  430. func(GetReg(playout->Instance), GetReg(playout->Element), GetScriptContext(), PropertyOperation_StrictMode)); \
  431. break; \
  432. }
  433. #define PROCESS_GET_ELEM_IMem_Strict(name, func) PROCESS_GET_ELEM_IMem_Strict_COMMON(name, func,)
  434. #define PROCESS_BR(name, func) \
  435. case OpCode::name: \
  436. { \
  437. PROCESS_READ_LAYOUT(name, Br,); \
  438. ip = func(playout); \
  439. break; \
  440. }
  441. #ifdef BYTECODE_BRANCH_ISLAND
  442. #define PROCESS_BRLONG(name, func) \
  443. case OpCode::name: \
  444. { \
  445. PROCESS_READ_LAYOUT(name, BrLong,); \
  446. ip = func(playout); \
  447. break; \
  448. }
  449. #endif
  450. #define PROCESS_BRS(name,func) \
  451. case OpCode::name: \
  452. { \
  453. PROCESS_READ_LAYOUT(name, BrS,); \
  454. if (func(playout->val,GetScriptContext())) \
  455. { \
  456. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  457. } \
  458. break; \
  459. }
  460. #define PROCESS_BRB_COMMON(name, func, suffix) \
  461. case OpCode::name: \
  462. { \
  463. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  464. if (func(GetReg(playout->R1))) \
  465. { \
  466. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  467. } \
  468. break; \
  469. }
  470. #define PROCESS_BRB(name, func) PROCESS_BRB_COMMON(name, func,)
  471. #define PROCESS_BRB_ALLOW_STACK_COMMON(name, func, suffix) \
  472. case OpCode::name: \
  473. { \
  474. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  475. if (func(GetRegAllowStackVar(playout->R1))) \
  476. { \
  477. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  478. } \
  479. break; \
  480. }
  481. #define PROCESS_BRB_ALLOW_STACK(name, func) PROCESS_BRB_ALLOW_STACK_COMMON(name, func,)
  482. #define PROCESS_BRBS_COMMON(name, func, suffix) \
  483. case OpCode::name: \
  484. { \
  485. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  486. if (func(GetReg(playout->R1), GetScriptContext())) \
  487. { \
  488. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  489. } \
  490. break; \
  491. }
  492. #define PROCESS_BRBS(name, func) PROCESS_BRBS_COMMON(name, func,)
  493. #define PROCESS_BRBReturnP1toA1_COMMON(name, func, suffix) \
  494. case OpCode::name: \
  495. { \
  496. PROCESS_READ_LAYOUT(name, BrReg1Unsigned1, suffix); \
  497. SetReg(playout->R1, func(GetForInEnumerator(playout->C2))); \
  498. if (!GetReg(playout->R1)) \
  499. { \
  500. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  501. } \
  502. break; \
  503. }
  504. #define PROCESS_BRBReturnP1toA1(name, func) PROCESS_BRBReturnP1toA1_COMMON(name, func,)
  505. #define PROCESS_BRBMem_ALLOW_STACK_COMMON(name, func, suffix) \
  506. case OpCode::name: \
  507. { \
  508. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  509. if (func(GetRegAllowStackVar(playout->R1),GetScriptContext())) \
  510. { \
  511. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  512. } \
  513. break; \
  514. }
  515. #define PROCESS_BRBMem_ALLOW_STACK(name, func) PROCESS_BRBMem_ALLOW_STACK_COMMON(name, func,)
  516. #define PROCESS_BRCMem_COMMON(name, func,suffix) \
  517. case OpCode::name: \
  518. { \
  519. PROCESS_READ_LAYOUT(name, BrReg2, suffix); \
  520. if (func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext())) \
  521. { \
  522. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  523. } \
  524. break; \
  525. }
  526. #define PROCESS_BRCMem(name, func) PROCESS_BRCMem_COMMON(name, func,)
  527. #define PROCESS_BRPROP(name, func) \
  528. case OpCode::name: \
  529. { \
  530. PROCESS_READ_LAYOUT(name, BrProperty,); \
  531. if (func(GetReg(playout->Instance), playout->PropertyIdIndex, GetScriptContext())) \
  532. { \
  533. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  534. } \
  535. break; \
  536. }
  537. #define PROCESS_BRLOCALPROP(name, func) \
  538. case OpCode::name: \
  539. { \
  540. PROCESS_READ_LAYOUT(name, BrLocalProperty,); \
  541. if (func(this->localClosure, playout->PropertyIdIndex, GetScriptContext())) \
  542. { \
  543. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  544. } \
  545. break; \
  546. }
  547. #define PROCESS_BRENVPROP(name, func) \
  548. case OpCode::name: \
  549. { \
  550. PROCESS_READ_LAYOUT(name, BrEnvProperty,); \
  551. if (func(LdEnv(), playout->SlotIndex, playout->PropertyIdIndex, GetScriptContext())) \
  552. { \
  553. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  554. } \
  555. break; \
  556. }
  557. #define PROCESS_W1(name, func) \
  558. case OpCode::name: \
  559. { \
  560. PROCESS_READ_LAYOUT(name, W1,); \
  561. func(playout->C1, GetScriptContext()); \
  562. break; \
  563. }
  564. #define PROCESS_U1toA1_COMMON(name, func, suffix) \
  565. case OpCode::name: \
  566. { \
  567. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  568. SetReg(playout->R0, \
  569. func(playout->C1,GetScriptContext())); \
  570. break; \
  571. }
  572. #define PROCESS_U1toA1(name, func) PROCESS_U1toA1_COMMON(name, func,)
  573. #define PROCESS_U1toA1NonVar_COMMON(name, func, suffix) \
  574. case OpCode::name: \
  575. { \
  576. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  577. SetNonVarReg(playout->R0, \
  578. func(playout->C1)); \
  579. break; \
  580. }
  581. #define PROCESS_U1toA1NonVar(name, func) PROCESS_U1toA1NonVar_COMMON(name, func,)
  582. #define PROCESS_U1toA1NonVar_FuncBody_COMMON(name, func, suffix) \
  583. case OpCode::name: \
  584. { \
  585. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  586. SetNonVarReg(playout->R0, \
  587. func(playout->C1,GetScriptContext(), this->m_functionBody)); \
  588. break; \
  589. }
  590. #define PROCESS_U1toA1NonVar_FuncBody(name, func) PROCESS_U1toA1NonVar_FuncBody_COMMON(name, func,)
  591. #define PROCESS_A1I2toXXNonVar_FuncBody(name, func) PROCESS_A1I2toXXNonVar_FuncBody_COMMON(name, func,)
  592. #define PROCESS_A1I2toXXNonVar_FuncBody_COMMON(name, func, suffix) \
  593. case OpCode::name: \
  594. { \
  595. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  596. func(playout->R0, playout->R1, playout->R2, GetScriptContext(), this->m_functionBody); \
  597. break; \
  598. }
  599. #define PROCESS_A1U1toXX_COMMON(name, func, suffix) \
  600. case OpCode::name: \
  601. { \
  602. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  603. func(GetReg(playout->R0), playout->C1); \
  604. break; \
  605. }
  606. #define PROCESS_A1U1toXX(name, func) PROCESS_A1U1toXX_COMMON(name, func,)
  607. #define PROCESS_A1U1toXXWithCache_COMMON(name, func, suffix) \
  608. case OpCode::name: \
  609. { \
  610. PROCESS_READ_LAYOUT(name, ProfiledReg1Unsigned1, suffix); \
  611. func(GetReg(playout->R0), playout->C1, playout->profileId); \
  612. break; \
  613. }
  614. #define PROCESS_A1U1toXXWithCache(name, func) PROCESS_A1U1toXXWithCache_COMMON(name, func,)
  615. #define PROCESS_EnvU1toXX_COMMON(name, func, suffix) \
  616. case OpCode::name: \
  617. { \
  618. PROCESS_READ_LAYOUT(name, Unsigned1, suffix); \
  619. func(LdEnv(), playout->C1); \
  620. break; \
  621. }
  622. #define PROCESS_EnvU1toXX(name, func) PROCESS_EnvU1toXX_COMMON(name, func,)
  623. #define PROCESS_GET_ELEM_SLOTNonVar_COMMON(name, func, layout, suffix) \
  624. case OpCode::name: \
  625. { \
  626. PROCESS_READ_LAYOUT(name, layout, suffix); \
  627. SetNonVarReg(playout->Value, func(GetNonVarReg(playout->Instance), playout)); \
  628. break; \
  629. }
  630. #define PROCESS_GET_ELEM_SLOTNonVar(name, func, layout) PROCESS_GET_ELEM_SLOTNonVar_COMMON(name, func, layout,)
  631. #define PROCESS_GET_ELEM_LOCALSLOTNonVar_COMMON(name, func, layout, suffix) \
  632. case OpCode::name: \
  633. { \
  634. PROCESS_READ_LAYOUT(name, layout, suffix); \
  635. SetNonVarReg(playout->Value, func((Var*)GetLocalClosure(), playout)); \
  636. break; \
  637. }
  638. #define PROCESS_GET_ELEM_LOCALSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_LOCALSLOTNonVar_COMMON(name, func, layout,)
  639. #define PROCESS_GET_ELEM_PARAMSLOTNonVar_COMMON(name, func, layout, suffix) \
  640. case OpCode::name: \
  641. { \
  642. PROCESS_READ_LAYOUT(name, layout, suffix); \
  643. SetNonVarReg(playout->Value, func((Var*)GetParamClosure(), playout)); \
  644. break; \
  645. }
  646. #define PROCESS_GET_ELEM_PARAMSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_PARAMSLOTNonVar_COMMON(name, func, layout,)
  647. #define PROCESS_GET_ELEM_INNERSLOTNonVar_COMMON(name, func, layout, suffix) \
  648. case OpCode::name: \
  649. { \
  650. PROCESS_READ_LAYOUT(name, layout, suffix); \
  651. SetNonVarReg(playout->Value, func(InnerScopeFromIndex(playout->SlotIndex1), playout)); \
  652. break; \
  653. }
  654. #define PROCESS_GET_ELEM_INNERSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_INNERSLOTNonVar_COMMON(name, func, layout,)
  655. #define PROCESS_GET_ELEM_ENVSLOTNonVar_COMMON(name, func, layout, suffix) \
  656. case OpCode::name: \
  657. { \
  658. PROCESS_READ_LAYOUT(name, layout, suffix); \
  659. SetNonVarReg(playout->Value, func(LdEnv(), playout)); \
  660. break; \
  661. }
  662. #define PROCESS_GET_ELEM_ENVSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_ENVSLOTNonVar_COMMON(name, func, layout,)
  663. #define PROCESS_SET_ELEM_SLOTNonVar_COMMON(name, func, suffix) \
  664. case OpCode::name: \
  665. { \
  666. PROCESS_READ_LAYOUT(name, ElementSlot, suffix); \
  667. func(GetNonVarReg(playout->Instance), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  668. break; \
  669. }
  670. #define PROCESS_SET_ELEM_SLOTNonVar(name, func) PROCESS_SET_ELEM_SLOTNonVar_COMMON(name, func,)
  671. #define PROCESS_SET_ELEM_LOCALSLOTNonVar_COMMON(name, func, suffix) \
  672. case OpCode::name: \
  673. { \
  674. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  675. func((Var*)GetLocalClosure(), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  676. break; \
  677. }
  678. #define PROCESS_SET_ELEM_LOCALSLOTNonVar(name, func) PROCESS_SET_ELEM_LOCALSLOTNonVar_COMMON(name, func,)
  679. #define PROCESS_SET_ELEM_PARAMSLOTNonVar_COMMON(name, func, suffix) \
  680. case OpCode::name: \
  681. { \
  682. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  683. func((Var*)GetParamClosure(), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  684. break; \
  685. }
  686. #define PROCESS_SET_ELEM_PARAMSLOTNonVar(name, func) PROCESS_SET_ELEM_PARAMSLOTNonVar_COMMON(name, func,); \
  687. #define PROCESS_SET_ELEM_INNERSLOTNonVar_COMMON(name, func, suffix) \
  688. case OpCode::name: \
  689. { \
  690. PROCESS_READ_LAYOUT(name, ElementSlotI2, suffix); \
  691. func(InnerScopeFromIndex(playout->SlotIndex1), playout->SlotIndex2, GetRegAllowStackVarEnableOnly(playout->Value)); \
  692. break; \
  693. }
  694. #define PROCESS_SET_ELEM_INNERSLOTNonVar(name, func) PROCESS_SET_ELEM_INNERSLOTNonVar_COMMON(name, func,)
  695. #define PROCESS_SET_ELEM_ENVSLOTNonVar_COMMON(name, func, suffix) \
  696. case OpCode::name: \
  697. { \
  698. PROCESS_READ_LAYOUT(name, ElementSlotI2, suffix); \
  699. func(LdEnv(), playout->SlotIndex1, playout->SlotIndex2, GetRegAllowStackVarEnableOnly(playout->Value)); \
  700. break; \
  701. }
  702. #define PROCESS_SET_ELEM_ENVSLOTNonVar(name, func) PROCESS_SET_ELEM_ENVSLOTNonVar_COMMON(name, func,)
  703. /*---------------------------------------------------------------------------------------------- */
  704. #define PROCESS_A3toA1Mem_COMMON(name, func, suffix) \
  705. case OpCode::name: \
  706. { \
  707. PROCESS_READ_LAYOUT(name, Reg4, suffix); \
  708. SetReg(playout->R0, \
  709. func(GetReg(playout->R1), GetReg(playout->R2), GetReg(playout->R3), GetScriptContext())); \
  710. break; \
  711. }
  712. #define PROCESS_A3toA1Mem(name, func) PROCESS_A3toA1Mem_COMMON(name, func,)
  713. /*---------------------------------------------------------------------------------------------- */
  714. #define PROCESS_A2I1toA1Mem_COMMON(name, func, suffix) \
  715. case OpCode::name: \
  716. { \
  717. PROCESS_READ_LAYOUT(name, Reg3B1, suffix); \
  718. SetReg(playout->R0, \
  719. func(GetReg(playout->R1), GetReg(playout->R2), playout->B3, GetScriptContext())); \
  720. break; \
  721. }
  722. #define PROCESS_A2I1toA1Mem(name, func) PROCESS_A2I1toA1Mem_COMMON(name, func,)
  723. /*---------------------------------------------------------------------------------------------- */
  724. #define PROCESS_A2I1toXXMem_COMMON(name, func, suffix) \
  725. case OpCode::name: \
  726. { \
  727. PROCESS_READ_LAYOUT(name, Reg2B1, suffix); \
  728. func(GetReg(playout->R0), GetReg(playout->R1), playout->B2, scriptContext); \
  729. break; \
  730. }
  731. #define PROCESS_A2I1toXXMem(name, func) PROCESS_A2I1toXXMem_COMMON(name, func,)
  732. /*---------------------------------------------------------------------------------------------- */
  733. #define PROCESS_A3I1toXXMem_COMMON(name, func, suffix) \
  734. case OpCode::name: \
  735. { \
  736. PROCESS_READ_LAYOUT(name, Reg3B1, suffix); \
  737. func(GetReg(playout->R0), GetReg(playout->R1), GetReg(playout->R2), playout->B3, scriptContext); \
  738. break; \
  739. }
  740. #define PROCESS_A3I1toXXMem(name, func) PROCESS_A3I1toXXMem_COMMON(name, func,)
  741. #if ENABLE_PROFILE_INFO
  742. #define PROCESS_IP_TARG_IMPL(name, func, layoutSize) \
  743. case OpCode::name: \
  744. { \
  745. Assert(!switchProfileMode); \
  746. ip = func<layoutSize, INTERPRETERPROFILE>(ip); \
  747. if(switchProfileMode) \
  748. { \
  749. m_reader.SetIP(ip); \
  750. return nullptr; \
  751. } \
  752. break; \
  753. }
  754. #else
  755. #define PROCESS_IP_TARG_IMPL(name, func, layoutSize) \
  756. case OpCode::name: \
  757. { \
  758. ip = func<layoutSize, INTERPRETERPROFILE>(ip); \
  759. break; \
  760. }
  761. #endif
  762. #define PROCESS_IP_TARG_COMMON(name, func, suffix) PROCESS_IP_TARG##suffix(name, func)
  763. #define PROCESS_IP_TARG_Large(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::LargeLayout)
  764. #define PROCESS_IP_TARG_Medium(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::MediumLayout)
  765. #define PROCESS_IP_TARG_Small(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::SmallLayout)
  766. #if ENABLE_TTD
  767. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  768. #define SHOULD_DO_TTD_STACK_STMT_OP(CTX) ((CTX)->ShouldPerformRecordOrReplayAction())
  769. #else
  770. #define SHOULD_DO_TTD_STACK_STMT_OP(CTX) ((CTX)->ShouldPerformRecordOrReplayDebuggerAction())
  771. #endif
  772. #endif
  773. namespace Js
  774. {
  775. Var InterpreterStackFrame::InnerScopeFromRegSlot(RegSlot reg) const
  776. {
  777. return InnerScopeFromIndex(reg - m_functionBody->GetFirstInnerScopeRegister());
  778. }
  779. Var InterpreterStackFrame::InnerScopeFromIndex(uint32 index) const
  780. {
  781. if (index >= m_functionBody->GetInnerScopeCount())
  782. {
  783. AssertMsg(false, "Illegal byte code: bad inner scope index");
  784. Js::Throw::FatalInternalError();
  785. }
  786. Assert(this->innerScopeArray != nullptr);
  787. return this->innerScopeArray[index];
  788. }
  789. void InterpreterStackFrame::SetInnerScopeFromIndex(uint32 index, Var scope)
  790. {
  791. if (index >= m_functionBody->GetInnerScopeCount())
  792. {
  793. AssertMsg(false, "Illegal byte code: bad inner scope index");
  794. Js::Throw::FatalInternalError();
  795. }
  796. Assert(this->innerScopeArray != nullptr);
  797. this->innerScopeArray[index] = scope;
  798. }
  799. const int k_stackFrameVarCount = (sizeof(InterpreterStackFrame) + sizeof(Var) - 1) / sizeof(Var);
  800. InterpreterStackFrame::Setup::Setup(Js::ScriptFunction * function, Js::Arguments& args, bool bailedOut, bool inlinee)
  801. : function(function), inParams(args.Values), inSlotsCount(args.Info.Count), executeFunction(function->GetFunctionBody()), callFlags(args.Info.Flags), bailedOutOfInlinee(inlinee), bailedOut(bailedOut)
  802. {
  803. SetupInternal();
  804. }
  805. InterpreterStackFrame::Setup::Setup(Js::ScriptFunction * function, Var * inParams, int inSlotsCount)
  806. : function(function), inParams(inParams), inSlotsCount(inSlotsCount), executeFunction(function->GetFunctionBody()), callFlags(CallFlags_None), bailedOutOfInlinee(false), bailedOut(false)
  807. {
  808. SetupInternal();
  809. }
  810. void InterpreterStackFrame::Setup::SetupInternal()
  811. {
  812. if (this->function->GetHasInlineCaches() && Js::ScriptFunctionWithInlineCache::Is(this->function))
  813. {
  814. this->inlineCaches = (void**)Js::ScriptFunctionWithInlineCache::FromVar(this->function)->GetInlineCaches();
  815. Assert(this->inlineCaches != nullptr);
  816. }
  817. else
  818. {
  819. this->inlineCaches = this->executeFunction->GetInlineCaches();
  820. }
  821. this->inlineCacheCount = this->executeFunction->GetInlineCacheCount();
  822. //
  823. // Compute the amount of memory needed on the stack:
  824. // - We compute this in 'Atoms' instead of 'bytes' to keep everything natural word aligned.
  825. //
  826. this->localCount = this->executeFunction->GetLocalsCount();
  827. uint extraVarCount = 0;
  828. #if ENABLE_PROFILE_INFO
  829. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(this->executeFunction))
  830. {
  831. extraVarCount += (sizeof(ImplicitCallFlags) * this->executeFunction->GetLoopCount() + sizeof(Var) - 1) / sizeof(Var);
  832. }
  833. #endif
  834. // If we bailed out, we will use the JIT frame's for..in enumerators
  835. uint forInVarCount = bailedOut? 0 : (this->executeFunction->GetForInLoopDepth() * (sizeof(Js::ForInObjectEnumerator) / sizeof(Var)));
  836. this->varAllocCount = k_stackFrameVarCount + localCount + this->executeFunction->GetOutParamMaxDepth() + forInVarCount +
  837. extraVarCount + this->executeFunction->GetInnerScopeCount();
  838. if (this->executeFunction->DoStackNestedFunc() && this->executeFunction->GetNestedCount() != 0)
  839. {
  840. // Track stack funcs...
  841. this->varAllocCount += (sizeof(StackScriptFunction) * this->executeFunction->GetNestedCount()) / sizeof(Var);
  842. if (!this->bailedOutOfInlinee)
  843. {
  844. // Frame display (if environment depth is statically known)...
  845. if (this->executeFunction->DoStackFrameDisplay())
  846. {
  847. uint16 envDepth = this->executeFunction->GetEnvDepth();
  848. Assert(envDepth != (uint16)-1);
  849. this->varAllocCount += sizeof(FrameDisplay) / sizeof(Var) + (envDepth + 1);
  850. }
  851. // ...and scope slots (if any)
  852. if (this->executeFunction->DoStackScopeSlots())
  853. {
  854. uint32 scopeSlots = this->executeFunction->scopeSlotArraySize;
  855. Assert(scopeSlots != 0);
  856. this->varAllocCount += scopeSlots + Js::ScopeSlots::FirstSlotIndex;
  857. }
  858. }
  859. }
  860. }
  861. InterpreterStackFrame *
  862. InterpreterStackFrame::Setup::InitializeAllocation(__in_ecount(varAllocCount) Var * allocation, bool initParams, bool profileParams, LoopHeader* loopHeaderArray, DWORD_PTR stackAddr
  863. #if DBG
  864. , Var invalidStackVar
  865. #endif
  866. )
  867. {
  868. //
  869. // Initialize the new InterpreterStackFrame instance on the program stack.
  870. //
  871. //This will fail if InterpreterStackFrame ever gets a non-empty ctor (you'll need to use
  872. //placement_new(allocation, InterpreterStackFrame) instead, though that will cause problems
  873. //if the placement_new is surrounded by a try/finally since this would mix C++/SEH exception
  874. //handling.
  875. __analysis_assume(varAllocCount >= k_stackFrameVarCount + localCount);
  876. InterpreterStackFrame* newInstance = (InterpreterStackFrame*)allocation;
  877. newInstance->scriptContext = this->executeFunction->GetScriptContext();
  878. newInstance->m_inSlotsCount = this->inSlotsCount;
  879. newInstance->m_inParams = this->inParams;
  880. newInstance->m_callFlags = this->callFlags;
  881. newInstance->m_outParams = newInstance->m_localSlots + localCount;
  882. newInstance->m_outSp = newInstance->m_outParams;
  883. newInstance->m_outSpCached = nullptr;
  884. newInstance->m_arguments = NULL;
  885. newInstance->function = this->function;
  886. newInstance->m_functionBody = this->executeFunction;
  887. newInstance->inlineCaches = this->inlineCaches;
  888. newInstance->inlineCacheCount = this->inlineCacheCount;
  889. newInstance->currentLoopNum = LoopHeader::NoLoop;
  890. newInstance->currentLoopCounter = 0;
  891. newInstance->m_flags = InterpreterStackFrameFlags_None;
  892. newInstance->closureInitDone = false;
  893. newInstance->isParamScopeDone = false;
  894. newInstance->shouldCacheSP = true;
  895. #if ENABLE_PROFILE_INFO
  896. newInstance->switchProfileMode = false;
  897. newInstance->isAutoProfiling = false;
  898. newInstance->switchProfileModeOnLoopEndNumber = 0u - 1;
  899. #endif
  900. newInstance->ehBailoutData = nullptr;
  901. newInstance->nestedTryDepth = -1;
  902. newInstance->nestedCatchDepth = -1;
  903. newInstance->nestedFinallyDepth = -1;
  904. newInstance->retOffset = 0;
  905. newInstance->localFrameDisplay = nullptr;
  906. newInstance->localClosure = nullptr;
  907. newInstance->paramClosure = nullptr;
  908. newInstance->innerScopeArray = nullptr;
  909. newInstance->m_asmJsBuffer = nullptr;
  910. #ifdef ENABLE_WASM
  911. newInstance->m_wasmMemory = nullptr;
  912. #endif
  913. Var* outparamsEnd = newInstance->m_outParams + this->executeFunction->GetOutParamMaxDepth();
  914. #if DBG
  915. newInstance->m_outParamsEnd = outparamsEnd;
  916. #endif
  917. bool doInterruptProbe = newInstance->scriptContext->GetThreadContext()->DoInterruptProbe(this->executeFunction);
  918. #if ENABLE_NATIVE_CODEGEN
  919. bool doJITLoopBody =
  920. !this->executeFunction->GetScriptContext()->GetConfig()->IsNoNative() &&
  921. !(this->executeFunction->GetHasTry() && (PHASE_OFF((Js::JITLoopBodyInTryCatchPhase), this->executeFunction) || this->executeFunction->GetHasFinally())) &&
  922. (this->executeFunction->ForceJITLoopBody() || this->executeFunction->IsJitLoopBodyPhaseEnabled()) &&
  923. !this->executeFunction->IsInDebugMode();
  924. #endif
  925. // Pick a version of the LoopBodyStart OpCode handlers that is hardcoded to do loop body JIT and
  926. // interrupt probes as needed.
  927. if (doInterruptProbe)
  928. {
  929. #if ENABLE_NATIVE_CODEGEN
  930. if (doJITLoopBody)
  931. {
  932. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<true, true>;
  933. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<true, true>;
  934. }
  935. else
  936. #endif
  937. {
  938. #if ENABLE_PROFILE_INFO
  939. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<true, false>;
  940. #endif
  941. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<true, false>;
  942. }
  943. }
  944. else
  945. {
  946. #if ENABLE_NATIVE_CODEGEN
  947. if (doJITLoopBody)
  948. {
  949. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<false, true>;
  950. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<false, true>;
  951. }
  952. else
  953. #endif
  954. {
  955. #if ENABLE_PROFILE_INFO
  956. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<false, false>;
  957. #endif
  958. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<false, false>;
  959. }
  960. }
  961. newInstance->loopHeaderArray = loopHeaderArray;
  962. newInstance->m_stackAddress = stackAddr;
  963. #if ENABLE_PROFILE_INFO
  964. // the savedLoopImplicitCallFlags is allocated at the end of the out param array
  965. newInstance->savedLoopImplicitCallFlags = nullptr;
  966. #endif
  967. char * nextAllocBytes = (char *)(outparamsEnd);
  968. // If we bailed out, we will use the JIT frame's for..in enumerators
  969. if (bailedOut || this->executeFunction->GetForInLoopDepth() == 0)
  970. {
  971. newInstance->forInObjectEnumerators = nullptr;
  972. }
  973. else
  974. {
  975. newInstance->forInObjectEnumerators = (ForInObjectEnumerator *)nextAllocBytes;
  976. nextAllocBytes += sizeof(ForInObjectEnumerator) * this->executeFunction->GetForInLoopDepth();
  977. }
  978. if (this->executeFunction->GetInnerScopeCount())
  979. {
  980. newInstance->innerScopeArray = (Var*)nextAllocBytes;
  981. nextAllocBytes += this->executeFunction->GetInnerScopeCount() * sizeof(Var);
  982. }
  983. if (this->executeFunction->DoStackNestedFunc() && this->executeFunction->GetNestedCount() != 0)
  984. {
  985. newInstance->InitializeStackFunctions((StackScriptFunction *)nextAllocBytes);
  986. nextAllocBytes = nextAllocBytes + sizeof(StackScriptFunction) * this->executeFunction->GetNestedCount();
  987. if (!this->bailedOutOfInlinee)
  988. {
  989. if (this->executeFunction->DoStackFrameDisplay())
  990. {
  991. uint16 envDepth = this->executeFunction->GetEnvDepth();
  992. Assert(envDepth != (uint16)-1);
  993. newInstance->localFrameDisplay = (FrameDisplay*)nextAllocBytes;
  994. newInstance->localFrameDisplay->SetLength(0); // Start with no scopes. It will get set in NewFrameDisplay
  995. nextAllocBytes += sizeof(FrameDisplay) + (envDepth + 1) * sizeof(Var);
  996. }
  997. if (this->executeFunction->DoStackScopeSlots())
  998. {
  999. uint32 scopeSlots = this->executeFunction->scopeSlotArraySize;
  1000. Assert(scopeSlots != 0);
  1001. ScopeSlots((Field(Var)*)nextAllocBytes).SetCount(0); // Start with count as 0. It will get set in NewScopeSlots
  1002. newInstance->localClosure = nextAllocBytes;
  1003. nextAllocBytes += (scopeSlots + ScopeSlots::FirstSlotIndex) * sizeof(Var);
  1004. }
  1005. }
  1006. }
  1007. #if ENABLE_PROFILE_INFO
  1008. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(this->executeFunction))
  1009. {
  1010. /*
  1011. __analysis_assume(varAllocCount == (k_stackFrameVarCount + localCount + executeFunction->GetOutParamMaxDepth()
  1012. + ((sizeof(ImplicitCallFlags) * executeFunction->GetLoopCount() + sizeof(Var) - 1) / sizeof(Var))));
  1013. */
  1014. newInstance->savedLoopImplicitCallFlags = (ImplicitCallFlags *)nextAllocBytes;
  1015. for (uint i = 0; i < this->executeFunction->GetLoopCount(); i++)
  1016. {
  1017. #pragma prefast(suppress:26015, "Above analysis assume doesn't work")
  1018. newInstance->savedLoopImplicitCallFlags[i] = ImplicitCall_None;
  1019. }
  1020. }
  1021. #endif
  1022. #if DBG
  1023. if (CONFIG_ISENABLED(InitializeInterpreterSlotsWithInvalidStackVarFlag))
  1024. {
  1025. // Fill the local slots with the invalid stack var so that we will crash deterministically if something goes wrong
  1026. for (uint i = 0; i < localCount; ++i)
  1027. {
  1028. newInstance->m_localSlots[i] = invalidStackVar;
  1029. }
  1030. }
  1031. else
  1032. {
  1033. memset(newInstance->m_localSlots, 0, sizeof(Js::Var) * localCount);
  1034. }
  1035. #else
  1036. if (newInstance->m_functionBody->IsInDebugMode())
  1037. {
  1038. // In the debug mode zero out the local slot, so this could prevent locals being uninitialized in the case of setNextStatement.
  1039. memset(newInstance->m_localSlots, 0, sizeof(Js::Var) * localCount);
  1040. }
  1041. // Zero out only the return slot. This is not a user local, so the byte code will not initialize
  1042. // it to "undefined". And it's not an expression temp, so, for instance, a jitted loop body may expect
  1043. // it to be valid on entry to the loop, where "valid" means either a var or null.
  1044. newInstance->SetNonVarReg(0, NULL);
  1045. #endif
  1046. // Wasm doesn't use const table
  1047. if (!executeFunction->IsWasmFunction())
  1048. {
  1049. // Initialize the low end of the local slots from the constant table.
  1050. // Skip the slot for the return value register.
  1051. this->executeFunction->InitConstantSlots(&newInstance->m_localSlots[FunctionBody::FirstRegSlot]);
  1052. }
  1053. // Set local FD/SS pointers to null until after we've successfully probed the stack in the process loop.
  1054. // That way we avoid trying to box these structures before they've been initialized in the byte code.
  1055. if (this->executeFunction->DoStackFrameDisplay())
  1056. {
  1057. newInstance->SetNonVarReg(executeFunction->GetLocalFrameDisplayRegister(), nullptr);
  1058. }
  1059. if (this->executeFunction->DoStackScopeSlots())
  1060. {
  1061. Assert(!executeFunction->HasScopeObject());
  1062. newInstance->SetNonVarReg(executeFunction->GetLocalClosureRegister(), nullptr);
  1063. }
  1064. Var *prestDest = &newInstance->m_localSlots[this->executeFunction->GetConstantCount()];
  1065. if (initParams)
  1066. {
  1067. #if ENABLE_PROFILE_INFO
  1068. Assert(!this->executeFunction->NeedEnsureDynamicProfileInfo());
  1069. #endif
  1070. if (profileParams)
  1071. {
  1072. #if ENABLE_PROFILE_INFO
  1073. Assert(this->executeFunction->HasExecutionDynamicProfileInfo());
  1074. #endif
  1075. FunctionBody* functionBody = this->executeFunction;
  1076. InitializeParams(newInstance, [functionBody](Var param, ArgSlot index)
  1077. {
  1078. #if ENABLE_PROFILE_INFO
  1079. functionBody->GetDynamicProfileInfo()->RecordParameterInfo(functionBody, index - 1, param);
  1080. #endif
  1081. }, &prestDest);
  1082. }
  1083. else
  1084. {
  1085. InitializeParams(newInstance, [](Var param, ArgSlot index) {}, &prestDest);
  1086. }
  1087. }
  1088. if (this->executeFunction->GetHasRestParameter())
  1089. {
  1090. InitializeRestParam(newInstance, prestDest);
  1091. }
  1092. Js::RegSlot envReg = executeFunction->GetEnvRegister();
  1093. if (envReg != Js::Constants::NoRegister && envReg < executeFunction->GetConstantCount())
  1094. {
  1095. Assert(this->executeFunction->GetThisRegisterForEventHandler() == Constants::NoRegister);
  1096. // The correct FD (possibly distinct from the one on the function) is passed in the constant table.
  1097. this->function->SetEnvironment((Js::FrameDisplay*)newInstance->GetNonVarReg(envReg));
  1098. }
  1099. return newInstance;
  1100. }
  1101. template <class Fn>
  1102. void InterpreterStackFrame::Setup::InitializeParams(InterpreterStackFrame * newInstance, Fn callback, Var **pprestDest)
  1103. {
  1104. ArgSlot requiredInParamCount = executeFunction->GetInParamsCount();
  1105. Assert(requiredInParamCount > 1);
  1106. if (this->inSlotsCount >= requiredInParamCount)
  1107. {
  1108. Var * pArg = &newInstance->m_localSlots[executeFunction->GetConstantCount()];
  1109. Var * paGivenSrc = this->inParams + 1;
  1110. ArgSlot paramIndex = 1;
  1111. do
  1112. {
  1113. Var src = *paGivenSrc++;
  1114. callback(src, paramIndex);
  1115. *pArg++ = src;
  1116. paramIndex++;
  1117. }
  1118. while (paramIndex < requiredInParamCount);
  1119. *pprestDest = pArg;
  1120. }
  1121. else
  1122. {
  1123. InitializeParamsAndUndef(newInstance, callback, pprestDest);
  1124. }
  1125. }
  1126. template <class Fn>
  1127. void InterpreterStackFrame::Setup::InitializeParamsAndUndef(InterpreterStackFrame * newInstance, Fn callback, Var **pprestDest)
  1128. {
  1129. Var * pArg = &newInstance->m_localSlots[executeFunction->GetConstantCount()];
  1130. Var * paGivenSrc = this->inParams + 1;
  1131. ArgSlot requiredInParamCount = executeFunction->GetInParamsCount();
  1132. ArgSlot paramIndex = 1;
  1133. while (paramIndex < this->inSlotsCount)
  1134. {
  1135. Var src = *paGivenSrc++;
  1136. callback(src, paramIndex);
  1137. *pArg++ = src;
  1138. paramIndex++;
  1139. }
  1140. Var varUndef = executeFunction->GetScriptContext()->GetLibrary()->GetUndefined();
  1141. do
  1142. {
  1143. callback(varUndef, paramIndex);
  1144. *pArg++ = varUndef;
  1145. paramIndex++;
  1146. }
  1147. while (paramIndex < requiredInParamCount);
  1148. *pprestDest = pArg;
  1149. }
  1150. void InterpreterStackFrame::Setup::InitializeRestParam(InterpreterStackFrame * newInstance, Var *dest)
  1151. {
  1152. Var *src = this->inParams + executeFunction->GetInParamsCount();
  1153. if (this->inSlotsCount > executeFunction->GetInParamsCount())
  1154. {
  1155. // Create the rest array and copy the args directly into the contiguous head segment.
  1156. int excess = this->inSlotsCount - executeFunction->GetInParamsCount();
  1157. *dest = JavascriptArray::OP_NewScArray(excess, executeFunction->GetScriptContext());
  1158. JavascriptArray *array = static_cast<JavascriptArray *>(*dest);
  1159. Field(Var)* elements = SparseArraySegment<Var>::From(array->GetHead())->elements;
  1160. CopyArray(elements, excess, src, excess);
  1161. }
  1162. else
  1163. {
  1164. // Rest is an empty array when there are no excess parameters.
  1165. *dest = JavascriptArray::OP_NewScArray(0, executeFunction->GetScriptContext());
  1166. }
  1167. }
  1168. FrameDisplay * InterpreterStackFrame::GetEnvForEvalCode()
  1169. {
  1170. FrameDisplay *pScope;
  1171. if (m_functionBody->GetIsStrictMode() && m_functionBody->GetIsGlobalFunc())
  1172. {
  1173. pScope = this->GetLocalFrameDisplay();
  1174. }
  1175. else
  1176. {
  1177. pScope = (FrameDisplay*)this->LdEnv();
  1178. }
  1179. return pScope;
  1180. }
  1181. void InterpreterStackFrame::InitializeClosures()
  1182. {
  1183. FunctionBody *executeFunction = this->function->GetFunctionBody();
  1184. Var environment;
  1185. if (executeFunction->IsParamAndBodyScopeMerged())
  1186. {
  1187. this->SetIsParamScopeDone(true);
  1188. }
  1189. RegSlot thisRegForEventHandler = executeFunction->GetThisRegisterForEventHandler();
  1190. if (thisRegForEventHandler != Constants::NoRegister)
  1191. {
  1192. Var varThis = OP_ArgIn0();
  1193. SetReg(thisRegForEventHandler, varThis);
  1194. environment = JavascriptOperators::OP_LdHandlerScope(varThis, GetScriptContext());
  1195. this->SetEnv((FrameDisplay*)environment);
  1196. }
  1197. else if (this->paramClosure != nullptr)
  1198. {
  1199. // When paramClosure is non-null we are calling this method to initialize the closure for body scope.
  1200. // In this case we have to use the param scope's closure as the parent for the body scope's frame display.
  1201. Assert(!executeFunction->IsParamAndBodyScopeMerged());
  1202. environment = this->GetLocalFrameDisplay();
  1203. }
  1204. else
  1205. {
  1206. environment = this->LdEnv();
  1207. }
  1208. Var funcExprScope = nullptr;
  1209. Js::RegSlot funcExprScopeReg = executeFunction->GetFuncExprScopeRegister();
  1210. if (funcExprScopeReg != Constants::NoRegister && this->paramClosure == nullptr)
  1211. {
  1212. // t0 = NewPseudoScope
  1213. // t1 = LdFrameDisplay t0 env
  1214. funcExprScope = JavascriptOperators::OP_NewPseudoScope(GetScriptContext());
  1215. SetReg(funcExprScopeReg, funcExprScope);
  1216. }
  1217. RegSlot closureReg = executeFunction->GetLocalClosureRegister();
  1218. if (closureReg != Js::Constants::NoRegister)
  1219. {
  1220. Assert(closureReg >= executeFunction->GetConstantCount());
  1221. if (executeFunction->HasScopeObject())
  1222. {
  1223. this->NewScopeObject();
  1224. }
  1225. else
  1226. {
  1227. this->NewScopeSlots();
  1228. }
  1229. this->SetNonVarReg(closureReg, nullptr);
  1230. }
  1231. Js::RegSlot frameDisplayReg = executeFunction->GetLocalFrameDisplayRegister();
  1232. if (frameDisplayReg != Js::Constants::NoRegister)
  1233. {
  1234. Assert(frameDisplayReg >= executeFunction->GetConstantCount());
  1235. if (funcExprScope != nullptr)
  1236. {
  1237. environment = OP_LdFrameDisplay(funcExprScope, environment, GetScriptContext());
  1238. }
  1239. if (closureReg != Js::Constants::NoRegister)
  1240. {
  1241. void *argHead = this->GetLocalClosure();
  1242. environment = this->NewFrameDisplay(argHead, environment);
  1243. }
  1244. this->SetLocalFrameDisplay((Js::FrameDisplay*)environment);
  1245. this->SetNonVarReg(frameDisplayReg, nullptr);
  1246. }
  1247. this->closureInitDone = true;
  1248. }
  1249. #ifdef _M_IX86
  1250. #ifdef ASMJS_PLAT
  1251. int InterpreterStackFrame::GetAsmJsArgSize(AsmJsCallStackLayout* stack)
  1252. {
  1253. JavascriptFunction * func = stack->functionObject;
  1254. AsmJsFunctionInfo* asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  1255. uint argSize = (uint)(asmInfo->GetArgByteSize());
  1256. argSize = ::Math::Align<int32>(argSize, 8);
  1257. // 2 * sizeof(Var) is for functionObject, and another push that DynamicInterpreterThunk does
  1258. return argSize + 2 * sizeof(Var);
  1259. }
  1260. int InterpreterStackFrame::GetDynamicRetType(AsmJsCallStackLayout* stack)
  1261. {
  1262. return GetRetType(stack->functionObject);
  1263. }
  1264. int InterpreterStackFrame::GetRetType(JavascriptFunction* func)
  1265. {
  1266. AsmJsFunctionInfo* asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  1267. return asmInfo->GetReturnType().which();
  1268. }
  1269. #ifdef ASMJS_PLAT
  1270. /*
  1271. AsmInterpreterThunk
  1272. -------------------
  1273. This is the entrypoint for all Asm Interpreter calls (external and internal)
  1274. TODO - Make this a dynamic Interpreter thunk to support ETW
  1275. Functionality:
  1276. 1) Prolog
  1277. 2) call AsmInterpreter passing the function object
  1278. 3) Get The return type
  1279. 4) Check for Double or Float return type
  1280. 5) If true then retrieve the value stored at a constant offset from the ScriptContext
  1281. 6) Get Argument Size for callee cleanup
  1282. 7) EpiLog
  1283. a) Retrieve the frame pointer
  1284. b) Store the return address in register (edx)
  1285. c) Clean the arguments based on the arguments size
  1286. d) push the return address back into the stack
  1287. */
  1288. __declspec(naked)
  1289. void InterpreterStackFrame::InterpreterAsmThunk(AsmJsCallStackLayout* layout)
  1290. {
  1291. __asm
  1292. {
  1293. //Prologue
  1294. push ebp;
  1295. mov ebp, esp;
  1296. // Allocate space to put the return value
  1297. sub esp, 16;
  1298. and esp, -16;
  1299. push esp;
  1300. push layout;
  1301. call InterpreterStackFrame::AsmJsInterpreter;
  1302. // we need to move stack around in order to do callee cleanup
  1303. // unfortunately, we don't really have enough registers to do this cleanly
  1304. //
  1305. // we are rearranging the stack from this:
  1306. // 0x14 caller push scriptArg1
  1307. // 0x10 caller push functionObject
  1308. // 0x0C DynamicInterpreterThunk return address
  1309. // 0x08 DynamicInterpreterThunk push ebp
  1310. // 0x04 DynamicInterpreterThunk push functionObject
  1311. // 0x00 InterpreterAsmThunk return address <- stack pointer
  1312. // to this:
  1313. // 0x14 DynamicInterpreterThunk return address
  1314. // 0x10 DynamicInterpreterThunk push ebp
  1315. // 0x0C InterpreterAsmThunk return address <- stack pointer
  1316. // Read return value into possible registers
  1317. movups xmm0, [esp];
  1318. mov edx, [esp + 4];
  1319. mov eax, [esp];
  1320. mov ecx, layout;
  1321. // Epilog, callee cleanup
  1322. mov esp, ebp;
  1323. pop ebp;
  1324. push eax; // save eax
  1325. push edx; // save edx
  1326. // we have to do +0x8 on all stack addresses because we saved 2 registers
  1327. push ecx; // ebp has been restored, we can't use parameters anymore
  1328. call InterpreterStackFrame::GetAsmJsArgSize;
  1329. mov ecx, eax;
  1330. lea eax, [esp + ecx * 1 + 0x8 + 0x8]; // eax will be our stack destination
  1331. mov edx, [esp + 0xC + 0x8];
  1332. mov [eax], edx; // move the dynamic interpreter thunk return location
  1333. mov edx, [esp + 0x8 + 0x8];
  1334. mov [eax - 0x4], edx; // move the dynamic interpreter thunk "push ebp" location
  1335. // skip "push functionObject"
  1336. mov edx, [esp + 0x0 + 0x8];
  1337. mov [eax - 0x8], edx; // move the return location
  1338. pop edx; // restore possible int64 return value
  1339. pop eax; // restore return value
  1340. add esp, ecx; // cleanup arguments
  1341. ret;
  1342. }
  1343. }
  1344. #endif
  1345. #endif
  1346. #endif
  1347. #if DYNAMIC_INTERPRETER_THUNK
  1348. #ifdef _M_IX86
  1349. __declspec(naked)
  1350. Var InterpreterStackFrame::DelayDynamicInterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1351. {
  1352. __asm
  1353. {
  1354. push ebp
  1355. mov ebp, esp
  1356. push [esp+8] // push function object
  1357. call InterpreterStackFrame::EnsureDynamicInterpreterThunk;
  1358. #ifdef _CONTROL_FLOW_GUARD
  1359. // verify that the call target is valid
  1360. push eax
  1361. mov ecx, eax
  1362. call[__guard_check_icall_fptr]
  1363. pop eax
  1364. #endif
  1365. pop ebp
  1366. jmp eax
  1367. }
  1368. }
  1369. #endif
  1370. #endif
  1371. #if ENABLE_PROFILE_INFO
  1372. JavascriptMethod InterpreterStackFrame::EnsureDynamicInterpreterThunk(Js::ScriptFunction * function)
  1373. {
  1374. #if DYNAMIC_INTERPRETER_THUNK
  1375. Assert(function);
  1376. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1377. JavascriptMethod entrypoint = functionBody->EnsureDynamicInterpreterThunk(function->GetFunctionEntryPointInfo());
  1378. Assert(!IsDelayDynamicInterpreterThunk(functionBody->GetDirectEntryPoint(function->GetEntryPointInfo())));
  1379. if (function->GetEntryPoint() == InterpreterStackFrame::DelayDynamicInterpreterThunk)
  1380. {
  1381. // If we are not profiling, or the function object is not cross site, this is the direct entry point.
  1382. // Change the entry point on the object
  1383. Assert(functionBody->GetDirectEntryPoint(function->GetEntryPointInfo()) == entrypoint);
  1384. function->ChangeEntryPoint(function->GetEntryPointInfo(), entrypoint);
  1385. }
  1386. // Return the original entry point to be called
  1387. return entrypoint;
  1388. #else
  1389. return function->GetEntryPoint();
  1390. #endif
  1391. }
  1392. #endif
  1393. bool InterpreterStackFrame::IsDelayDynamicInterpreterThunk(JavascriptMethod entryPoint)
  1394. {
  1395. return
  1396. #if DYNAMIC_INTERPRETER_THUNK
  1397. #if _M_X64
  1398. entryPoint == InterpreterStackFrame::AsmJsDelayDynamicInterpreterThunk ||
  1399. #endif
  1400. entryPoint == InterpreterStackFrame::DelayDynamicInterpreterThunk;
  1401. #else
  1402. false;
  1403. #endif
  1404. }
  1405. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1406. THREAD_LOCAL int InterpreterThunkStackCountTracker::s_count = 0;
  1407. #endif
  1408. #if DYNAMIC_INTERPRETER_THUNK
  1409. #pragma optimize("", off)
  1410. #ifdef ASMJS_PLAT
  1411. void InterpreterStackFrame::StaticInterpreterAsmThunk(RecyclableObject* function, ...)
  1412. {
  1413. InterpreterAsmThunk((AsmJsCallStackLayout*)&function);
  1414. }
  1415. #endif
  1416. #if !defined(_M_ARM64)
  1417. Var InterpreterStackFrame::StaticInterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1418. {
  1419. return InterpreterThunk((JavascriptCallStackLayout*)&function);
  1420. }
  1421. #else
  1422. // Language\arm64\arm64_Thunks.asm
  1423. #endif
  1424. #pragma optimize("", on)
  1425. Var InterpreterStackFrame::InterpreterThunk(JavascriptCallStackLayout* layout)
  1426. {
  1427. Js::ScriptFunction * function = Js::ScriptFunction::UnsafeFromVar(layout->functionObject);
  1428. Js::ArgumentReader args(&layout->callInfo, layout->args);
  1429. void* localReturnAddress = _ReturnAddress();
  1430. void* localAddressOfReturnAddress = _AddressOfReturnAddress();
  1431. return InterpreterHelper(function, args, localReturnAddress, localAddressOfReturnAddress);
  1432. }
  1433. #else
  1434. #pragma optimize("", off)
  1435. Var InterpreterStackFrame::InterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1436. {
  1437. ARGUMENTS(args, callInfo);
  1438. void* localReturnAddress = _ReturnAddress();
  1439. void* localAddressOfReturnAddress = _AddressOfReturnAddress();
  1440. Assert(ScriptFunction::Is(function));
  1441. return InterpreterHelper(ScriptFunction::FromVar(function), args, localReturnAddress, localAddressOfReturnAddress);
  1442. }
  1443. #pragma optimize("", on)
  1444. #endif
  1445. const bool InterpreterStackFrame::ShouldDoProfile(FunctionBody* executeFunction)
  1446. {
  1447. #if ENABLE_PROFILE_INFO
  1448. const bool doProfile = executeFunction->GetInterpreterExecutionMode(false) == ExecutionMode::ProfilingInterpreter ||
  1449. (executeFunction->IsInDebugMode() && DynamicProfileInfo::IsEnabled(executeFunction));
  1450. return doProfile;
  1451. #else
  1452. return false;
  1453. #endif
  1454. }
  1455. InterpreterStackFrame* InterpreterStackFrame::CreateInterpreterStackFrameForGenerator(ScriptFunction* function, FunctionBody* executeFunction, JavascriptGenerator* generator, bool doProfile)
  1456. {
  1457. //
  1458. // Allocate a new InterpreterStackFrame instance on the recycler heap.
  1459. // It will live with the JavascriptGenerator object.
  1460. //
  1461. ScriptContext* functionScriptContext = function->GetScriptContext();
  1462. Arguments generatorArgs = generator->GetArguments();
  1463. InterpreterStackFrame::Setup setup(function, generatorArgs);
  1464. size_t varAllocCount = setup.GetAllocationVarCount();
  1465. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  1466. DWORD_PTR stackAddr = reinterpret_cast<DWORD_PTR>(&generator); // use any stack address from this frame to ensure correct debugging functionality
  1467. LoopHeader* loopHeaderArray = executeFunction->GetHasAllocatedLoopHeaders() ? executeFunction->GetLoopHeaderArrayPtr() : nullptr;
  1468. Var* allocation = RecyclerNewPlus(functionScriptContext->GetRecycler(), varSizeInBytes, Var);
  1469. AnalysisAssert(allocation);
  1470. InterpreterStackFrame* newInstance;
  1471. #if DBG
  1472. // Allocate invalidVar on GC instead of stack since this InterpreterStackFrame will out live the current real frame
  1473. Js::RecyclableObject* invalidVar = (Js::RecyclableObject*)RecyclerNewPlusLeaf(functionScriptContext->GetRecycler(), sizeof(Js::RecyclableObject), Var);
  1474. AnalysisAssert(invalidVar);
  1475. memset(reinterpret_cast<void*>(invalidVar), 0xFE, sizeof(Js::RecyclableObject));
  1476. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns(), doProfile, loopHeaderArray, stackAddr, invalidVar);
  1477. #else
  1478. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns(), doProfile, loopHeaderArray, stackAddr);
  1479. #endif
  1480. newInstance->m_reader.Create(executeFunction);
  1481. generator->SetFrame(newInstance, varSizeInBytes);
  1482. return newInstance;
  1483. }
  1484. Var InterpreterStackFrame::InterpreterHelper(ScriptFunction* function, ArgumentReader args, void* returnAddress, void* addressOfReturnAddress, AsmJsReturnStruct* asmJsReturn)
  1485. {
  1486. const bool isAsmJs = asmJsReturn != nullptr;
  1487. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1488. // Support for simulating partially initialized interpreter stack frame.
  1489. InterpreterThunkStackCountTracker tracker;
  1490. if (CONFIG_ISENABLED(InjectPartiallyInitializedInterpreterFrameErrorFlag) &&
  1491. CONFIG_FLAG(InjectPartiallyInitializedInterpreterFrameError) == InterpreterThunkStackCountTracker::GetCount())
  1492. {
  1493. switch (CONFIG_FLAG(InjectPartiallyInitializedInterpreterFrameErrorType))
  1494. {
  1495. case 0:
  1496. DebugBreak();
  1497. break;
  1498. case 1:
  1499. Js::JavascriptError::MapAndThrowError(function->GetScriptContext(), VBSERR_InternalError);
  1500. break;
  1501. default:
  1502. DebugBreak();
  1503. }
  1504. }
  1505. #endif
  1506. ScriptContext* functionScriptContext = function->GetScriptContext();
  1507. ThreadContext * threadContext = functionScriptContext->GetThreadContext();
  1508. Assert(!threadContext->IsDisableImplicitException());
  1509. functionScriptContext->VerifyAlive(!function->IsExternal());
  1510. Assert(threadContext->IsScriptActive());
  1511. Assert(threadContext->IsInScript());
  1512. FunctionBody* executeFunction = JavascriptFunction::UnsafeFromVar(function)->GetFunctionBody();
  1513. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1514. if (!isAsmJs && executeFunction->IsInDebugMode() != functionScriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  1515. {
  1516. if (executeFunction->GetUtf8SourceInfo()->GetIsLibraryCode())
  1517. {
  1518. Assert(!executeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  1519. }
  1520. else
  1521. {
  1522. Throw::FatalInternalError();
  1523. }
  1524. }
  1525. #endif
  1526. if (executeFunction->GetInterpretedCount() == 0)
  1527. {
  1528. executeFunction->TraceInterpreterExecutionMode();
  1529. }
  1530. class AutoRestore
  1531. {
  1532. private:
  1533. ThreadContext *const threadContext;
  1534. const uint8 savedLoopDepth;
  1535. public:
  1536. AutoRestore(ThreadContext *const threadContext, FunctionBody *const executeFunction)
  1537. : threadContext(threadContext),
  1538. savedLoopDepth(threadContext->LoopDepth())
  1539. {
  1540. if (savedLoopDepth != 0 && !executeFunction->GetIsAsmJsFunction())
  1541. {
  1542. executeFunction->SetWasCalledFromLoop();
  1543. }
  1544. }
  1545. ~AutoRestore()
  1546. {
  1547. threadContext->SetLoopDepth(savedLoopDepth);
  1548. }
  1549. } autoRestore(threadContext, executeFunction);
  1550. #if ENABLE_PROFILE_INFO
  1551. DynamicProfileInfo * dynamicProfileInfo = nullptr;
  1552. const bool doProfile = ShouldDoProfile(executeFunction);
  1553. if (doProfile)
  1554. {
  1555. #if !DYNAMIC_INTERPRETER_THUNK
  1556. executeFunction->EnsureDynamicProfileInfo();
  1557. #endif
  1558. dynamicProfileInfo = executeFunction->GetDynamicProfileInfo();
  1559. threadContext->ClearImplicitCallFlags();
  1560. }
  1561. #else
  1562. const bool doProfile = false;
  1563. #endif
  1564. executeFunction->IncreaseInterpretedCount();
  1565. #ifdef BGJIT_STATS
  1566. functionScriptContext->interpretedCount++;
  1567. functionScriptContext->maxFuncInterpret = max(functionScriptContext->maxFuncInterpret, executeFunction->GetInterpretedCount());
  1568. #endif
  1569. AssertMsg(!executeFunction->IsDeferredParseFunction(),
  1570. "Non-intrinsic functions must provide byte-code to execute");
  1571. executeFunction->BeginExecution();
  1572. bool fReleaseAlloc = false;
  1573. InterpreterStackFrame* newInstance = nullptr;
  1574. if (!isAsmJs && executeFunction->IsCoroutine())
  1575. {
  1576. // If the FunctionBody is a generator then this call is being made by one of the three
  1577. // generator resuming methods: next(), throw(), or return(). They all pass the generator
  1578. // object as the first of two arguments. The real user arguments are obtained from the
  1579. // generator object. The second argument is the ResumeYieldData which is only needed
  1580. // when resuming a generator and so it only used here if a frame already exists on the
  1581. // generator object.
  1582. AssertOrFailFastMsg(args.Info.Count == 2 && ((args.Info.Flags & CallFlags_ExtraArg) == CallFlags_None), "Generator ScriptFunctions should only be invoked by generator APIs with the pair of arguments they pass in -- the generator object and a ResumeYieldData pointer");
  1583. JavascriptGenerator* generator = JavascriptGenerator::FromVar(args[0]);
  1584. newInstance = generator->GetFrame();
  1585. if (newInstance != nullptr)
  1586. {
  1587. ResumeYieldData* resumeYieldData = static_cast<ResumeYieldData*>(args[1]);
  1588. newInstance->SetNonVarReg(executeFunction->GetYieldRegister(), resumeYieldData);
  1589. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  1590. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  1591. newInstance->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  1592. }
  1593. else
  1594. {
  1595. newInstance = CreateInterpreterStackFrameForGenerator(function, executeFunction, generator, doProfile);
  1596. }
  1597. }
  1598. else
  1599. {
  1600. InterpreterStackFrame::Setup setup(function, args);
  1601. size_t varAllocCount = setup.GetAllocationVarCount();
  1602. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  1603. //
  1604. // Allocate a new InterpreterStackFrame instance on the interpreter's virtual stack.
  1605. //
  1606. DWORD_PTR stackAddr;
  1607. Var* allocation;
  1608. // If the locals area exceeds a certain limit, allocate it from a private arena rather than
  1609. // this frame. The current limit is based on an old assert on the number of locals we would allow here.
  1610. if (varAllocCount > InterpreterStackFrame::LocalsThreshold)
  1611. {
  1612. ArenaAllocator *tmpAlloc = nullptr;
  1613. fReleaseAlloc = functionScriptContext->EnsureInterpreterArena(&tmpAlloc);
  1614. allocation = (Var*)tmpAlloc->Alloc(varSizeInBytes);
  1615. stackAddr = reinterpret_cast<DWORD_PTR>(&allocation); // use a stack address so the debugger stepping logic works (step-out, for example, compares stack depths to determine when to complete the step)
  1616. }
  1617. else
  1618. {
  1619. PROBE_STACK_PARTIAL_INITIALIZED_INTERPRETER_FRAME(functionScriptContext, Js::Constants::MinStackInterpreter + varSizeInBytes);
  1620. allocation = (Var*)_alloca(varSizeInBytes);
  1621. #if DBG
  1622. memset(allocation, 0xFE, varSizeInBytes);
  1623. #endif
  1624. stackAddr = reinterpret_cast<DWORD_PTR>(allocation);
  1625. }
  1626. /*
  1627. * If the function has any loop headers, we allocate an array for the loop headers wrappers, and
  1628. * reference the wrappers in the array. We then push the pointer to the array onto the stack itself.
  1629. * We do this so that while the function is being interpreted, we don't want the jitted loop
  1630. * bodies to be collected, even if the loop body isn't being executed. The loop body will
  1631. * get collected when the function has been JITted, and when the function exits the interpreter.
  1632. * The array contains nulls if the loop body isn't jitted (or hasn't been jitted yet) but
  1633. * it's cheaper to just copy them all into the recycler array rather than just the ones that
  1634. * have been jitted.
  1635. */
  1636. LoopHeader* loopHeaderArray = nullptr;
  1637. if (executeFunction->GetHasAllocatedLoopHeaders())
  1638. {
  1639. // Loop header array is recycler allocated, so we push it on the stack
  1640. // When we scan the stack, we'll recognize it as a recycler allocated
  1641. // object, and mark it's contents and keep the individual loop header
  1642. // wrappers alive
  1643. loopHeaderArray = executeFunction->GetLoopHeaderArrayPtr();
  1644. }
  1645. #if DBG
  1646. Js::RecyclableObject * invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  1647. memset(reinterpret_cast<void*>(invalidStackVar), 0xFE, sizeof(Js::RecyclableObject));
  1648. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns() && !isAsmJs, doProfile, loopHeaderArray, stackAddr, invalidStackVar);
  1649. #else
  1650. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns() && !isAsmJs, doProfile, loopHeaderArray, stackAddr);
  1651. #endif
  1652. newInstance->m_reader.Create(executeFunction);
  1653. }
  1654. //
  1655. // Execute the function's byte-code, returning the return-value:
  1656. // - Mark that the function is current executing and may not be modified.
  1657. //
  1658. #if ENABLE_TTD
  1659. TTD::TTDExceptionFramePopper exceptionFramePopper;
  1660. if(SHOULD_DO_TTD_STACK_STMT_OP(functionScriptContext))
  1661. {
  1662. bool isInFinally = newInstance->TestFlags(Js::InterpreterStackFrameFlags_WithinFinallyBlock);
  1663. threadContext->TTDExecutionInfo->PushCallEvent(function, args.Info.Count, args.Values, isInFinally);
  1664. exceptionFramePopper.PushInfo(threadContext->TTDExecutionInfo, function);
  1665. }
  1666. #endif
  1667. Var aReturn = nullptr;
  1668. {
  1669. #ifdef ENABLE_SCRIPT_DEBUGGING
  1670. if (!isAsmJs && executeFunction->IsInDebugMode())
  1671. {
  1672. #if DYNAMIC_INTERPRETER_THUNK
  1673. PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, addressOfReturnAddress);
  1674. aReturn = newInstance->DebugProcess();
  1675. #else
  1676. aReturn = newInstance->DebugProcessThunk(_ReturnAddress(), _AddressOfReturnAddress());
  1677. #endif
  1678. }
  1679. else
  1680. #endif
  1681. {
  1682. #if DYNAMIC_INTERPRETER_THUNK
  1683. PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, addressOfReturnAddress);
  1684. aReturn = newInstance->Process();
  1685. #else
  1686. aReturn = newInstance->ProcessThunk(_ReturnAddress(), _AddressOfReturnAddress());
  1687. #endif
  1688. }
  1689. }
  1690. executeFunction->EndExecution();
  1691. #if ENABLE_TTD
  1692. if(SHOULD_DO_TTD_STACK_STMT_OP(functionScriptContext))
  1693. {
  1694. exceptionFramePopper.PopInfo();
  1695. threadContext->TTDExecutionInfo->PopCallEvent(function, aReturn);
  1696. }
  1697. #endif
  1698. #ifdef ASMJS_PLAT
  1699. if (isAsmJs)
  1700. {
  1701. asmJsReturn->i = newInstance->GetRegRawInt(0);
  1702. asmJsReturn->l = newInstance->GetRegRawInt64(0);
  1703. asmJsReturn->d = newInstance->GetRegRawDouble(0);
  1704. asmJsReturn->f = newInstance->GetRegRawFloat(0);
  1705. asmJsReturn->simd = newInstance->GetRegRawSimd(0);
  1706. }
  1707. #endif
  1708. if (fReleaseAlloc)
  1709. {
  1710. functionScriptContext->ReleaseInterpreterArena();
  1711. }
  1712. #if ENABLE_PROFILE_INFO
  1713. if (doProfile)
  1714. {
  1715. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  1716. }
  1717. #endif
  1718. return aReturn;
  1719. }
  1720. #ifdef ASMJS_PLAT
  1721. #if _M_IX86
  1722. void InterpreterStackFrame::AsmJsInterpreter(AsmJsCallStackLayout* stack, byte* retDst)
  1723. {
  1724. ScriptFunction * function = (ScriptFunction*)stack->functionObject;
  1725. Var* paramsAddr = stack->args;
  1726. int flags = CallFlags_Value;
  1727. ArgSlot nbArgs = ArgSlotMath::Add(function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetArgCount(), 1);
  1728. CallInfo callInfo((CallFlags)flags, nbArgs);
  1729. ArgumentReader args(&callInfo, paramsAddr);
  1730. void* returnAddress = _ReturnAddress();
  1731. void* addressOfReturnAddress = _AddressOfReturnAddress();
  1732. #if ENABLE_PROFILE_INFO
  1733. function->GetFunctionBody()->EnsureDynamicProfileInfo();
  1734. #endif
  1735. AsmJsReturnStruct asmJsReturn = { 0 };
  1736. InterpreterHelper(function, args, returnAddress, addressOfReturnAddress, &asmJsReturn);
  1737. //Handle return value
  1738. AsmJsRetType::Which retType = (AsmJsRetType::Which) GetRetType(function);
  1739. switch (retType)
  1740. {
  1741. #ifdef ENABLE_WASM_SIMD
  1742. case AsmJsRetType::Int32x4:
  1743. case AsmJsRetType::Bool32x4:
  1744. case AsmJsRetType::Bool16x8:
  1745. case AsmJsRetType::Bool8x16:
  1746. case AsmJsRetType::Float32x4:
  1747. case AsmJsRetType::Float64x2:
  1748. case AsmJsRetType::Int16x8:
  1749. case AsmJsRetType::Int8x16:
  1750. case AsmJsRetType::Uint32x4:
  1751. case AsmJsRetType::Uint16x8:
  1752. case AsmJsRetType::Uint8x16:
  1753. Assert(Wasm::Simd::IsEnabled());
  1754. *(AsmJsSIMDValue*)retDst = asmJsReturn.simd;
  1755. break;
  1756. #endif
  1757. // double return
  1758. case AsmJsRetType::Double:
  1759. *(double*)retDst = asmJsReturn.d;
  1760. break;
  1761. // float return
  1762. case AsmJsRetType::Float:
  1763. *(float*)retDst = asmJsReturn.f;
  1764. break;
  1765. // signed or void return
  1766. case AsmJsRetType::Signed:
  1767. case AsmJsRetType::Void:
  1768. *(int*)retDst = asmJsReturn.i;
  1769. break;
  1770. case AsmJsRetType::Int64:
  1771. *(int64*)retDst = asmJsReturn.l;
  1772. break;
  1773. default:
  1774. Assume(false);
  1775. }
  1776. }
  1777. #elif _M_X64
  1778. typedef double(*AsmJsInterpreterDoubleEP)(AsmJsCallStackLayout*, void *);
  1779. typedef float(*AsmJsInterpreterFloatEP)(AsmJsCallStackLayout*, void *);
  1780. typedef int(*AsmJsInterpreterIntEP)(AsmJsCallStackLayout*, void *);
  1781. typedef int64(*AsmJsInterpreterInt64EP)(AsmJsCallStackLayout*, void *);
  1782. void * InterpreterStackFrame::GetAsmJsInterpreterEntryPoint(AsmJsCallStackLayout* stack)
  1783. {
  1784. JavascriptFunction * function = stack->functionObject;
  1785. void * entryPoint = nullptr;
  1786. switch (function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetReturnType().which())
  1787. {
  1788. case Js::AsmJsRetType::Double:
  1789. {
  1790. entryPoint = (void*)(AsmJsInterpreterDoubleEP)Js::InterpreterStackFrame::AsmJsInterpreter < double > ;
  1791. break;
  1792. }
  1793. case Js::AsmJsRetType::Float:
  1794. {
  1795. entryPoint = (void*)(AsmJsInterpreterFloatEP)Js::InterpreterStackFrame::AsmJsInterpreter < float > ;
  1796. break;
  1797. }
  1798. case Js::AsmJsRetType::Signed:
  1799. case Js::AsmJsRetType::Void:
  1800. {
  1801. entryPoint = (void*)(AsmJsInterpreterIntEP)Js::InterpreterStackFrame::AsmJsInterpreter < int > ;
  1802. break;
  1803. }
  1804. case Js::AsmJsRetType::Int64:
  1805. {
  1806. entryPoint = (void*)(AsmJsInterpreterInt64EP)Js::InterpreterStackFrame::AsmJsInterpreter < int64 > ;
  1807. break;
  1808. }
  1809. #ifdef ENABLE_WASM_SIMD
  1810. case Js::AsmJsRetType::Int32x4:
  1811. case Js::AsmJsRetType::Bool32x4:
  1812. case Js::AsmJsRetType::Bool16x8:
  1813. case Js::AsmJsRetType::Bool8x16:
  1814. case Js::AsmJsRetType::Float32x4:
  1815. case Js::AsmJsRetType::Float64x2:
  1816. case Js::AsmJsRetType::Int16x8:
  1817. case Js::AsmJsRetType::Int8x16:
  1818. case Js::AsmJsRetType::Uint32x4:
  1819. case Js::AsmJsRetType::Uint16x8:
  1820. case Js::AsmJsRetType::Uint8x16:
  1821. {
  1822. entryPoint = (void*)Js::InterpreterStackFrame::AsmJsInterpreterSimdJs;
  1823. break;
  1824. }
  1825. #endif
  1826. default:
  1827. Assume(UNREACHED);
  1828. }
  1829. return entryPoint;
  1830. }
  1831. template<typename T>
  1832. T InterpreterStackFrame::AsmJsInterpreter(AsmJsCallStackLayout* layout)
  1833. {
  1834. Js::ScriptFunction * function = Js::ScriptFunction::FromVar(layout->functionObject);
  1835. int flags = CallFlags_Value;
  1836. ArgSlot nbArgs = ArgSlotMath::Add(function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetArgCount(), 1);
  1837. CallInfo callInfo((CallFlags)flags, nbArgs);
  1838. ArgumentReader args(&callInfo, (Var*)layout->args);
  1839. void* returnAddress = _ReturnAddress();
  1840. void* addressOfReturnAddress = _AddressOfReturnAddress();
  1841. function->GetFunctionBody()->EnsureDynamicProfileInfo();
  1842. AsmJsReturnStruct asmJsReturn = { 0 };
  1843. InterpreterHelper(function, args, returnAddress, addressOfReturnAddress, &asmJsReturn);
  1844. return asmJsReturn.GetRetVal<T>();
  1845. }
  1846. __m128 InterpreterStackFrame::AsmJsInterpreterSimdJs(AsmJsCallStackLayout* layout)
  1847. {
  1848. return AsmJsInterpreter<X86SIMDValue>(layout).m128_value;
  1849. }
  1850. #endif
  1851. #endif
  1852. ///----------------------------------------------------------------------------
  1853. ///
  1854. /// InterpreterStackFrame::SetOut()
  1855. ///
  1856. /// SetOut() change the Var value stored in the specified "out parameter"
  1857. /// register.
  1858. ///
  1859. ///----------------------------------------------------------------------------
  1860. inline void InterpreterStackFrame::SetOut(ArgSlot outRegisterID, Var aValue)
  1861. {
  1862. //
  1863. // The "out" parameter slots are located at the end of the local register range, counting
  1864. // forwards. This results in the "in" parameter slots being disjoint from the rest of the
  1865. // InterpreterStackFrame.
  1866. // ..., InterpreterStackFrame A, Locals A[], ..., Out A:0, Out A:1, Out A:2, ...
  1867. // | In B:0, In B:1, ..., InterpreterStackFrame B, Locals B[], ...
  1868. // (current 'this') |
  1869. // (new 'this' after call)
  1870. //
  1871. Assert(m_outParams + outRegisterID < m_outSp);
  1872. m_outParams[outRegisterID] = aValue;
  1873. }
  1874. inline void InterpreterStackFrame::SetOut(ArgSlot_OneByte outRegisterID, Var aValue)
  1875. {
  1876. Assert(m_outParams + outRegisterID < m_outSp);
  1877. m_outParams[outRegisterID] = aValue;
  1878. }
  1879. inline void InterpreterStackFrame::OP_SetOutAsmDb( RegSlot outRegisterID, double val )
  1880. {
  1881. Assert(m_outParams + outRegisterID < m_outSp);
  1882. m_outParams[outRegisterID] = JavascriptNumber::NewWithCheck( val, scriptContext );
  1883. }
  1884. inline void InterpreterStackFrame::OP_SetOutAsmInt( RegSlot outRegisterID, int val )
  1885. {
  1886. Assert( m_outParams + outRegisterID < m_outSp );
  1887. m_outParams[outRegisterID] = JavascriptNumber::ToVar( val, scriptContext );
  1888. }
  1889. void InterpreterStackFrame::OP_SetOutAsmFlt(RegSlot outRegisterID, float val)
  1890. {
  1891. OP_SetOutAsmDb(outRegisterID, (double)val);
  1892. }
  1893. inline void InterpreterStackFrame::OP_I_SetOutAsmFlt(RegSlot outRegisterID, float val)
  1894. {
  1895. Assert(m_outParams + outRegisterID < m_outSp);
  1896. *(float*)(&(m_outParams[outRegisterID])) = val;
  1897. }
  1898. inline void InterpreterStackFrame::OP_I_SetOutAsmLong(RegSlot outRegisterID, int64 val)
  1899. {
  1900. Assert(m_outParams + outRegisterID < m_outSp);
  1901. *(int64*)(&(m_outParams[outRegisterID])) = val;
  1902. }
  1903. inline void InterpreterStackFrame::OP_I_SetOutAsmInt(RegSlot outRegisterID, int val)
  1904. {
  1905. Assert(m_outParams + outRegisterID < m_outSp);
  1906. *(int*)(&(m_outParams[outRegisterID])) = val;
  1907. }
  1908. inline void InterpreterStackFrame::OP_I_SetOutAsmDb(RegSlot outRegisterID, double val)
  1909. {
  1910. Assert(m_outParams + outRegisterID < m_outSp);
  1911. *(double*)(&(m_outParams[outRegisterID])) = val;
  1912. }
  1913. inline void InterpreterStackFrame::OP_I_SetOutAsmSimd(RegSlot outRegisterID, AsmJsSIMDValue val)
  1914. {
  1915. Assert(m_outParams + outRegisterID < m_outSp);
  1916. *(AsmJsSIMDValue*)(&(m_outParams[outRegisterID])) = val;
  1917. }
  1918. template<int type, bool toJs>
  1919. void InterpreterStackFrame::OP_InvalidWasmTypeConversion(...)
  1920. {
  1921. #ifdef ENABLE_WASM
  1922. CompileAssert(type < Wasm::WasmTypes::Limit);
  1923. const char16* fromType = toJs ? Wasm::WasmTypes::GetTypeName(static_cast<Wasm::WasmTypes::WasmType>(type)) : _u("Javascript Variable");
  1924. const char16* toType = toJs ? _u("Javascript Variable") : Wasm::WasmTypes::GetTypeName(static_cast<Wasm::WasmTypes::WasmType>(type));
  1925. JavascriptError::ThrowTypeErrorVar(scriptContext, WASMERR_InvalidTypeConversion, fromType, toType);
  1926. #else
  1927. Assert(UNREACHED); //shouldn't get there
  1928. JavascriptError::ThrowTypeErrorVar(scriptContext, WASMERR_InvalidTypeConversion, _u("unknown"), _u("unknown")); //throw for a release build
  1929. #endif
  1930. }
  1931. // This will be called in the beginning of the try_finally.
  1932. inline void InterpreterStackFrame::CacheSp()
  1933. {
  1934. // Before caching the current m_outSp, we will be storing the previous the previously stored value in the m_outSpCached.
  1935. *m_outSp++ = (Var)m_outSpCached;
  1936. *m_outSp++ = (Var)m_outParams;
  1937. m_outSpCached = m_outSp - 2;
  1938. }
  1939. inline void InterpreterStackFrame::RestoreSp()
  1940. {
  1941. // This will be called in the Finally block to restore from the previous SP cached.
  1942. // m_outSpCached can be null if the catch block is called.
  1943. if (m_outSpCached != nullptr)
  1944. {
  1945. Assert(m_outSpCached < m_outSp);
  1946. m_outSp = m_outSpCached;
  1947. m_outSpCached = (Var*)*m_outSp;
  1948. Assert(m_outSpCached == nullptr || m_outSpCached <= m_outSp);
  1949. m_outParams = (Var*)*(m_outSp + 1);
  1950. }
  1951. else
  1952. {
  1953. ResetOut();
  1954. }
  1955. }
  1956. inline void InterpreterStackFrame::PushOut(Var aValue)
  1957. {
  1958. *m_outSp++ = aValue;
  1959. }
  1960. inline void InterpreterStackFrame::PopOut(ArgSlot argCount)
  1961. {
  1962. ArgSlotMath::Inc(argCount);
  1963. m_outSp -= argCount;
  1964. m_outParams = (Var*)*m_outSp;
  1965. AssertMsg(m_localSlots + this->m_functionBody->GetLocalsCount() <= m_outSp &&
  1966. m_outSp < (m_localSlots + this->m_functionBody->GetLocalsCount() + this->m_functionBody->GetOutParamMaxDepth()),
  1967. "out args Stack pointer not in range after Pop");
  1968. }
  1969. void InterpreterStackFrame::ResetOut()
  1970. {
  1971. //
  1972. // Reset the m_outParams and m_outSp
  1973. //
  1974. m_outParams = m_localSlots + this->m_functionBody->GetLocalsCount();
  1975. m_outSp = m_outParams;
  1976. m_outSpCached = nullptr;
  1977. }
  1978. #ifdef ENABLE_SCRIPT_DEBUGGING
  1979. _NOINLINE
  1980. Var InterpreterStackFrame::DebugProcessThunk(void* returnAddress, void* addressOfReturnAddress)
  1981. {
  1982. PushPopFrameHelper pushPopFrameHelper(this, returnAddress, addressOfReturnAddress);
  1983. return this->DebugProcess();
  1984. }
  1985. //
  1986. // Under debug mode allow the exception to be swallowed and execution to continue
  1987. // if the debugger has specified that behavior.
  1988. //
  1989. Var InterpreterStackFrame::DebugProcess()
  1990. {
  1991. Assert(this->returnAddress != nullptr);
  1992. while (true)
  1993. {
  1994. JavascriptExceptionObject *exception = nullptr;
  1995. try
  1996. {
  1997. #if ENABLE_TTD
  1998. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  1999. {
  2000. return this->ProcessWithDebugging_PreviousStmtTracking();
  2001. }
  2002. else
  2003. {
  2004. return this->ProcessWithDebugging();
  2005. }
  2006. #else
  2007. return this->ProcessWithDebugging();
  2008. #endif
  2009. }
  2010. catch (const Js::JavascriptException& err)
  2011. {
  2012. JavascriptExceptionObject *exception_ = err.GetAndClear();
  2013. Assert(exception_);
  2014. exception = exception_;
  2015. }
  2016. if (exception)
  2017. {
  2018. bool skipException = false;
  2019. if (exception != scriptContext->GetThreadContext()->GetPendingSOErrorObject()
  2020. && exception != scriptContext->GetThreadContext()->GetPendingOOMErrorObject())
  2021. {
  2022. skipException = exception->IsDebuggerSkip();
  2023. }
  2024. if (skipException)
  2025. {
  2026. // If we are going to swallow the exception then advance to the beginning of the next user statement
  2027. if (exception->IsIgnoreAdvanceToNextStatement()
  2028. || this->scriptContext->GetDebugContext()->GetProbeContainer()->AdvanceToNextUserStatement(this->m_functionBody, &this->m_reader))
  2029. {
  2030. // We must fix up the return value to at least be undefined:
  2031. this->SetReg((RegSlot)0,this->scriptContext->GetLibrary()->GetUndefined());
  2032. // If we recover from the exception, there may be a chance the out pointers in the InterpreterStackframe are not in a proper state.
  2033. // Reset them to correct the stack.
  2034. ResetOut();
  2035. // If we can successfully advance then continuing processing
  2036. continue;
  2037. }
  2038. }
  2039. JavascriptExceptionOperators::DoThrowCheckClone(exception, scriptContext);
  2040. }
  2041. }
  2042. }
  2043. #endif
  2044. template<typename OpCodeType, Js::OpCode (ReadOpFunc)(const byte*&), void (TracingFunc)(InterpreterStackFrame*, OpCodeType)>
  2045. OpCodeType InterpreterStackFrame::ReadOp(const byte *& ip)
  2046. {
  2047. #if DBG || DBG_DUMP
  2048. //
  2049. // For debugging byte-code, store the current offset before the instruction is read:
  2050. // - We convert this to "void *" to encourage the debugger to always display in hex,
  2051. // which matches the displayed offsets used by ByteCodeDumper.
  2052. //
  2053. this->DEBUG_currentByteOffset = (void *) m_reader.GetCurrentOffset();
  2054. #endif
  2055. OpCodeType op = (OpCodeType)ReadOpFunc(ip);
  2056. #if DBG_DUMP
  2057. TracingFunc(this, op);
  2058. #endif
  2059. return op;
  2060. }
  2061. void InterpreterStackFrame::TraceOpCode(InterpreterStackFrame* that, Js::OpCode op)
  2062. {
  2063. #if DBG_DUMP
  2064. that->scriptContext->byteCodeHistogram[(int)op]++;
  2065. if (PHASE_TRACE(Js::InterpreterPhase, that->m_functionBody))
  2066. {
  2067. Output::Print(_u("%d.%d:Executing %s at offset 0x%X\n"), that->m_functionBody->GetSourceContextId(), that->m_functionBody->GetLocalFunctionId(), Js::OpCodeUtil::GetOpCodeName(op), that->DEBUG_currentByteOffset);
  2068. }
  2069. #endif
  2070. }
  2071. void InterpreterStackFrame::TraceAsmJsOpCode(InterpreterStackFrame* that, Js::OpCodeAsmJs op)
  2072. {
  2073. #if DBG_DUMP && defined(ASMJS_PLAT)
  2074. if(PHASE_TRACE(Js::AsmjsInterpreterPhase, that->m_functionBody))
  2075. {
  2076. Output::Print(_u("%d.%d:Executing %s at offset 0x%X\n"), that->m_functionBody->GetSourceContextId(), that->m_functionBody->GetLocalFunctionId(), Js::OpCodeUtilAsmJs::GetOpCodeName(op), that->DEBUG_currentByteOffset);
  2077. }
  2078. #endif
  2079. }
  2080. #if ENABLE_TTD
  2081. template<typename OpCodeType, Js::OpCode(ReadOpFunc)(const byte*&), void (TracingFunc)(InterpreterStackFrame*, OpCodeType)>
  2082. OpCodeType InterpreterStackFrame::ReadOp_WPreviousStmtTracking(const byte *& ip)
  2083. {
  2084. #if DBG || DBG_DUMP
  2085. //
  2086. // For debugging byte-code, store the current offset before the instruction is read:
  2087. // - We convert this to "void *" to encourage the debugger to always display in hex,
  2088. // which matches the displayed offsets used by ByteCodeDumper.
  2089. //
  2090. this->DEBUG_currentByteOffset = (void *)m_reader.GetCurrentOffset();
  2091. #endif
  2092. #if ENABLE_TTD
  2093. AssertMsg(this->scriptContext->GetThreadContext()->IsRuntimeInTTDMode(), "We never be fetching an opcode via this path if this is not true!!!");
  2094. #endif
  2095. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  2096. {
  2097. TTD::ExecutionInfoManager* executionMgr = this->scriptContext->GetThreadContext()->TTDExecutionInfo;
  2098. executionMgr->UpdateCurrentStatementInfo(m_reader.GetCurrentOffset());
  2099. }
  2100. OpCodeType op = (OpCodeType)ReadOpFunc(ip);
  2101. #if DBG_DUMP
  2102. TracingFunc(this, op);
  2103. #endif
  2104. return op;
  2105. }
  2106. #endif
  2107. _NOINLINE
  2108. Var InterpreterStackFrame::ProcessThunk(void* address, void* addressOfReturnAddress)
  2109. {
  2110. PushPopFrameHelper pushPopFrameHelper(this, address, addressOfReturnAddress);
  2111. return this->Process();
  2112. }
  2113. #ifdef ASMJS_PLAT
  2114. Var InterpreterStackFrame::ProcessAsmJsModule()
  2115. {
  2116. FunctionBody* asmJsModuleFunctionBody = GetFunctionBody();
  2117. AsmJsModuleInfo* info = asmJsModuleFunctionBody->GetAsmJsModuleInfo();
  2118. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2119. if (Configuration::Global.flags.ForceAsmJsLinkFail)
  2120. {
  2121. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Forcing link failure"));
  2122. return this->ProcessLinkFailedAsmJsModule();
  2123. }
  2124. #endif
  2125. if (m_inSlotsCount != info->GetArgInCount() + 1)
  2126. {
  2127. // Error reparse without asm.js
  2128. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Invalid module argument count"));
  2129. return this->ProcessLinkFailedAsmJsModule();
  2130. }
  2131. const AsmJsModuleMemory& moduleMemory = info->GetModuleMemory();
  2132. Field(Var)* moduleMemoryPtr = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), moduleMemory.mMemorySize);
  2133. Field(Var)* arrayBufferPtr = moduleMemoryPtr + moduleMemory.mArrayBufferOffset;
  2134. Assert(moduleMemory.mArrayBufferOffset == AsmJsModuleMemory::MemoryTableBeginOffset);
  2135. Field(Var)* stdLibPtr = moduleMemoryPtr + moduleMemory.mStdLibOffset;
  2136. int* localIntSlots = (int*)(moduleMemoryPtr + moduleMemory.mIntOffset);
  2137. float* localFloatSlots = (float*)(moduleMemoryPtr + moduleMemory.mFloatOffset);
  2138. double* localDoubleSlots = (double*)(moduleMemoryPtr + moduleMemory.mDoubleOffset);
  2139. Field(Var)* localFunctionImports = moduleMemoryPtr + moduleMemory.mFFIOffset ;
  2140. Field(Var)* localModuleFunctions = moduleMemoryPtr + moduleMemory.mFuncOffset ;
  2141. Field(Field(Var)*)* localFunctionTables = (Field(Field(Var)*)*)(moduleMemoryPtr + moduleMemory.mFuncPtrOffset) ;
  2142. ThreadContext* threadContext = this->scriptContext->GetThreadContext();
  2143. *stdLibPtr = (m_inSlotsCount > 1) ? m_inParams[1] : nullptr;
  2144. Var foreign = (m_inSlotsCount > 2) ? m_inParams[2] : nullptr;
  2145. *arrayBufferPtr = (m_inSlotsCount > 3) ? m_inParams[3] : nullptr;
  2146. //cache the current state of the disable implicit call flag
  2147. DisableImplicitFlags prevDisableImplicitFlags = threadContext->GetDisableImplicitFlags();
  2148. ImplicitCallFlags saveImplicitcallFlags = threadContext->GetImplicitCallFlags();
  2149. // Disable implicit calls to check if any of the VarImport or Function Import leads to implicit calls
  2150. threadContext->DisableImplicitCall();
  2151. threadContext->SetImplicitCallFlags(ImplicitCallFlags::ImplicitCall_None);
  2152. bool checkParamResult = ASMLink::CheckParams(this->scriptContext, info, *stdLibPtr, foreign, *arrayBufferPtr);
  2153. if (!checkParamResult)
  2154. {
  2155. // don't need to print, because checkParams will do it for us
  2156. goto linkFailure;
  2157. }
  2158. else if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2159. {
  2160. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Params have side effects"));
  2161. return this->ProcessLinkFailedAsmJsModule();
  2162. }
  2163. // Initialize Variables
  2164. for (int i = 0; i < info->GetVarCount(); i++)
  2165. {
  2166. const auto& var = info->GetVar(i);
  2167. const AsmJsVarType type(var.type);
  2168. if (type.isInt())
  2169. {
  2170. localIntSlots[var.location] = var.initialiser.intInit;
  2171. }
  2172. else if (type.isFloat())
  2173. {
  2174. localFloatSlots[var.location] = var.initialiser.floatInit;
  2175. }
  2176. else if (type.isDouble())
  2177. {
  2178. localDoubleSlots[var.location] = var.initialiser.doubleInit;
  2179. }
  2180. else
  2181. {
  2182. Assert(UNREACHED);
  2183. }
  2184. }
  2185. // Load constant variables
  2186. for (int i = 0; i < info->GetVarImportCount(); i++)
  2187. {
  2188. const auto& import = info->GetVarImport(i);
  2189. const AsmJsVarType type(import.type);
  2190. // this might throw, but it would anyway in non-asm.js
  2191. Var value = JavascriptOperators::OP_GetProperty(foreign, import.field, scriptContext);
  2192. // check if there is implicit call and if there is implicit call then clear the disableimplicitcall flag
  2193. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2194. {
  2195. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing var import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2196. return this->ProcessLinkFailedAsmJsModule();
  2197. }
  2198. if (CONFIG_FLAG(AsmJsEdge))
  2199. {
  2200. // emscripten had a bug which caused this check to fail in some circumstances, so this check fails for some demos
  2201. if (!TaggedNumber::Is(value) && (!RecyclableObject::Is(value) || DynamicType::Is(RecyclableObject::FromVar(value)->GetTypeId())))
  2202. {
  2203. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Var import %s must be primitive"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2204. goto linkFailure;
  2205. }
  2206. }
  2207. if (type.isInt())
  2208. {
  2209. int val = JavascriptMath::ToInt32(value, scriptContext);
  2210. localIntSlots[import.location] = val;
  2211. }
  2212. else if (type.isFloat())
  2213. {
  2214. float val = (float)JavascriptConversion::ToNumber(value, scriptContext);
  2215. localFloatSlots[import.location] = val;
  2216. }
  2217. else if (type.isDouble())
  2218. {
  2219. double val = JavascriptConversion::ToNumber(value, scriptContext);
  2220. localDoubleSlots[import.location] = val;
  2221. }
  2222. // check for implicit call after converting to number
  2223. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2224. {
  2225. // Runtime error
  2226. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing var import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2227. return this->ProcessLinkFailedAsmJsModule();
  2228. }
  2229. }
  2230. // Load external functions
  2231. for (int i = 0; i < info->GetFunctionImportCount(); i++)
  2232. {
  2233. const auto& import = info->GetFunctionImport(i);
  2234. // this might throw, but it would anyway in non-asm.js
  2235. Var importFunc = JavascriptOperators::OP_GetProperty(foreign, import.field, scriptContext);
  2236. // check if there is implicit call and if there is implicit call then clear the disableimplicitcall flag
  2237. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2238. {
  2239. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing foreign function import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2240. return this->ProcessLinkFailedAsmJsModule();
  2241. }
  2242. if (!JavascriptFunction::Is(importFunc))
  2243. {
  2244. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Foreign function import %s is not a function"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2245. goto linkFailure;
  2246. }
  2247. localFunctionImports[import.location] = importFunc;
  2248. }
  2249. threadContext->SetDisableImplicitFlags(prevDisableImplicitFlags);
  2250. threadContext->SetImplicitCallFlags(saveImplicitcallFlags);
  2251. // scope
  2252. {
  2253. FrameDisplay* pDisplay = RecyclerNewPlus(scriptContext->GetRecycler(), sizeof(void*), FrameDisplay, 0);
  2254. //DynamicObject* asmModule = scriptContext->GetLibrary()->CreateObject(false, 1);
  2255. //JavascriptOperators::OP_SetProperty(asmModule, PropertyIds::module, moduleMemoryPtr, scriptContext);
  2256. //pDisplay->SetItem(0, this->function);
  2257. for (int i = 0; i < info->GetFunctionCount(); i++)
  2258. {
  2259. const auto& modFunc = info->GetFunction(i);
  2260. // TODO: add more runtime checks here
  2261. FunctionInfoPtrPtr functionInfo = m_functionBody->GetNestedFuncReference(i);
  2262. AsmJsScriptFunction* scriptFuncObj = AsmJsScriptFunction::OP_NewAsmJsFunc(pDisplay, functionInfo);
  2263. localModuleFunctions[modFunc.location] = scriptFuncObj;
  2264. if (scriptFuncObj->GetDynamicType()->GetEntryPoint() == DefaultDeferredDeserializeThunk)
  2265. {
  2266. JavascriptFunction::DeferredDeserialize(scriptFuncObj);
  2267. }
  2268. scriptFuncObj->GetDynamicType()->SetEntryPoint(AsmJsExternalEntryPoint);
  2269. scriptFuncObj->GetFunctionBody()->GetAsmJsFunctionInfo()->SetModuleFunctionBody(asmJsModuleFunctionBody);
  2270. scriptFuncObj->SetModuleEnvironment(moduleMemoryPtr);
  2271. if (!info->IsRuntimeProcessed())
  2272. {
  2273. // don't reset entrypoint upon relinking
  2274. FunctionEntryPointInfo* entrypointInfo = (FunctionEntryPointInfo*)scriptFuncObj->GetEntryPointInfo();
  2275. entrypointInfo->SetIsAsmJSFunction(true);
  2276. #if DYNAMIC_INTERPRETER_THUNK
  2277. if (!PHASE_ON1(AsmJsJITTemplatePhase))
  2278. {
  2279. entrypointInfo->jsMethod = AsmJsDefaultEntryThunk;
  2280. }
  2281. #endif
  2282. }
  2283. }
  2284. }
  2285. // Initialize function table arrays
  2286. for (int i = 0; i < info->GetFunctionTableCount(); i++)
  2287. {
  2288. const auto& modFuncTable = info->GetFunctionTable(i);
  2289. Field(Var)* funcTableArray = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), modFuncTable.size);
  2290. for (uint j = 0; j < modFuncTable.size; j++)
  2291. {
  2292. // get the module function index
  2293. const RegSlot index = modFuncTable.moduleFunctionIndex[j];
  2294. // assign the module function pointer to the array
  2295. Var functionPtr = localModuleFunctions[index];
  2296. funcTableArray[j] = functionPtr;
  2297. }
  2298. localFunctionTables[i] = funcTableArray;
  2299. }
  2300. // Do MTJRC/MAIC:0 check
  2301. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2302. if (
  2303. (PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxTemplatizedJitRunCount) == 0) ||
  2304. (!PHASE_ON1(Js::AsmJsJITTemplatePhase) && (CONFIG_FLAG(MaxAsmJsInterpreterRunCount) == 0 || CONFIG_FLAG(ForceNative)))
  2305. )
  2306. {
  2307. if (PHASE_TRACE1(AsmjsEntryPointInfoPhase))
  2308. {
  2309. Output::Print(_u("%s Scheduling For Full JIT at callcount:%d\n"), asmJsModuleFunctionBody->GetDisplayName(), 0);
  2310. Output::Flush();
  2311. }
  2312. for (int i = 0; i < info->GetFunctionCount(); i++)
  2313. {
  2314. ScriptFunction* functionObj = (ScriptFunction*)PointerValue(localModuleFunctions[i]);
  2315. AnalysisAssert(functionObj != nullptr);
  2316. // don't want to generate code for APIs like changeHeap
  2317. if (functionObj->GetEntryPoint() == Js::AsmJsExternalEntryPoint)
  2318. {
  2319. WAsmJs::JitFunctionIfReady(functionObj);
  2320. }
  2321. }
  2322. }
  2323. #endif
  2324. info->SetIsRuntimeProcessed(true);
  2325. // create export object
  2326. if (info->GetExportsCount())
  2327. {
  2328. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), info->GetExportsIdArray(),
  2329. this->GetFunctionBody()->GetObjectLiteralTypeRef(0));
  2330. for (int i = 0; i < info->GetExportsCount(); i++)
  2331. {
  2332. auto ex = info->GetExport(i);
  2333. Var func = localModuleFunctions[*ex.location];
  2334. JavascriptOperators::OP_InitProperty(newObj, *ex.id, func);
  2335. }
  2336. SetReg((RegSlot)0, newObj);
  2337. return newObj;
  2338. }
  2339. // export only 1 function
  2340. {
  2341. Var exportFunc = localModuleFunctions[info->GetExportFunctionIndex()];
  2342. SetReg((RegSlot)0, exportFunc);
  2343. return exportFunc;
  2344. }
  2345. linkFailure:
  2346. threadContext->SetDisableImplicitFlags(prevDisableImplicitFlags);
  2347. threadContext->SetImplicitCallFlags(saveImplicitcallFlags);
  2348. return this->ProcessLinkFailedAsmJsModule();
  2349. }
  2350. Var InterpreterStackFrame::ProcessLinkFailedAsmJsModule()
  2351. {
  2352. AsmJSCompiler::OutputError(this->scriptContext, _u("asm.js linking failed."));
  2353. Js::FunctionBody* asmJsModuleFunctionBody = GetFunctionBody();
  2354. AsmJsModuleInfo* info = asmJsModuleFunctionBody->GetAsmJsModuleInfo();
  2355. // do not support relinking with failed relink
  2356. if (info->IsRuntimeProcessed())
  2357. {
  2358. Js::Throw::OutOfMemory();
  2359. }
  2360. ScriptFunction * funcObj = GetJavascriptFunction();
  2361. ScriptFunction::ReparseAsmJsModule(&funcObj);
  2362. const bool doProfile =
  2363. funcObj->GetFunctionBody()->GetInterpreterExecutionMode(false) == ExecutionMode::ProfilingInterpreter ||
  2364. (funcObj->GetFunctionBody()->IsInDebugMode() && DynamicProfileInfo::IsEnabled(funcObj->GetFunctionBody()));
  2365. DynamicProfileInfo * dynamicProfileInfo = nullptr;
  2366. if (doProfile)
  2367. {
  2368. dynamicProfileInfo = funcObj->GetFunctionBody()->GetDynamicProfileInfo();
  2369. funcObj->GetScriptContext()->GetThreadContext()->ClearImplicitCallFlags();
  2370. }
  2371. // after reparsing, we want to also use a new interpreter stack frame, as it will have different characteristics than the asm.js version
  2372. InterpreterStackFrame::Setup setup(funcObj, m_inParams, m_inSlotsCount);
  2373. size_t varAllocCount = setup.GetAllocationVarCount();
  2374. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  2375. Var* allocation = nullptr;
  2376. DWORD_PTR stackAddr;
  2377. bool fReleaseAlloc = false;
  2378. if (varAllocCount > InterpreterStackFrame::LocalsThreshold)
  2379. {
  2380. ArenaAllocator *tmpAlloc = nullptr;
  2381. fReleaseAlloc = GetScriptContext()->EnsureInterpreterArena(&tmpAlloc);
  2382. allocation = (Var*)tmpAlloc->Alloc(varSizeInBytes);
  2383. // use a stack address so the debugger stepping logic works (step-out, for example, compares stack depths to determine when to complete the step)
  2384. // debugger stepping does not matter here, but it's worth being consistent with normal stack frame
  2385. stackAddr = reinterpret_cast<DWORD_PTR>(&allocation);
  2386. }
  2387. else
  2388. {
  2389. PROBE_STACK_PARTIAL_INITIALIZED_INTERPRETER_FRAME(GetScriptContext(), Js::Constants::MinStackInterpreter + varSizeInBytes);
  2390. allocation = (Var*)_alloca(varSizeInBytes);
  2391. stackAddr = reinterpret_cast<DWORD_PTR>(allocation);
  2392. }
  2393. #if DBG
  2394. Var invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  2395. memset(invalidStackVar, 0xFE, sizeof(Js::RecyclableObject));
  2396. InterpreterStackFrame * newInstance = newInstance = setup.InitializeAllocation(allocation, funcObj->GetFunctionBody()->GetHasImplicitArgIns(), doProfile, nullptr, stackAddr, invalidStackVar);
  2397. #else
  2398. InterpreterStackFrame * newInstance = newInstance = setup.InitializeAllocation(allocation, funcObj->GetFunctionBody()->GetHasImplicitArgIns(), doProfile, nullptr, stackAddr);
  2399. #endif
  2400. newInstance->m_reader.Create(funcObj->GetFunctionBody());
  2401. // now that we have set up the new frame, let's interpret it!
  2402. funcObj->GetFunctionBody()->BeginExecution();
  2403. PushPopFrameHelper pushPopFrameHelper(newInstance, this->returnAddress, this->addressOfReturnAddress);
  2404. Var retVal = newInstance->ProcessUnprofiled();
  2405. if (doProfile)
  2406. {
  2407. dynamicProfileInfo->RecordImplicitCallFlags(GetScriptContext()->GetThreadContext()->GetImplicitCallFlags());
  2408. }
  2409. if (fReleaseAlloc)
  2410. {
  2411. GetScriptContext()->ReleaseInterpreterArena();
  2412. }
  2413. return retVal;
  2414. }
  2415. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2416. int AsmJsCallDepth = 0;
  2417. #endif
  2418. // Function memory allocation should be done the same way as
  2419. // T AsmJsCommunEntryPoint(Js::ScriptFunction* func, ...) (AsmJSJitTemplate.cpp)
  2420. // update any changes there
  2421. /*
  2422. This function does the following fixup
  2423. Stack Before Stack After
  2424. ============== ================
  2425. | VarConstants | | VarConstants |
  2426. |--------------| |-----------------
  2427. | IntConstants | | IntConstants |
  2428. |--------------| | ------------ |
  2429. | FloatConst | | Int Vars+Tmps |
  2430. |--------------| |----------------|
  2431. | DoubleConst | | FloatConst |
  2432. |--------------| | ---------- |
  2433. | Var&Temps | | Flt Vars+tmps |
  2434. |==============| |----------------|
  2435. | DoubleConst |
  2436. | ----------- |
  2437. | Dbl Vars+Tmps |
  2438. ================
  2439. intSrc,FltSrc&DblSrc are pointers to the stack before the change
  2440. m_localIntSlots,m_localFloatSlots,m_localDoubleSlots are pointers to the stack after the change
  2441. */
  2442. void InterpreterStackFrame::AlignMemoryForAsmJs()
  2443. {
  2444. FunctionBody *const functionBody = GetFunctionBody();
  2445. ScriptFunction* func = GetJavascriptFunction();
  2446. uint32& callCount = ((FunctionEntryPointInfo*)func->GetEntryPointInfo())->callsCount;
  2447. WAsmJs::JitFunctionIfReady(func, ++callCount);
  2448. AsmJsFunctionInfo* info = functionBody->GetAsmJsFunctionInfo();
  2449. // The const table is copied after the FirstRegSlot
  2450. byte* constTable = (byte*)(m_localSlots + FunctionBody::FirstRegSlot);
  2451. byte* slotsStart = (byte*)m_localSlots;
  2452. // Must do in reverse order to avoid overwriting const of other type as we move things around
  2453. for (int i = WAsmJs::LIMIT - 1; i >= 0; --i)
  2454. {
  2455. WAsmJs::Types type = (WAsmJs::Types)i;
  2456. auto typeInfo = info->GetTypedSlotInfo(type);
  2457. byte* destination = slotsStart + typeInfo->byteOffset;
  2458. switch (type)
  2459. {
  2460. case WAsmJs::INT32: m_localIntSlots = (int*)destination; break;
  2461. case WAsmJs::INT64: m_localInt64Slots = (int64*)destination; break;
  2462. case WAsmJs::FLOAT32: m_localFloatSlots = (float*)destination; break;
  2463. case WAsmJs::FLOAT64: m_localDoubleSlots = (double*)destination; break;
  2464. case WAsmJs::SIMD: m_localSimdSlots = (AsmJsSIMDValue*)destination; break;
  2465. default:
  2466. CompileAssert(WAsmJs::SIMD == WAsmJs::LastType);
  2467. Assert(false);
  2468. break;
  2469. }
  2470. byte* source = constTable + typeInfo->constSrcByteOffset;
  2471. if (typeInfo->constCount > 0 && source != destination)
  2472. {
  2473. // Make sure slots are aligned for this type
  2474. Assert(::Math::Align<intptr_t>((intptr_t)destination, (intptr_t)WAsmJs::GetTypeByteSize(type)) == (intptr_t)destination);
  2475. Assert(typeInfo->constSrcByteOffset != Js::Constants::InvalidOffset);
  2476. uint constByteSize = typeInfo->constCount * WAsmJs::GetTypeByteSize(type);
  2477. memmove_s(destination, constByteSize, source, constByteSize);
  2478. }
  2479. }
  2480. // Load module environment
  2481. AsmJsScriptFunction* asmJsFunc = AsmJsScriptFunction::FromVar(this->function);
  2482. m_localSlots[AsmJsFunctionMemory::ModuleEnvRegister] = asmJsFunc->GetModuleEnvironment();
  2483. m_localSlots[AsmJsFunctionMemory::ArrayBufferRegister] = nullptr;
  2484. #ifdef ENABLE_WASM
  2485. if (WasmScriptFunction::Is(func))
  2486. {
  2487. WasmScriptFunction* wasmFunc = WasmScriptFunction::FromVar(func);
  2488. m_wasmMemory = wasmFunc->GetWebAssemblyMemory();
  2489. m_signatures = func->GetFunctionBody()->GetAsmJsFunctionInfo()->GetWebAssemblyModule()->GetSignatures();
  2490. }
  2491. else
  2492. #endif
  2493. {
  2494. m_asmJsBuffer = asmJsFunc->GetAsmJsArrayBuffer();
  2495. }
  2496. m_localSlots[AsmJsFunctionMemory::ArraySizeRegister] = 0; // do not cache ArraySize in the interpreter
  2497. m_localSlots[AsmJsFunctionMemory::ScriptContextBufferRegister] = functionBody->GetScriptContext();
  2498. int* intArg = m_localIntSlots + info->GetTypedSlotInfo(WAsmJs::INT32)->constCount;
  2499. int64* int64Arg = m_localInt64Slots + info->GetTypedSlotInfo(WAsmJs::INT64)->constCount;
  2500. double* doubleArg = m_localDoubleSlots + info->GetTypedSlotInfo(WAsmJs::FLOAT64)->constCount;
  2501. float* floatArg = m_localFloatSlots + info->GetTypedSlotInfo(WAsmJs::FLOAT32)->constCount;
  2502. #ifdef ENABLE_WASM_SIMD
  2503. AsmJsSIMDValue* simdArg = m_localSimdSlots + info->GetTypedSlotInfo(WAsmJs::SIMD)->constCount;
  2504. #endif
  2505. // Move the arguments to the right location
  2506. ArgSlot argCount = info->GetArgCount();
  2507. #if _M_X64 && _WIN32
  2508. uint homingAreaSize = 0;
  2509. #endif
  2510. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2511. const bool tracingFunc = PHASE_TRACE(AsmjsFunctionEntryPhase, functionBody);
  2512. if (tracingFunc)
  2513. {
  2514. if (AsmJsCallDepth)
  2515. {
  2516. Output::Print(_u("%*c"), AsmJsCallDepth, ' ');
  2517. }
  2518. Output::Print(_u("Executing function %s("), functionBody->GetDisplayName());
  2519. ++AsmJsCallDepth;
  2520. }
  2521. #endif
  2522. uintptr_t argAddress = (uintptr_t)m_inParams;
  2523. for (ArgSlot i = 0; i < argCount; i++)
  2524. {
  2525. #if _M_X64 && _WIN32
  2526. // 3rd Argument should be at the end of the homing area.
  2527. Assert(i != 3 || argAddress == (uintptr_t)m_inParams + homingAreaSize);
  2528. if (i < 3)
  2529. {
  2530. // for x64 we spill the first 3 floating point args below the rest of the arguments on the stack
  2531. // m_inParams will be from DynamicInterpreterThunk's frame. Floats are in InterpreterAsmThunk's frame. Stack will be set up like so:
  2532. // DIT arg2 <- first scriptArg, m_inParams points here
  2533. // DIT arg1
  2534. // padding
  2535. // IAT r9 home
  2536. // IAT r8 home
  2537. // IAT rdx home
  2538. // IAT rcx home
  2539. // IAT return address
  2540. // IAT push rbp
  2541. // IAT padding
  2542. // IAT xmm3 spill
  2543. // IAT xmm2 spill
  2544. // IAT xmm1 spill <- floatSpillAddress for arg1
  2545. #define FLOAT_SPILL_ADDRESS_OFFSET_WORDS 15
  2546. // floats are spilled as xmmwords
  2547. uintptr_t floatSpillAddress = (uintptr_t)m_inParams - MachPtr * (FLOAT_SPILL_ADDRESS_OFFSET_WORDS - 2*i);
  2548. if (info->GetArgType(i).isInt())
  2549. {
  2550. *intArg = *(int*)argAddress;
  2551. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2552. if (tracingFunc)
  2553. {
  2554. Output::Print(_u("%d, "), *intArg);
  2555. }
  2556. #endif
  2557. ++intArg;
  2558. homingAreaSize += MachPtr;
  2559. }
  2560. else if (info->GetArgType(i).isInt64())
  2561. {
  2562. *int64Arg = *(int64*)argAddress;
  2563. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2564. if (tracingFunc)
  2565. {
  2566. Output::Print(_u("%lld, "), *int64Arg);
  2567. }
  2568. #endif
  2569. ++int64Arg;
  2570. homingAreaSize += MachPtr;
  2571. }
  2572. else if (info->GetArgType(i).isFloat())
  2573. {
  2574. *floatArg = *(float*)floatSpillAddress;
  2575. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2576. if (tracingFunc)
  2577. {
  2578. Output::Print(_u("%.2f, "), *floatArg);
  2579. }
  2580. #endif
  2581. ++floatArg;
  2582. homingAreaSize += MachPtr;
  2583. }
  2584. else if (info->GetArgType(i).isDouble())
  2585. {
  2586. *doubleArg = *(double*)floatSpillAddress;
  2587. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2588. if (tracingFunc)
  2589. {
  2590. Output::Print(_u("%.2f, "), *doubleArg);
  2591. }
  2592. #endif
  2593. ++doubleArg;
  2594. homingAreaSize += MachPtr;
  2595. }
  2596. else
  2597. {
  2598. #ifdef ENABLE_WASM_SIMD
  2599. Assert(info->GetArgType(i).isSIMD());
  2600. *simdArg = *(AsmJsSIMDValue*)floatSpillAddress;
  2601. ++simdArg;
  2602. homingAreaSize += sizeof(AsmJsSIMDValue);
  2603. #else
  2604. Assert(UNREACHED);
  2605. #endif
  2606. }
  2607. if (Wasm::Simd::IsEnabled() && i == 2) // last argument ?
  2608. {
  2609. // If we have simd arguments, the homing area in m_inParams can be larger than 3 64-bit slots. This is because SIMD values are unboxed there too.
  2610. // After unboxing, the homing area is overwritten by rdx, r8 and r9, and we read/skip 64-bit slots from the homing area (argAddress += MachPtr).
  2611. // After the last argument of the 3 is read, we need to advance argAddress to skip over the possible extra space and to the start of the rest of the arguments.
  2612. argAddress = (uintptr_t)m_inParams + homingAreaSize;
  2613. }
  2614. else
  2615. {
  2616. argAddress += MachPtr;
  2617. }
  2618. }
  2619. else
  2620. #endif
  2621. if (info->GetArgType(i).isInt())
  2622. {
  2623. *intArg = *(int*)argAddress;
  2624. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2625. if (tracingFunc)
  2626. {
  2627. Output::Print(_u("%d, "), *intArg);
  2628. }
  2629. #endif
  2630. ++intArg;
  2631. argAddress += MachPtr;
  2632. }
  2633. else if (info->GetArgType(i).isInt64())
  2634. {
  2635. *int64Arg = *(int64*)argAddress;
  2636. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2637. if (tracingFunc)
  2638. {
  2639. Output::Print(_u("%lld, "), *int64Arg);
  2640. }
  2641. #endif
  2642. ++int64Arg;
  2643. argAddress += sizeof(int64);
  2644. }
  2645. else if (info->GetArgType(i).isFloat())
  2646. {
  2647. *floatArg = *(float*)argAddress;
  2648. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2649. if (tracingFunc)
  2650. {
  2651. Output::Print(_u("%.2f, "), *floatArg);
  2652. }
  2653. #endif
  2654. ++floatArg;
  2655. argAddress += MachPtr;
  2656. }
  2657. else if (info->GetArgType(i).isDouble())
  2658. {
  2659. Assert(info->GetArgType(i).isDouble());
  2660. *doubleArg = *(double*)argAddress;
  2661. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2662. if (tracingFunc)
  2663. {
  2664. Output::Print(_u("%.2f, "), *doubleArg);
  2665. }
  2666. #endif
  2667. ++doubleArg;
  2668. argAddress += sizeof(double);
  2669. }
  2670. #ifdef ENABLE_WASM_SIMD
  2671. else if (Wasm::Simd::IsEnabled() && info->GetArgType(i).isSIMD())
  2672. {
  2673. *simdArg = *(AsmJsSIMDValue*)argAddress;
  2674. ++simdArg;
  2675. argAddress += sizeof(AsmJsSIMDValue);
  2676. }
  2677. #endif
  2678. else
  2679. {
  2680. AssertMsg(UNREACHED, "Invalid function arg type.");
  2681. }
  2682. }
  2683. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2684. if (tracingFunc)
  2685. {
  2686. Output::Print(_u("){\n"));
  2687. Output::Flush();
  2688. }
  2689. #endif
  2690. }
  2691. #endif
  2692. ///----------------------------------------------------------------------------
  2693. ///
  2694. /// InterpreterStackFrame::Process
  2695. ///
  2696. /// Process() processes a single loop of execution for the current
  2697. /// JavascriptFunction being executed:
  2698. /// - Individual instructions are dispatched to specific handlers for different
  2699. /// OpCodes.
  2700. ///
  2701. ///----------------------------------------------------------------------------
  2702. #if ENABLE_PROFILE_INFO
  2703. #define INTERPRETERLOOPNAME ProcessProfiled
  2704. #define PROVIDE_INTERPRETERPROFILE
  2705. #include "InterpreterLoop.inl"
  2706. #undef PROVIDE_INTERPRETERPROFILE
  2707. #undef INTERPRETERLOOPNAME
  2708. #endif
  2709. #define INTERPRETERLOOPNAME ProcessUnprofiled
  2710. #include "InterpreterLoop.inl"
  2711. #undef INTERPRETERLOOPNAME
  2712. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2713. #define PROVIDE_INTERPRETER_STMTS
  2714. #define INTERPRETERLOOPNAME ProcessUnprofiled_PreviousStmtTracking
  2715. #include "InterpreterLoop.inl"
  2716. #undef INTERPRETERLOOPNAME
  2717. #undef PROVIDE_INTERPRETER_STMTS
  2718. #endif
  2719. #ifdef ASMJS_PLAT
  2720. #define INTERPRETERLOOPNAME ProcessAsmJs
  2721. #define INTERPRETER_ASMJS
  2722. #include "InterpreterProcessOpCodeAsmJs.h"
  2723. #include "InterpreterLoop.inl"
  2724. #undef INTERPRETER_ASMJS
  2725. #undef INTERPRETERLOOPNAME
  2726. #endif
  2727. // For now, always collect profile data when debugging,
  2728. // otherwise the backend will be confused if there's no profile data.
  2729. #ifdef ENABLE_SCRIPT_DEBUGGING
  2730. #define INTERPRETERLOOPNAME ProcessWithDebugging
  2731. #define PROVIDE_DEBUGGING
  2732. #if ENABLE_PROFILE_INFO
  2733. #define PROVIDE_INTERPRETERPROFILE
  2734. #endif
  2735. #include "InterpreterLoop.inl"
  2736. #if ENABLE_PROFILE_INFO
  2737. #undef PROVIDE_INTERPRETERPROFILE
  2738. #endif
  2739. #undef PROVIDE_DEBUGGING
  2740. #undef INTERPRETERLOOPNAME
  2741. #endif
  2742. #if ENABLE_TTD
  2743. #define PROVIDE_INTERPRETER_STMTS
  2744. #define INTERPRETERLOOPNAME ProcessWithDebugging_PreviousStmtTracking
  2745. #define PROVIDE_DEBUGGING
  2746. #if ENABLE_PROFILE_INFO
  2747. #define PROVIDE_INTERPRETERPROFILE
  2748. #endif
  2749. #include "InterpreterLoop.inl"
  2750. #if ENABLE_PROFILE_INFO
  2751. #undef PROVIDE_INTERPRETERPROFILE
  2752. #endif
  2753. #undef PROVIDE_DEBUGGING
  2754. #undef INTERPRETERLOOPNAME
  2755. #undef PROVIDE_INTERPRETER_STMTS
  2756. #endif
  2757. Var InterpreterStackFrame::Process()
  2758. {
  2759. #if ENABLE_PROFILE_INFO
  2760. class AutoRestore
  2761. {
  2762. private:
  2763. InterpreterStackFrame *const interpreterStackFrame;
  2764. const uint32 savedSwitchProfileModeOnLoopEndNumber;
  2765. const bool savedIsAutoProfiling;
  2766. const bool savedSwitchProfileMode;
  2767. public:
  2768. AutoRestore(InterpreterStackFrame *const interpreterStackFrame)
  2769. : interpreterStackFrame(interpreterStackFrame),
  2770. savedIsAutoProfiling(interpreterStackFrame->isAutoProfiling),
  2771. savedSwitchProfileMode(interpreterStackFrame->switchProfileMode),
  2772. savedSwitchProfileModeOnLoopEndNumber(interpreterStackFrame->switchProfileModeOnLoopEndNumber)
  2773. {
  2774. }
  2775. ~AutoRestore()
  2776. {
  2777. interpreterStackFrame->isAutoProfiling = savedIsAutoProfiling;
  2778. interpreterStackFrame->switchProfileMode = savedSwitchProfileMode;
  2779. interpreterStackFrame->switchProfileModeOnLoopEndNumber = savedSwitchProfileModeOnLoopEndNumber;
  2780. }
  2781. } autoRestore(this);
  2782. #endif
  2783. if (this->ehBailoutData && !this->TestFlags(InterpreterStackFrameFlags_FromBailOutInInlinee))
  2784. {
  2785. if (this->TestFlags(Js::InterpreterStackFrameFlags_FromBailOut) && !this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutFromEHCode))
  2786. {
  2787. this->OrFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutFromEHCode);
  2788. EHBailoutData * topLevelEHBailoutData = this->ehBailoutData;
  2789. while (topLevelEHBailoutData->parent->nestingDepth != -1)
  2790. {
  2791. topLevelEHBailoutData->parent->child = topLevelEHBailoutData;
  2792. topLevelEHBailoutData = topLevelEHBailoutData->parent;
  2793. }
  2794. ProcessTryHandlerBailout(topLevelEHBailoutData, this->ehBailoutData->nestingDepth);
  2795. this->ClearFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutFromEHCode);
  2796. this->ehBailoutData = nullptr;
  2797. }
  2798. }
  2799. #ifdef ASMJS_PLAT
  2800. if( GetFunctionBody()->GetIsAsmjsMode() )
  2801. {
  2802. FunctionBody *const functionBody = GetFunctionBody();
  2803. AsmJsFunctionInfo* asmInfo = functionBody->GetAsmJsFunctionInfo();
  2804. if (asmInfo)
  2805. {
  2806. AlignMemoryForAsmJs();
  2807. Var returnVar = ProcessAsmJs();
  2808. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2809. if( PHASE_TRACE( AsmjsFunctionEntryPhase, functionBody ) )
  2810. {
  2811. --AsmJsCallDepth;
  2812. if( AsmJsCallDepth )
  2813. {
  2814. Output::Print( _u("%*c}"), AsmJsCallDepth, ' ' );
  2815. }
  2816. else
  2817. {
  2818. Output::Print( _u("}") );
  2819. }
  2820. switch( asmInfo->GetReturnType().which() )
  2821. {
  2822. case AsmJsRetType::Void:
  2823. break;
  2824. case AsmJsRetType::Signed:
  2825. Output::Print( _u(" = %d"), m_localIntSlots[0] );
  2826. break;
  2827. case AsmJsRetType::Int64:
  2828. Output::Print( _u(" = %lld"), m_localInt64Slots[0] );
  2829. break;
  2830. case AsmJsRetType::Float:
  2831. Output::Print(_u(" = %.4f"), m_localFloatSlots[0]);
  2832. break;
  2833. case AsmJsRetType::Double:
  2834. Output::Print( _u(" = %.4f"), m_localDoubleSlots[0]);
  2835. break;
  2836. default:
  2837. break;
  2838. }
  2839. Output::Print( _u(";\n") );
  2840. Output::Flush();
  2841. }
  2842. #endif
  2843. return returnVar;
  2844. }
  2845. else
  2846. {
  2847. Assert(functionBody->GetAsmJsModuleInfo());
  2848. return ProcessAsmJsModule();
  2849. }
  2850. }
  2851. #endif
  2852. #if ENABLE_PROFILE_INFO
  2853. switchProfileMode = false;
  2854. switchProfileModeOnLoopEndNumber = 0u - 1;
  2855. #endif
  2856. #if ENABLE_PROFILE_INFO
  2857. FunctionBody *const functionBody = GetFunctionBody();
  2858. const ExecutionMode interpreterExecutionMode =
  2859. functionBody->GetInterpreterExecutionMode(TestFlags(InterpreterStackFrameFlags_FromBailOut));
  2860. if(interpreterExecutionMode == ExecutionMode::ProfilingInterpreter)
  2861. {
  2862. #if ENABLE_TTD
  2863. AssertMsg(!SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext), "We should have pinned into Interpreter mode in this case!!!");
  2864. #endif
  2865. isAutoProfiling = false;
  2866. return ProcessProfiled();
  2867. }
  2868. Assert(
  2869. interpreterExecutionMode == ExecutionMode::Interpreter ||
  2870. interpreterExecutionMode == ExecutionMode::AutoProfilingInterpreter);
  2871. isAutoProfiling = interpreterExecutionMode == ExecutionMode::AutoProfilingInterpreter;
  2872. Var result;
  2873. while(true)
  2874. {
  2875. Assert(!switchProfileMode);
  2876. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2877. if(this->scriptContext->ShouldPerformRecordOrReplayAction())
  2878. {
  2879. result = ProcessUnprofiled_PreviousStmtTracking();
  2880. }
  2881. else
  2882. {
  2883. result = ProcessUnprofiled();
  2884. }
  2885. #else
  2886. result = ProcessUnprofiled();
  2887. #endif
  2888. Assert(!(switchProfileMode && result));
  2889. if(switchProfileMode)
  2890. {
  2891. switchProfileMode = false;
  2892. }
  2893. else
  2894. {
  2895. break;
  2896. }
  2897. Assert(isAutoProfiling);
  2898. #if DBG_DUMP
  2899. if(PHASE_TRACE(InterpreterAutoProfilePhase, functionBody))
  2900. {
  2901. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2902. Output::Print(_u("InterpreterAutoProfile - Func %s - Started profiling\n"), functionBody->GetDebugNumberSet(debugStringBuffer));
  2903. Output::Flush();
  2904. }
  2905. #endif
  2906. Assert(!switchProfileMode);
  2907. result = ProcessProfiled();
  2908. Assert(!(switchProfileMode && result));
  2909. if(switchProfileMode)
  2910. {
  2911. switchProfileMode = false;
  2912. }
  2913. else
  2914. {
  2915. break;
  2916. }
  2917. Assert(isAutoProfiling);
  2918. #if DBG_DUMP
  2919. if(PHASE_TRACE(InterpreterAutoProfilePhase, functionBody))
  2920. {
  2921. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2922. Output::Print(_u("InterpreterAutoProfile - Func %s - Stopped profiling\n"), functionBody->GetDebugNumberSet(debugStringBuffer));
  2923. Output::Flush();
  2924. }
  2925. #endif
  2926. }
  2927. return result;
  2928. #else
  2929. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2930. if(this->scriptContext->ShouldPerformRecordOrReplayAction())
  2931. {
  2932. return ProcessUnprofiled_PreviousStmtTracking();
  2933. }
  2934. else
  2935. {
  2936. return ProcessUnprofiled();
  2937. }
  2938. #else
  2939. return ProcessUnprofiled();
  2940. #endif
  2941. #endif
  2942. }
  2943. template <class T>
  2944. void InterpreterStackFrame::OP_GetMethodProperty(unaligned T *playout)
  2945. {
  2946. Var varInstance = GetReg(playout->Instance);
  2947. OP_GetMethodProperty(varInstance, playout);
  2948. }
  2949. template <class T>
  2950. void InterpreterStackFrame::OP_GetLocalMethodProperty(unaligned T *playout)
  2951. {
  2952. OP_GetMethodProperty(this->localClosure, playout);
  2953. }
  2954. template <class T>
  2955. void InterpreterStackFrame::OP_GetMethodProperty(Var varInstance, unaligned T *playout)
  2956. {
  2957. #if ENABLE_COPYONACCESS_ARRAY
  2958. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(varInstance);
  2959. #endif
  2960. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  2961. RecyclableObject* obj = JavascriptOperators::TryFromVar<RecyclableObject>(varInstance);
  2962. if (obj)
  2963. {
  2964. ScriptFunction *fn = JavascriptOperators::TryFromVar<ScriptFunction>(obj);
  2965. if ((propertyId == PropertyIds::apply || propertyId == PropertyIds::call) && fn)
  2966. {
  2967. // If the property being loaded is "apply"/"call", make an optimistic assumption that apply/call is not overridden and
  2968. // undefer the function right here if it was defer parsed before. This is required so that the load of "apply"/"call"
  2969. // happens from the same "type". Otherwise, we will have a polymorphic cache for load of "apply"/"call".
  2970. if(fn->GetType()->GetEntryPoint() == JavascriptFunction::DeferredParsingThunk)
  2971. {
  2972. JavascriptFunction::DeferredParse(&fn);
  2973. }
  2974. }
  2975. }
  2976. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  2977. PropertyValueInfo info;
  2978. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  2979. Var aValue;
  2980. if (obj &&
  2981. CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false>(
  2982. obj, false, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  2983. {
  2984. SetReg(playout->Value, aValue);
  2985. return;
  2986. }
  2987. OP_GetMethodProperty_NoFastPath(varInstance, playout);
  2988. }
  2989. template <class T>
  2990. _NOINLINE void InterpreterStackFrame::OP_GetMethodProperty_NoFastPath(Var instance, unaligned T *playout)
  2991. {
  2992. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  2993. Var value = JavascriptOperators::PatchGetMethod<false>(
  2994. GetFunctionBody(),
  2995. GetInlineCache(playout->inlineCacheIndex),
  2996. playout->inlineCacheIndex,
  2997. instance,
  2998. propertyId
  2999. );
  3000. #ifdef TELEMETRY_INTERPRETER
  3001. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3002. {
  3003. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3004. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(instance, propertyId, value, true);
  3005. }
  3006. #endif
  3007. SetReg(playout->Value, value);
  3008. }
  3009. template <class T>
  3010. void InterpreterStackFrame::OP_GetRootMethodProperty(unaligned T *playout)
  3011. {
  3012. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  3013. Js::Var instance = this->GetRootObject();
  3014. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3015. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3016. DynamicObject *obj = DynamicObject::UnsafeFromVar(instance);
  3017. PropertyValueInfo info;
  3018. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3019. Var aValue;
  3020. if (CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false>(
  3021. obj, true, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  3022. {
  3023. SetReg(playout->Value, aValue);
  3024. return;
  3025. }
  3026. OP_GetRootMethodProperty_NoFastPath(playout);
  3027. }
  3028. template <class T>
  3029. _NOINLINE void InterpreterStackFrame::OP_GetRootMethodProperty_NoFastPath(unaligned T *playout)
  3030. {
  3031. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3032. Var rootInstance = this->GetRootObject();
  3033. Var value = JavascriptOperators::PatchGetRootMethod<false>(
  3034. GetFunctionBody(),
  3035. GetInlineCache(playout->inlineCacheIndex),
  3036. playout->inlineCacheIndex,
  3037. DynamicObject::UnsafeFromVar(rootInstance),
  3038. propertyId
  3039. );
  3040. #ifdef TELEMETRY_INTERPRETER
  3041. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3042. {
  3043. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3044. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(rootInstance, propertyId, value, true);
  3045. }
  3046. #endif
  3047. SetReg(playout->Value, value);
  3048. }
  3049. template <class T>
  3050. void InterpreterStackFrame::OP_GetMethodPropertyScoped(unaligned T *playout)
  3051. {
  3052. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3053. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3054. threadContext->ClearImplicitCallFlags();
  3055. Var varInstance = GetReg(playout->Instance);
  3056. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3057. RecyclableObject* obj = NULL;
  3058. if (RecyclableObject::Is(varInstance))
  3059. {
  3060. obj = RecyclableObject::FromVar(varInstance);
  3061. }
  3062. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3063. PropertyValueInfo info;
  3064. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3065. Var aValue;
  3066. if (obj &&
  3067. CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false>(
  3068. obj, false, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  3069. {
  3070. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3071. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3072. SetReg(playout->Value, aValue);
  3073. return;
  3074. }
  3075. OP_GetMethodPropertyScoped_NoFastPath(playout);
  3076. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3077. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3078. }
  3079. template <class T>
  3080. _NOINLINE void InterpreterStackFrame::OP_GetMethodPropertyScoped_NoFastPath(unaligned T *playout)
  3081. {
  3082. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3083. Js::Var instance = GetReg(playout->Instance);
  3084. Js::Var value = JavascriptOperators::PatchScopedGetMethod<false>(
  3085. GetFunctionBody(),
  3086. GetInlineCache(playout->inlineCacheIndex),
  3087. playout->inlineCacheIndex,
  3088. instance,
  3089. propertyId
  3090. );
  3091. SetReg(playout->Value, value);
  3092. #ifdef TELEMETRY_INTERPRETER
  3093. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3094. {
  3095. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3096. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(instance, propertyId, value, true);
  3097. }
  3098. #endif
  3099. }
  3100. template <class T>
  3101. void InterpreterStackFrame::OP_ProfiledGetMethodProperty(unaligned T *playout)
  3102. {
  3103. ProfiledGetProperty<T, false, true, false>(playout, GetReg(playout->Instance));
  3104. }
  3105. template <class T>
  3106. void InterpreterStackFrame::OP_ProfiledGetLocalMethodProperty(unaligned T *playout)
  3107. {
  3108. ProfiledGetProperty<T, false, true, false>(playout, this->localClosure);
  3109. }
  3110. template <class T>
  3111. void InterpreterStackFrame::OP_ProfiledGetRootMethodProperty(unaligned T *playout)
  3112. {
  3113. ProfiledGetProperty<T, true, true, false>(playout, GetRootObject());
  3114. }
  3115. RecyclableObject *
  3116. InterpreterStackFrame::OP_CallGetFunc(Var target)
  3117. {
  3118. return JavascriptOperators::GetCallableObjectOrThrow(target, GetScriptContext());
  3119. }
  3120. void InterpreterStackFrame::OP_AsmStartCall( const unaligned OpLayoutStartCall * playout )
  3121. {
  3122. OP_StartCall( playout->ArgCount/sizeof(Var) );
  3123. m_outParams[0] = scriptContext->GetLibrary()->GetUndefined();
  3124. }
  3125. void InterpreterStackFrame::OP_StartCall(const unaligned OpLayoutStartCall * playout)
  3126. {
  3127. OP_StartCall(playout->ArgCount);
  3128. }
  3129. void InterpreterStackFrame::OP_StartCall(uint outParamCount)
  3130. {
  3131. // Save the outParams for the current callsite on the outparam stack
  3132. PushOut(m_outParams);
  3133. // Update outParams for the indicated callsite
  3134. m_outParams = m_outSp;
  3135. m_outSp += outParamCount;
  3136. AssertMsg(m_localSlots + this->m_functionBody->GetLocalsCount() < m_outSp &&
  3137. m_outSp <= (m_localSlots + this->m_functionBody->GetLocalsCount() + this->m_functionBody->GetOutParamMaxDepth()),
  3138. "out args Stack pointer not in range after Push");
  3139. }
  3140. #ifdef ASMJS_PLAT
  3141. void InterpreterStackFrame::OP_ProfiledCallAsmInternal(RegSlot funcReg, RegSlot returnReg, ProfileId profileId)
  3142. {
  3143. Var target = GetRegRawPtr(funcReg);
  3144. ScriptFunction* function = (ScriptFunction*)OP_CallGetFunc(target);
  3145. Js::FunctionBody * body = function->GetFunctionBody();
  3146. DynamicProfileInfo * dynamicProfileInfo = GetFunctionBody()->GetDynamicProfileInfo();
  3147. dynamicProfileInfo->RecordAsmJsCallSiteInfo(GetFunctionBody(), profileId, body);
  3148. return OP_CallAsmInternalCommon(function, returnReg);
  3149. }
  3150. void InterpreterStackFrame::OP_CallAsmInternal(RegSlot funcReg, RegSlot returnReg)
  3151. {
  3152. Var target = GetRegRawPtr(funcReg);
  3153. ScriptFunction* function = (ScriptFunction*)OP_CallGetFunc(target);
  3154. return OP_CallAsmInternalCommon(function, returnReg);
  3155. }
  3156. void InterpreterStackFrame::OP_CallAsmInternalCommon(ScriptFunction* function, RegSlot returnReg)
  3157. {
  3158. AsmJsScriptFunction* scriptFunc = AsmJsScriptFunction::FromVar(function);
  3159. AsmJsFunctionInfo* asmInfo = scriptFunc->GetFunctionBody()->GetAsmJsFunctionInfo();
  3160. uint alignedArgsSize = ::Math::Align<uint32>(asmInfo->GetArgByteSize(), 16);
  3161. #if _M_X64 && _WIN32
  3162. // convention is to always allocate spill space for rcx,rdx,r8,r9
  3163. if (alignedArgsSize < 0x20) alignedArgsSize = 0x20;
  3164. uint* argSizes = asmInfo->GetArgsSizesArray();
  3165. Assert(asmInfo->GetArgSizeArrayLength() >= 2);
  3166. byte* curOutParams = (byte*)m_outParams + sizeof(Var);
  3167. Assert(curOutParams + argSizes[0] + argSizes[1] + 16 <= (byte*)this->m_outParamsEnd);
  3168. // Prepare in advance the possible arguments that will need to be put in register
  3169. byte _declspec(align(16)) reg[3 * 16];
  3170. CompileAssert((FunctionBody::MinAsmJsOutParams() * sizeof(Var)) == (sizeof(Var) * 2 + sizeof(reg)));
  3171. js_memcpy_s(reg, 16, curOutParams, 16);
  3172. js_memcpy_s(reg + 16, 16, curOutParams + argSizes[0], 16);
  3173. js_memcpy_s(reg + 32, 16, curOutParams + argSizes[0] + argSizes[1], 16);
  3174. #else
  3175. byte* reg = nullptr;
  3176. #endif
  3177. ScriptContext * scriptContext = function->GetScriptContext();
  3178. Js::FunctionEntryPointInfo* entrypointInfo = (Js::FunctionEntryPointInfo*)function->GetEntryPointInfo();
  3179. PROBE_STACK_CALL(scriptContext, function, alignedArgsSize + Js::Constants::MinStackDefault);
  3180. switch (asmInfo->GetReturnType().which())
  3181. {
  3182. case AsmJsRetType::Void:
  3183. JavascriptFunction::CallAsmJsFunction<int>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3184. break;
  3185. case AsmJsRetType::Signed:
  3186. m_localIntSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<int>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3187. break;
  3188. case AsmJsRetType::Int64:
  3189. m_localInt64Slots[returnReg] = JavascriptFunction::CallAsmJsFunction<int64>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3190. break;
  3191. case AsmJsRetType::Double:
  3192. m_localDoubleSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<double>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3193. break;
  3194. case AsmJsRetType::Float:
  3195. m_localFloatSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<float>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3196. break;
  3197. #ifdef ENABLE_WASM_SIMD
  3198. case AsmJsRetType::Float32x4:
  3199. case AsmJsRetType::Int32x4:
  3200. case AsmJsRetType::Bool32x4:
  3201. case AsmJsRetType::Bool16x8:
  3202. case AsmJsRetType::Bool8x16:
  3203. case AsmJsRetType::Float64x2:
  3204. case AsmJsRetType::Int16x8:
  3205. case AsmJsRetType::Int8x16:
  3206. case AsmJsRetType::Uint32x4:
  3207. case AsmJsRetType::Uint16x8:
  3208. case AsmJsRetType::Uint8x16:
  3209. #if _WIN32 //WASM.SIMD ToDo: Enable thunk for Xplat
  3210. #if _M_X64
  3211. X86SIMDValue simdVal;
  3212. simdVal.m128_value = JavascriptFunction::CallAsmJsFunction<__m128>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3213. m_localSimdSlots[returnReg] = X86SIMDValue::ToSIMDValue(simdVal);
  3214. #else
  3215. m_localSimdSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<AsmJsSIMDValue>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3216. #endif
  3217. #endif
  3218. break;
  3219. #endif
  3220. default:
  3221. Assume(UNREACHED);
  3222. }
  3223. const ArgSlot nVarToPop = (asmInfo->GetArgByteSize() / sizeof(Var)) + 1;
  3224. PopOut(nVarToPop);
  3225. Assert(function);
  3226. }
  3227. #endif
  3228. template <class T>
  3229. void InterpreterStackFrame::OP_AsmCall(const unaligned T* playout)
  3230. {
  3231. Var target = GetRegRawPtr(playout->Function);
  3232. RecyclableObject * function = OP_CallGetFunc(target);
  3233. #if DBG
  3234. if (this->IsInDebugMode())
  3235. {
  3236. JavascriptFunction::CheckValidDebugThunk(scriptContext, function);
  3237. }
  3238. #endif
  3239. if (playout->Return == Js::Constants::NoRegister)
  3240. {
  3241. Arguments args(CallInfo(CallFlags_NotUsed, playout->ArgCount), m_outParams);
  3242. JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3243. }
  3244. else
  3245. {
  3246. Arguments args(CallInfo(CallFlags_Value, playout->ArgCount), m_outParams);
  3247. Var retVal = JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3248. SetRegRawPtr(playout->Return, retVal);
  3249. }
  3250. PopOut(playout->ArgCount);
  3251. }
  3252. template <class T>
  3253. void InterpreterStackFrame::OP_EnsureHeapAttached(const unaligned T* playout)
  3254. {
  3255. AsmJsModuleInfo::EnsureHeapAttached(this->function);
  3256. }
  3257. template <class T>
  3258. void InterpreterStackFrame::OP_CallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, const Js::AuxArray<uint32> *spreadIndices)
  3259. {
  3260. // Always save and restore implicit call flags when calling out
  3261. // REVIEW: Can we avoid it if we don't collect dynamic profile info?
  3262. ThreadContext * threadContext = scriptContext->GetThreadContext();
  3263. Js::ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3264. #ifdef ENABLE_SCRIPT_DEBUGGING
  3265. #if DBG
  3266. if (this->IsInDebugMode())
  3267. {
  3268. JavascriptFunction::CheckValidDebugThunk(scriptContext, function);
  3269. }
  3270. #endif
  3271. #endif
  3272. ArgSlot argCount = playout->ArgCount;
  3273. if (playout->Return == Js::Constants::NoRegister)
  3274. {
  3275. flags |= CallFlags_NotUsed;
  3276. Arguments args(CallInfo((CallFlags)flags, argCount), m_outParams);
  3277. AssertMsg(static_cast<unsigned>(args.Info.Flags) == flags, "Flags don't fit into the CallInfo field?");
  3278. argCount = args.GetArgCountWithExtraArgs();
  3279. if (spreadIndices != nullptr)
  3280. {
  3281. JavascriptFunction::CallSpreadFunction(function, args, spreadIndices);
  3282. }
  3283. else
  3284. {
  3285. JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3286. }
  3287. }
  3288. else
  3289. {
  3290. flags |= CallFlags_Value;
  3291. Arguments args(CallInfo((CallFlags)flags, argCount), m_outParams);
  3292. AssertMsg(static_cast<unsigned>(args.Info.Flags) == flags, "Flags don't fit into the CallInfo field?");
  3293. argCount = args.GetArgCountWithExtraArgs();
  3294. if (spreadIndices != nullptr)
  3295. {
  3296. SetReg((RegSlot)playout->Return, JavascriptFunction::CallSpreadFunction(function, args, spreadIndices));
  3297. }
  3298. else
  3299. {
  3300. SetReg((RegSlot)playout->Return, JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args));
  3301. }
  3302. }
  3303. threadContext->SetImplicitCallFlags(savedImplicitCallFlags);
  3304. PopOut(argCount);
  3305. }
  3306. template <class T>
  3307. void InterpreterStackFrame::OP_CallCommonI(const unaligned T * playout, RecyclableObject * function, unsigned flags)
  3308. {
  3309. OP_CallCommon(playout, function, flags); // CallCommon doesn't do anything with Member
  3310. }
  3311. #if ENABLE_PROFILE_INFO
  3312. template <class T>
  3313. void InterpreterStackFrame::OP_ProfileCallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, ProfileId profileId, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  3314. {
  3315. FunctionBody* functionBody = this->m_functionBody;
  3316. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  3317. FunctionInfo* functionInfo = function->GetTypeId() == TypeIds_Function?
  3318. JavascriptFunction::FromVar(function)->GetFunctionInfo() : nullptr;
  3319. bool isConstructorCall = (CallFlags_New & flags) == CallFlags_New;
  3320. dynamicProfileInfo->RecordCallSiteInfo(functionBody, profileId, functionInfo, functionInfo ? static_cast<JavascriptFunction*>(function) : nullptr, playout->ArgCount, isConstructorCall, inlineCacheIndex);
  3321. OP_CallCommon<T>(playout, function, flags, spreadIndices);
  3322. if (playout->Return != Js::Constants::NoRegister)
  3323. {
  3324. dynamicProfileInfo->RecordReturnTypeOnCallSiteInfo(functionBody, profileId, GetReg((RegSlot)playout->Return));
  3325. }
  3326. }
  3327. template <class T>
  3328. void InterpreterStackFrame::OP_ProfileReturnTypeCallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, ProfileId profileId, const Js::AuxArray<uint32> *spreadIndices)
  3329. {
  3330. OP_CallCommon<T>(playout, function, flags, spreadIndices);
  3331. FunctionBody* functionBody = this->m_functionBody;
  3332. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  3333. if (playout->Return != Js::Constants::NoRegister)
  3334. {
  3335. dynamicProfileInfo->RecordReturnType(functionBody, profileId, GetReg((RegSlot)playout->Return));
  3336. }
  3337. }
  3338. #endif
  3339. template <class T>
  3340. void InterpreterStackFrame::OP_GetRootProperty(unaligned T* playout)
  3341. {
  3342. // Same fast path as in the backend.
  3343. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  3344. Js::Var instance = this->GetRootObject();
  3345. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3346. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3347. DynamicObject * obj = DynamicObject::UnsafeFromVar(instance);
  3348. PropertyValueInfo info;
  3349. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3350. Var value;
  3351. if(CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false>(
  3352. obj, true, obj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3353. {
  3354. SetReg(playout->Value, value);
  3355. return;
  3356. }
  3357. OP_GetRootProperty_NoFastPath(playout);
  3358. }
  3359. template <class T>
  3360. void InterpreterStackFrame::OP_GetRootPropertyForTypeOf(unaligned T* playout)
  3361. {
  3362. Var rootInstance = GetRootObject();
  3363. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3364. Var value = JavascriptOperators::PatchGetRootValueForTypeOf<false>(
  3365. GetFunctionBody(),
  3366. GetInlineCache(playout->inlineCacheIndex),
  3367. playout->inlineCacheIndex,
  3368. DynamicObject::UnsafeFromVar(rootInstance),
  3369. propertyId
  3370. );
  3371. SetReg(playout->Value, value);
  3372. #ifdef TELEMETRY_INTERPRETER
  3373. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3374. {
  3375. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3376. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3377. }
  3378. #endif
  3379. }
  3380. template <class T>
  3381. _NOINLINE void InterpreterStackFrame::OP_GetRootProperty_NoFastPath(unaligned T* playout)
  3382. {
  3383. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3384. Var rootInstance = this->GetRootObject();
  3385. Var value = JavascriptOperators::PatchGetRootValue<false>(
  3386. GetFunctionBody(),
  3387. GetInlineCache(playout->inlineCacheIndex),
  3388. playout->inlineCacheIndex,
  3389. DynamicObject::UnsafeFromVar(rootInstance),
  3390. propertyId
  3391. );
  3392. SetReg(playout->Value, value);
  3393. #ifdef TELEMETRY_INTERPRETER
  3394. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3395. {
  3396. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3397. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3398. }
  3399. #endif
  3400. }
  3401. #if ENABLE_PROFILE_INFO
  3402. template <class T>
  3403. void InterpreterStackFrame::UpdateFldInfoFlagsForGetSetInlineCandidate(unaligned T* playout, FldInfoFlags& fldInfoFlags, CacheType cacheType,
  3404. DynamicProfileInfo * dynamicProfileInfo, uint inlineCacheIndex, RecyclableObject * obj)
  3405. {
  3406. RecyclableObject *callee = nullptr;
  3407. //TODO: Setter case once we stop sharing inline caches for these callsites.
  3408. if ((cacheType & (CacheType_Getter | CacheType_Setter)) && GetInlineCache(inlineCacheIndex)->GetGetterSetter(obj->GetType(), &callee))
  3409. {
  3410. const auto functionBody = this->m_functionBody;
  3411. bool canInline = dynamicProfileInfo->RecordLdFldCallSiteInfo(functionBody, callee, false /*callApplyTarget*/);
  3412. if (canInline)
  3413. {
  3414. //updates this fldInfoFlags passed by reference.
  3415. fldInfoFlags = DynamicProfileInfo::MergeFldInfoFlags(fldInfoFlags, FldInfo_InlineCandidate);
  3416. }
  3417. }
  3418. }
  3419. template <class T>
  3420. void InterpreterStackFrame::UpdateFldInfoFlagsForCallApplyInlineCandidate(unaligned T* playout, FldInfoFlags& fldInfoFlags, CacheType cacheType,
  3421. DynamicProfileInfo * dynamicProfileInfo, uint inlineCacheIndex, RecyclableObject * obj)
  3422. {
  3423. RecyclableObject *callee = nullptr;
  3424. if (!(fldInfoFlags & FldInfo_Polymorphic) && GetInlineCache(inlineCacheIndex)->GetCallApplyTarget(obj, &callee))
  3425. {
  3426. const auto functionBody = this->m_functionBody;
  3427. bool canInline = dynamicProfileInfo->RecordLdFldCallSiteInfo(functionBody, callee, true /*callApplyTarget*/);
  3428. if (canInline)
  3429. {
  3430. //updates this fldInfoFlags passed by reference.
  3431. fldInfoFlags = DynamicProfileInfo::MergeFldInfoFlags(fldInfoFlags, FldInfo_InlineCandidate);
  3432. }
  3433. }
  3434. }
  3435. template <class T, bool Root, bool Method, bool CallApplyTarget>
  3436. void InterpreterStackFrame::ProfiledGetProperty(unaligned T* playout, const Var instance)
  3437. {
  3438. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3439. Var value = ProfilingHelpers::ProfiledLdFld<Root, Method, CallApplyTarget>(
  3440. instance,
  3441. propertyId,
  3442. GetInlineCache(playout->inlineCacheIndex),
  3443. playout->inlineCacheIndex,
  3444. GetFunctionBody(),
  3445. instance);
  3446. SetReg(playout->Value, value);
  3447. #ifdef TELEMETRY_INTERPRETER
  3448. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3449. {
  3450. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3451. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, /*successful:*/true);
  3452. }
  3453. #endif
  3454. }
  3455. template <class T>
  3456. void InterpreterStackFrame::OP_ProfiledGetRootProperty(unaligned T* playout)
  3457. {
  3458. ProfiledGetProperty<T, true, false, false>(playout, GetRootObject());
  3459. }
  3460. template <class T>
  3461. void InterpreterStackFrame::OP_ProfiledGetRootPropertyForTypeOf(unaligned T* playout)
  3462. {
  3463. Var rootInstance = GetRootObject();
  3464. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3465. Var value = ProfilingHelpers::ProfiledLdFldForTypeOf<true, false, false>(
  3466. rootInstance,
  3467. propertyId,
  3468. GetInlineCache(playout->inlineCacheIndex),
  3469. playout->inlineCacheIndex,
  3470. GetFunctionBody());
  3471. SetReg(playout->Value, value);
  3472. #ifdef TELEMETRY_INTERPRETER
  3473. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3474. {
  3475. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3476. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3477. }
  3478. #endif
  3479. }
  3480. #endif
  3481. template <class T>
  3482. void InterpreterStackFrame::OP_GetPropertyForTypeOf(unaligned T* playout)
  3483. {
  3484. Var instance = GetReg(playout->Instance);
  3485. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3486. Var value = JavascriptOperators::PatchGetValueForTypeOf<false>(
  3487. GetFunctionBody(),
  3488. GetInlineCache(playout->inlineCacheIndex),
  3489. playout->inlineCacheIndex,
  3490. instance,
  3491. propertyId
  3492. );
  3493. SetReg(playout->Value, value);
  3494. #ifdef TELEMETRY_INTERPRETER
  3495. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3496. {
  3497. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3498. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, /*successful:*/true);
  3499. }
  3500. #endif
  3501. }
  3502. template <class T>
  3503. void InterpreterStackFrame::OP_GetProperty(unaligned T* playout)
  3504. {
  3505. // Same fast path as in the backend.
  3506. Var instance = GetReg(playout->Instance);
  3507. OP_GetProperty(instance, playout);
  3508. }
  3509. template <class T>
  3510. void InterpreterStackFrame::OP_GetLocalProperty(unaligned T* playout)
  3511. {
  3512. // Same fast path as in the backend.
  3513. Var instance = this->localClosure;
  3514. OP_GetProperty(instance, playout);
  3515. }
  3516. template <class T>
  3517. void InterpreterStackFrame::OP_GetProperty(Var instance, unaligned T* playout)
  3518. {
  3519. InlineCache *inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3520. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3521. RecyclableObject* obj = JavascriptOperators::TryFromVar<RecyclableObject>(instance);
  3522. if (obj)
  3523. {
  3524. PropertyValueInfo info;
  3525. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3526. Var value;
  3527. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false>(
  3528. obj, false, obj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3529. {
  3530. SetReg(playout->Value, value);
  3531. return;
  3532. }
  3533. }
  3534. OP_GetProperty_NoFastPath(instance, playout);
  3535. }
  3536. template <class T>
  3537. void InterpreterStackFrame::OP_GetSuperProperty(unaligned T* playout)
  3538. {
  3539. // Same fast path as in the backend.
  3540. Var instance = GetReg(playout->Instance);
  3541. Var thisInstance = GetReg(playout->Value2);
  3542. InlineCache *inlineCache = GetInlineCache(playout->PropertyIdIndex);
  3543. PropertyId propertyId = GetPropertyIdFromCacheId(playout->PropertyIdIndex);
  3544. if (RecyclableObject::Is(instance) && RecyclableObject::Is(thisInstance))
  3545. {
  3546. RecyclableObject* superObj = RecyclableObject::FromVar(instance);
  3547. RecyclableObject* thisObj = RecyclableObject::FromVar(thisInstance);
  3548. PropertyValueInfo info;
  3549. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->PropertyIdIndex, true);
  3550. Var value;
  3551. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false>(
  3552. thisObj, false, superObj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3553. {
  3554. SetReg(playout->Value, value);
  3555. return;
  3556. }
  3557. }
  3558. SetReg(
  3559. playout->Value,
  3560. JavascriptOperators::PatchGetValueWithThisPtr<false>(
  3561. GetFunctionBody(),
  3562. GetInlineCache(playout->PropertyIdIndex),
  3563. playout->PropertyIdIndex,
  3564. GetReg(playout->Instance),
  3565. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3566. GetReg(playout->Value2)));
  3567. }
  3568. template <class T>
  3569. _NOINLINE void InterpreterStackFrame::OP_GetProperty_NoFastPath(Var instance, unaligned T* playout)
  3570. {
  3571. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3572. Var value = JavascriptOperators::PatchGetValue<false>(
  3573. GetFunctionBody(),
  3574. GetInlineCache(playout->inlineCacheIndex),
  3575. playout->inlineCacheIndex,
  3576. instance,
  3577. propertyId
  3578. );
  3579. #ifdef TELEMETRY_INTERPRETER
  3580. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3581. {
  3582. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3583. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, true);
  3584. }
  3585. #endif
  3586. SetReg(playout->Value, value);
  3587. }
  3588. #if ENABLE_PROFILE_INFO
  3589. template <class T>
  3590. void InterpreterStackFrame::OP_ProfiledGetProperty(unaligned T* playout)
  3591. {
  3592. ProfiledGetProperty<T, false, false, false>(playout, GetReg(playout->Instance));
  3593. }
  3594. template <class T>
  3595. void InterpreterStackFrame::OP_ProfiledGetLocalProperty(unaligned T* playout)
  3596. {
  3597. ProfiledGetProperty<T, false, false, false>(playout, this->localClosure);
  3598. }
  3599. template <class T>
  3600. void InterpreterStackFrame::OP_ProfiledGetSuperProperty(unaligned T* playout)
  3601. {
  3602. SetReg(
  3603. playout->Value,
  3604. ProfilingHelpers::ProfiledLdFld<false, false, false>(
  3605. GetReg(playout->Instance),
  3606. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3607. GetInlineCache(playout->PropertyIdIndex),
  3608. playout->PropertyIdIndex,
  3609. GetFunctionBody(),
  3610. GetReg(playout->Value2)));
  3611. }
  3612. template <class T>
  3613. void InterpreterStackFrame::OP_ProfiledGetPropertyForTypeOf(unaligned T* playout)
  3614. {
  3615. Var instance = GetReg(playout->Instance);
  3616. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3617. Var value = ProfilingHelpers::ProfiledLdFldForTypeOf<false, false, false>(
  3618. instance,
  3619. propertyId,
  3620. GetInlineCache(playout->inlineCacheIndex),
  3621. playout->inlineCacheIndex,
  3622. GetFunctionBody()
  3623. );
  3624. SetReg(playout->Value, value);
  3625. #ifdef TELEMETRY_INTERPRETER
  3626. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3627. {
  3628. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3629. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, true);
  3630. }
  3631. #endif
  3632. }
  3633. template <class T>
  3634. void InterpreterStackFrame::OP_ProfiledGetPropertyCallApplyTarget(unaligned T* playout)
  3635. {
  3636. ProfiledGetProperty<T, false, false, true>(playout, GetReg(playout->Instance));
  3637. }
  3638. #endif
  3639. template <typename T>
  3640. void InterpreterStackFrame::OP_GetPropertyScoped(const unaligned OpLayoutT_ElementP<T>* playout)
  3641. {
  3642. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3643. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3644. threadContext->ClearImplicitCallFlags();
  3645. // Get the property, using a scope stack rather than an individual instance.
  3646. // Use the cache
  3647. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3648. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3649. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3650. ScriptContext* scriptContext = GetScriptContext();
  3651. int length = pScope->GetLength();
  3652. if ( 1 == length )
  3653. {
  3654. RecyclableObject *obj = RecyclableObject::FromVar(pScope->GetItem(0));
  3655. PropertyValueInfo info;
  3656. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3657. Var value;
  3658. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false>(
  3659. obj, false, obj, propertyId, &value, scriptContext, nullptr, &info))
  3660. {
  3661. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3662. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3663. SetReg(playout->Value, value);
  3664. return;
  3665. }
  3666. }
  3667. OP_GetPropertyScoped_NoFastPath(playout);
  3668. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3669. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3670. }
  3671. template <typename T>
  3672. void InterpreterStackFrame::OP_GetPropertyForTypeOfScoped(const unaligned OpLayoutT_ElementP<T>* playout)
  3673. {
  3674. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3675. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3676. threadContext->ClearImplicitCallFlags();
  3677. // Get the property, using a scope stack rather than an individual instance.
  3678. // Use the cache
  3679. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3680. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3681. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3682. ScriptContext* scriptContext = GetScriptContext();
  3683. int length = pScope->GetLength();
  3684. if (1 == length)
  3685. {
  3686. DynamicObject *obj = (DynamicObject*)pScope->GetItem(0);
  3687. PropertyValueInfo info;
  3688. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3689. Var value;
  3690. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false>(
  3691. obj, false, obj, propertyId, &value, scriptContext, nullptr, &info))
  3692. {
  3693. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3694. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3695. SetReg(playout->Value, value);
  3696. return;
  3697. }
  3698. }
  3699. SetReg(
  3700. playout->Value,
  3701. JavascriptOperators::PatchGetPropertyForTypeOfScoped<false>(
  3702. GetFunctionBody(),
  3703. GetInlineCache(playout->inlineCacheIndex),
  3704. playout->inlineCacheIndex,
  3705. GetEnvForEvalCode(),
  3706. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3707. GetReg(Js::FunctionBody::RootObjectRegSlot)));
  3708. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3709. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3710. }
  3711. template <typename T>
  3712. _NOINLINE void InterpreterStackFrame::OP_GetPropertyScoped_NoFastPath(const unaligned OpLayoutT_ElementP<T>* playout)
  3713. {
  3714. // Implicit root object as default instance
  3715. Var defaultInstance = GetReg(Js::FunctionBody::RootObjectRegSlot);
  3716. // PatchGetPropertyScoped doesn't update type and slotIndex if the scope is not an array of length 1.
  3717. SetReg(
  3718. playout->Value,
  3719. JavascriptOperators::PatchGetPropertyScoped<false>(
  3720. GetFunctionBody(),
  3721. GetInlineCache(playout->inlineCacheIndex),
  3722. playout->inlineCacheIndex,
  3723. GetEnvForEvalCode(),
  3724. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3725. defaultInstance));
  3726. }
  3727. template <class T>
  3728. void InterpreterStackFrame::OP_SetPropertyScoped(unaligned T* playout, PropertyOperationFlags flags)
  3729. {
  3730. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3731. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3732. threadContext->ClearImplicitCallFlags();
  3733. // Set the property, using a scope stack rather than an individual instance.
  3734. // Use the cache
  3735. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3736. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3737. InlineCache *inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3738. ScriptContext* scriptContext = GetScriptContext();
  3739. Var value = GetReg(playout->Value);
  3740. int length = pScope->GetLength();
  3741. if ( 1 == length )
  3742. {
  3743. RecyclableObject* obj = RecyclableObject::FromVar(pScope->GetItem(0));
  3744. PropertyValueInfo info;
  3745. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3746. if (CacheOperators::TrySetProperty<true, false, false, false, false, true, false, false>(
  3747. obj, false, propertyId, value, scriptContext, flags, nullptr, &info))
  3748. {
  3749. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3750. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3751. return;
  3752. }
  3753. }
  3754. OP_SetPropertyScoped_NoFastPath(playout, flags);
  3755. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3756. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3757. }
  3758. template <class T>
  3759. _NOINLINE void InterpreterStackFrame::OP_SetPropertyScoped_NoFastPath(unaligned T* playout, PropertyOperationFlags flags)
  3760. {
  3761. // Implicit root object as default instance
  3762. Var defaultInstance = GetReg(Js::FunctionBody::RootObjectRegSlot);
  3763. // PatchSetPropertyScoped doesn't update type and slotIndex if the scope is not an array of length 1.
  3764. JavascriptOperators::PatchSetPropertyScoped<false>(
  3765. GetFunctionBody(),
  3766. GetInlineCache(playout->inlineCacheIndex),
  3767. playout->inlineCacheIndex,
  3768. GetEnvForEvalCode(),
  3769. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3770. GetReg(playout->Value),
  3771. defaultInstance,
  3772. flags);
  3773. }
  3774. template <class T>
  3775. void InterpreterStackFrame::OP_SetPropertyScopedStrict(unaligned T* playout)
  3776. {
  3777. OP_SetPropertyScoped(playout, PropertyOperation_StrictMode);
  3778. }
  3779. template <class T>
  3780. void InterpreterStackFrame::OP_ConsoleSetPropertyScoped(unaligned T* playout)
  3781. {
  3782. OP_SetPropertyScoped(playout, PropertyOperation_AllowUndeclInConsoleScope);
  3783. }
  3784. template <class T>
  3785. void InterpreterStackFrame::OP_ConsoleSetPropertyScopedStrict(unaligned T* playout)
  3786. {
  3787. OP_SetPropertyScoped(playout, (PropertyOperationFlags)(PropertyOperation_StrictMode | PropertyOperation_AllowUndeclInConsoleScope));
  3788. }
  3789. template <class T>
  3790. inline bool InterpreterStackFrame::TrySetPropertyLocalFastPath(unaligned T* playout, PropertyId pid, RecyclableObject* instance, InlineCache*& inlineCache, PropertyOperationFlags flags)
  3791. {
  3792. inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3793. PropertyValueInfo info;
  3794. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3795. return
  3796. CacheOperators::TrySetProperty<true, false, false, false, false, true, false, false>(
  3797. instance,
  3798. !!(flags & PropertyOperation_Root),
  3799. pid,
  3800. GetReg(playout->Value),
  3801. GetScriptContext(),
  3802. flags,
  3803. nullptr,
  3804. &info);
  3805. }
  3806. template <class T>
  3807. inline void InterpreterStackFrame::DoSetProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3808. {
  3809. // Same fast path as in the backend.
  3810. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3811. InlineCache *inlineCache;
  3812. if (!TaggedNumber::Is(instance)
  3813. && TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  3814. {
  3815. if(GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3816. {
  3817. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3818. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3819. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3820. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3821. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3822. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3823. }
  3824. return;
  3825. }
  3826. DoSetProperty_NoFastPath(playout, instance, flags);
  3827. }
  3828. template <class T>
  3829. inline void InterpreterStackFrame::DoSetSuperProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3830. {
  3831. DoSetSuperProperty_NoFastPath(playout, instance, m_functionBody->GetIsStrictMode() ?
  3832. (PropertyOperationFlags)(flags | PropertyOperation_StrictMode) : flags);
  3833. }
  3834. template <class T>
  3835. _NOINLINE void InterpreterStackFrame::DoSetProperty_NoFastPath(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3836. {
  3837. #if ENABLE_COPYONACCESS_ARRAY
  3838. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3839. #endif
  3840. InlineCache *const inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3841. const auto PatchPutRootValue = &JavascriptOperators::PatchPutRootValueNoLocalFastPath<false, InlineCache>;
  3842. const auto PatchPutValue = &JavascriptOperators::PatchPutValueNoLocalFastPath<false, InlineCache>;
  3843. const auto PatchPut = flags & PropertyOperation_Root ? PatchPutRootValue : PatchPutValue;
  3844. PatchPut(
  3845. GetFunctionBody(),
  3846. inlineCache,
  3847. playout->inlineCacheIndex,
  3848. instance,
  3849. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3850. GetReg(playout->Value),
  3851. flags);
  3852. if(!TaggedNumber::Is(instance) && GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3853. {
  3854. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3855. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3856. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3857. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3858. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3859. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3860. }
  3861. }
  3862. template <class T>
  3863. _NOINLINE void InterpreterStackFrame::DoSetSuperProperty_NoFastPath(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3864. {
  3865. #if ENABLE_COPYONACCESS_ARRAY
  3866. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3867. #endif
  3868. InlineCache *const inlineCache = GetInlineCache(playout->PropertyIdIndex);
  3869. JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<false, InlineCache>(
  3870. GetFunctionBody(),
  3871. inlineCache,
  3872. playout->PropertyIdIndex,
  3873. instance,
  3874. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3875. GetReg(playout->Value),
  3876. GetReg(playout->Value2),
  3877. flags);
  3878. if (!TaggedNumber::Is(instance) && GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3879. {
  3880. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3881. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3882. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3883. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3884. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3885. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3886. }
  3887. }
  3888. #if ENABLE_PROFILE_INFO
  3889. template <class T, bool Root>
  3890. void InterpreterStackFrame::ProfiledSetProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3891. {
  3892. Assert(!Root || flags & PropertyOperation_Root);
  3893. ProfilingHelpers::ProfiledStFld<Root>(
  3894. instance,
  3895. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3896. GetInlineCache(playout->inlineCacheIndex),
  3897. playout->inlineCacheIndex,
  3898. GetReg(playout->Value),
  3899. flags,
  3900. GetJavascriptFunction(),
  3901. instance);
  3902. }
  3903. template <class T, bool Root>
  3904. void InterpreterStackFrame::ProfiledSetSuperProperty(unaligned T* playout, Var instance, Var thisInstance, PropertyOperationFlags flags)
  3905. {
  3906. Assert(!Root || flags & PropertyOperation_Root);
  3907. ProfilingHelpers::ProfiledStFld<Root>(
  3908. instance,
  3909. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3910. GetInlineCache(playout->PropertyIdIndex),
  3911. playout->PropertyIdIndex,
  3912. GetReg(playout->Value),
  3913. m_functionBody->GetIsStrictMode() ?
  3914. (PropertyOperationFlags)(flags | PropertyOperation_StrictMode ) : flags,
  3915. GetJavascriptFunction(),
  3916. thisInstance);
  3917. }
  3918. #endif
  3919. template <class T>
  3920. void InterpreterStackFrame::OP_SetProperty(unaligned T* playout)
  3921. {
  3922. DoSetProperty(playout, GetReg(playout->Instance), PropertyOperation_None);
  3923. }
  3924. template <class T>
  3925. void InterpreterStackFrame::OP_SetLocalProperty(unaligned T* playout)
  3926. {
  3927. DoSetProperty(playout, this->localClosure, PropertyOperation_None);
  3928. }
  3929. template <class T>
  3930. void InterpreterStackFrame::OP_SetSuperProperty(unaligned T* playout)
  3931. {
  3932. DoSetSuperProperty(playout, GetReg(playout->Instance), PropertyOperation_None);
  3933. }
  3934. template <class T>
  3935. void InterpreterStackFrame::OP_ProfiledSetProperty(unaligned T* playout)
  3936. {
  3937. ProfiledSetProperty<T, false>(playout, GetReg(playout->Instance), PropertyOperation_None);
  3938. }
  3939. template <class T>
  3940. void InterpreterStackFrame::OP_ProfiledSetLocalProperty(unaligned T* playout)
  3941. {
  3942. ProfiledSetProperty<T, false>(playout, this->localClosure, PropertyOperation_None);
  3943. }
  3944. template <class T>
  3945. void InterpreterStackFrame::OP_ProfiledSetSuperProperty(unaligned T* playout)
  3946. {
  3947. ProfiledSetSuperProperty<T, false>(playout, GetReg(playout->Instance), GetReg(playout->Value2), PropertyOperation_None);
  3948. }
  3949. template <class T>
  3950. void InterpreterStackFrame::OP_SetRootProperty(unaligned T* playout)
  3951. {
  3952. DoSetProperty(playout, this->GetRootObject(), PropertyOperation_Root);
  3953. }
  3954. template <class T>
  3955. void InterpreterStackFrame::OP_ProfiledSetRootProperty(unaligned T* playout)
  3956. {
  3957. ProfiledSetProperty<T, true>(playout, this->GetRootObject(), PropertyOperation_Root);
  3958. }
  3959. template <class T>
  3960. void InterpreterStackFrame::OP_SetPropertyStrict(unaligned T* playout)
  3961. {
  3962. DoSetProperty(playout, GetReg(playout->Instance), PropertyOperation_StrictMode);
  3963. }
  3964. template <class T>
  3965. void InterpreterStackFrame::OP_ProfiledSetPropertyStrict(unaligned T* playout)
  3966. {
  3967. ProfiledSetProperty<T, false>(playout, GetReg(playout->Instance), PropertyOperation_StrictMode);
  3968. }
  3969. template <class T>
  3970. void InterpreterStackFrame::OP_SetRootPropertyStrict(unaligned T* playout)
  3971. {
  3972. DoSetProperty(playout, this->GetRootObject(), PropertyOperation_StrictModeRoot);
  3973. }
  3974. template <class T>
  3975. void InterpreterStackFrame::OP_ProfiledSetRootPropertyStrict(unaligned T* playout)
  3976. {
  3977. ProfiledSetProperty<T, true>(playout, this->GetRootObject(), PropertyOperation_StrictModeRoot);
  3978. }
  3979. #if ENABLE_PROFILE_INFO
  3980. template <bool doProfile>
  3981. Var InterpreterStackFrame::ProfiledDivide(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  3982. {
  3983. Var result = JavascriptMath::Divide(aLeft, aRight,scriptContext);
  3984. if (doProfile)
  3985. {
  3986. Js::FunctionBody* body = this->m_functionBody;
  3987. body->GetDynamicProfileInfo()->RecordDivideResultType(body, profileId, result);
  3988. }
  3989. return result;
  3990. }
  3991. template <bool doProfile>
  3992. Var InterpreterStackFrame::ProfileModulus(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  3993. {
  3994. // If both arguments are TaggedInt, then try to do integer division
  3995. // This case is not handled by the lowerer.
  3996. if (doProfile)
  3997. {
  3998. Js::FunctionBody* body = this->function->GetFunctionBody();
  3999. if(TaggedInt::IsPair(aLeft, aRight))
  4000. {
  4001. int nLeft = TaggedInt::ToInt32(aLeft);
  4002. int nRight = TaggedInt::ToInt32(aRight);
  4003. // nLeft is positive and nRight is +2^i
  4004. // Fast path for Power of 2 divisor
  4005. if (nLeft > 0 && ::Math::IsPow2(nRight))
  4006. {
  4007. body->GetDynamicProfileInfo()->RecordModulusOpType(body, profileId, /*isModByPowerOf2*/ true);
  4008. return TaggedInt::ToVarUnchecked(nLeft & (nRight - 1));
  4009. }
  4010. }
  4011. body->GetDynamicProfileInfo()->RecordModulusOpType(body, profileId, /*isModByPowerOf2*/ false);
  4012. }
  4013. return JavascriptMath::Modulus(aLeft, aRight,scriptContext);
  4014. }
  4015. template <bool doProfile>
  4016. Var InterpreterStackFrame::ProfiledSwitch(Var exp, ProfileId profileId)
  4017. {
  4018. if (doProfile)
  4019. {
  4020. Js::FunctionBody* body = this->m_functionBody;
  4021. body->GetDynamicProfileInfo()->RecordSwitchType(body, profileId, exp);
  4022. }
  4023. return exp;
  4024. }
  4025. #else
  4026. template <bool doProfile>
  4027. Var InterpreterStackFrame::ProfiledDivide(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  4028. {
  4029. Assert(!doProfile);
  4030. return JavascriptMath::Divide(aLeft, aRight, scriptContext);
  4031. }
  4032. template <bool doProfile>
  4033. Var InterpreterStackFrame::ProfileModulus(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  4034. {
  4035. Assert(!doProfile);
  4036. return JavascriptMath::Modulus(aLeft, aRight, scriptContext);
  4037. }
  4038. template <bool doProfile>
  4039. Var InterpreterStackFrame::ProfiledSwitch(Var exp, ProfileId profileId)
  4040. {
  4041. Assert(!doProfile);
  4042. return exp;
  4043. }
  4044. #endif
  4045. template <class T>
  4046. void InterpreterStackFrame::DoInitProperty(unaligned T* playout, Var instance)
  4047. {
  4048. // Same fast path as in the backend.
  4049. InlineCache *inlineCache = nullptr;
  4050. Assert(!TaggedNumber::Is(instance));
  4051. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4052. if (TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache))
  4053. {
  4054. return;
  4055. }
  4056. DoInitProperty_NoFastPath(playout, instance);
  4057. }
  4058. template <class T>
  4059. _NOINLINE void InterpreterStackFrame::DoInitProperty_NoFastPath(unaligned T* playout, Var instance)
  4060. {
  4061. JavascriptOperators::PatchInitValue<false>(
  4062. GetFunctionBody(),
  4063. GetInlineCache(playout->inlineCacheIndex),
  4064. playout->inlineCacheIndex,
  4065. RecyclableObject::FromVar(instance),
  4066. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  4067. GetReg(playout->Value));
  4068. }
  4069. template <class T>
  4070. void InterpreterStackFrame::OP_InitClassMember(const unaligned T * playout)
  4071. {
  4072. uint inlineCacheIndex = playout->inlineCacheIndex;
  4073. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4074. Var instance = GetReg(playout->Instance);
  4075. PropertyOperationFlags flags = PropertyOperation_None;
  4076. Assert(!TaggedNumber::Is(instance));
  4077. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4078. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4079. {
  4080. JavascriptOperators::OP_InitClassMember(instance, propertyId, GetReg(playout->Value));
  4081. }
  4082. }
  4083. template <class T>
  4084. void InterpreterStackFrame::OP_InitClassMemberGet(const unaligned T * playout)
  4085. {
  4086. JavascriptOperators::OP_InitClassMemberGet(
  4087. GetReg(playout->Instance),
  4088. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  4089. GetReg(playout->Value));
  4090. }
  4091. template <class T>
  4092. void InterpreterStackFrame::OP_InitClassMemberSet(const unaligned T * playout)
  4093. {
  4094. JavascriptOperators::OP_InitClassMemberSet(
  4095. GetReg(playout->Instance),
  4096. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  4097. GetReg(playout->Value));
  4098. }
  4099. template <class T>
  4100. void InterpreterStackFrame::OP_InitClassMemberSetComputedName(const unaligned T * playout)
  4101. {
  4102. JavascriptOperators::OP_InitClassMemberSetComputedName(
  4103. GetReg(playout->Instance),
  4104. GetReg(playout->Element),
  4105. GetReg(playout->Value),
  4106. m_functionBody->GetScriptContext());
  4107. }
  4108. template <class T>
  4109. void InterpreterStackFrame::OP_InitClassMemberGetComputedName(const unaligned T * playout)
  4110. {
  4111. JavascriptOperators::OP_InitClassMemberGetComputedName(
  4112. GetReg(playout->Instance),
  4113. GetReg(playout->Element),
  4114. GetReg(playout->Value),
  4115. m_functionBody->GetScriptContext());
  4116. }
  4117. template <class T>
  4118. void InterpreterStackFrame::OP_InitClassMemberComputedName(const unaligned T * playout)
  4119. {
  4120. JavascriptOperators::OP_InitClassMemberComputedName(
  4121. GetReg(playout->Instance),
  4122. GetReg(playout->Element),
  4123. GetReg(playout->Value),
  4124. m_functionBody->GetScriptContext());
  4125. }
  4126. template <class T>
  4127. void InterpreterStackFrame::DoInitLetFld(const unaligned T * playout, Var instance, PropertyOperationFlags flags)
  4128. {
  4129. uint inlineCacheIndex = playout->inlineCacheIndex;
  4130. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4131. Assert(!TaggedNumber::Is(instance));
  4132. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4133. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4134. {
  4135. JavascriptOperators::OP_InitLetProperty(instance, propertyId, GetReg(playout->Value));
  4136. }
  4137. }
  4138. template <class T>
  4139. void InterpreterStackFrame::DoInitConstFld(const unaligned T * playout, Var instance, PropertyOperationFlags flags)
  4140. {
  4141. uint inlineCacheIndex = playout->inlineCacheIndex;
  4142. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4143. Assert(!TaggedNumber::Is(instance));
  4144. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4145. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4146. {
  4147. JavascriptOperators::OP_InitConstProperty(instance, propertyId, GetReg(playout->Value));
  4148. }
  4149. }
  4150. template <class T>
  4151. void InterpreterStackFrame::OP_InitProperty(unaligned T* playout)
  4152. {
  4153. DoInitProperty(playout, GetReg(playout->Instance));
  4154. }
  4155. template <class T>
  4156. void InterpreterStackFrame::OP_InitLocalProperty(unaligned T* playout)
  4157. {
  4158. DoInitProperty(playout, this->localClosure);
  4159. }
  4160. template <class T>
  4161. void InterpreterStackFrame::OP_InitInnerFld(const unaligned T* playout)
  4162. {
  4163. DoInitProperty(playout, InnerScopeFromIndex(playout->scopeIndex));
  4164. }
  4165. template <class T>
  4166. void InterpreterStackFrame::OP_InitLetFld(const unaligned T * playout)
  4167. {
  4168. DoInitLetFld(playout, GetReg(playout->Instance));
  4169. }
  4170. template <class T>
  4171. void InterpreterStackFrame::OP_InitInnerLetFld(const unaligned T * playout)
  4172. {
  4173. DoInitLetFld(playout, InnerScopeFromIndex(playout->scopeIndex));
  4174. }
  4175. template <class T>
  4176. void InterpreterStackFrame::OP_InitLocalLetFld(const unaligned T * playout)
  4177. {
  4178. DoInitLetFld(playout, this->localClosure);
  4179. }
  4180. template <class T>
  4181. void InterpreterStackFrame::OP_InitConstFld(const unaligned T * playout)
  4182. {
  4183. DoInitConstFld(playout, GetReg(playout->Instance));
  4184. }
  4185. template <class T>
  4186. void InterpreterStackFrame::OP_InitRootProperty(unaligned T* playout)
  4187. {
  4188. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4189. DoInitProperty(playout, this->GetRootObject());
  4190. }
  4191. template <class T>
  4192. void InterpreterStackFrame::OP_InitRootLetFld(const unaligned T * playout)
  4193. {
  4194. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4195. DoInitLetFld(playout, this->GetRootObject(), PropertyOperation_Root);
  4196. }
  4197. template <class T>
  4198. void InterpreterStackFrame::OP_InitRootConstFld(const unaligned T * playout)
  4199. {
  4200. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4201. DoInitConstFld(playout, this->GetRootObject(), PropertyOperation_Root);
  4202. }
  4203. template <class T>
  4204. void InterpreterStackFrame::OP_InitUndeclLetProperty(unaligned T* playout)
  4205. {
  4206. Var instance = InnerScopeFromIndex(playout->scopeIndex);
  4207. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4208. JavascriptOperators::OP_InitLetProperty(instance, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4209. }
  4210. template <class T>
  4211. void InterpreterStackFrame::OP_InitUndeclLocalLetProperty(unaligned T* playout)
  4212. {
  4213. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4214. JavascriptOperators::OP_InitLetProperty(this->localClosure, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4215. }
  4216. void InterpreterStackFrame::OP_InitUndeclRootLetProperty(uint propertyIdIndex)
  4217. {
  4218. Var instance = this->GetRootObject();
  4219. PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  4220. JavascriptOperators::OP_InitUndeclRootLetProperty(instance, propertyId);
  4221. }
  4222. template <class T>
  4223. void InterpreterStackFrame::OP_InitUndeclConstProperty(unaligned T* playout)
  4224. {
  4225. Var instance = InnerScopeFromIndex(playout->scopeIndex);
  4226. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4227. JavascriptOperators::OP_InitConstProperty(instance, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4228. }
  4229. template <class T>
  4230. void InterpreterStackFrame::OP_InitUndeclLocalConstProperty(unaligned T* playout)
  4231. {
  4232. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4233. JavascriptOperators::OP_InitConstProperty(this->localClosure, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4234. }
  4235. void InterpreterStackFrame::OP_InitUndeclRootConstProperty(uint propertyIdIndex)
  4236. {
  4237. Var instance = this->GetRootObject();
  4238. PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  4239. JavascriptOperators::OP_InitUndeclRootConstProperty(instance, propertyId);
  4240. }
  4241. template <class T>
  4242. void InterpreterStackFrame::OP_InitUndeclConsoleLetProperty(unaligned T* playout)
  4243. {
  4244. FrameDisplay* pScope = (FrameDisplay*)this->LdEnv();
  4245. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  4246. PropertyId propertyId = m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex);
  4247. JavascriptOperators::OP_InitLetProperty(pScope->GetItem(0), propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4248. }
  4249. template <class T>
  4250. void InterpreterStackFrame::OP_InitUndeclConsoleConstProperty(unaligned T* playout)
  4251. {
  4252. FrameDisplay* pScope = (FrameDisplay*)this->LdEnv();
  4253. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  4254. PropertyId propertyId = m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex);
  4255. JavascriptOperators::OP_InitConstProperty(pScope->GetItem(0), propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4256. }
  4257. #if ENABLE_PROFILE_INFO
  4258. template <class T>
  4259. void InterpreterStackFrame::ProfiledInitProperty(unaligned T* playout, Var instance)
  4260. {
  4261. ProfilingHelpers::ProfiledInitFld(
  4262. RecyclableObject::FromVar(instance),
  4263. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  4264. GetInlineCache(playout->inlineCacheIndex),
  4265. playout->inlineCacheIndex,
  4266. GetReg(playout->Value),
  4267. GetFunctionBody());
  4268. }
  4269. template <class T>
  4270. void InterpreterStackFrame::OP_ProfiledInitProperty(unaligned T* playout)
  4271. {
  4272. ProfiledInitProperty(playout, GetReg(playout->Instance));
  4273. }
  4274. template <class T>
  4275. void InterpreterStackFrame::OP_ProfiledInitLocalProperty(unaligned T* playout)
  4276. {
  4277. ProfiledInitProperty(playout, this->localClosure);
  4278. }
  4279. template <class T>
  4280. void InterpreterStackFrame::OP_ProfiledInitRootProperty(unaligned T* playout)
  4281. {
  4282. ProfiledInitProperty(playout, this->GetRootObject());
  4283. }
  4284. template <class T>
  4285. void InterpreterStackFrame::OP_ProfiledGetElementI(const unaligned OpLayoutDynamicProfile<T>* playout)
  4286. {
  4287. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4288. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4289. threadContext->ClearImplicitCallFlags();
  4290. SetReg(
  4291. playout->Value,
  4292. ProfilingHelpers::ProfiledLdElem(
  4293. GetReg(playout->Instance),
  4294. GetReg(playout->Element),
  4295. m_functionBody,
  4296. playout->profileId,
  4297. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall),
  4298. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization)));
  4299. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall | InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  4300. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4301. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4302. }
  4303. #endif
  4304. template <typename T>
  4305. void InterpreterStackFrame::OP_GetElementI(const unaligned T* playout)
  4306. {
  4307. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4308. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4309. threadContext->ClearImplicitCallFlags();
  4310. // Same fast path as in the backend.
  4311. Var instance = GetReg(playout->Instance);
  4312. // Only enable fast path if the javascript array is not cross site
  4313. Var element;
  4314. #if ENABLE_PROFILE_INFO
  4315. if (!TaggedNumber::Is(instance) && VirtualTableInfo<JavascriptArray>::HasVirtualTable(instance))
  4316. {
  4317. element =
  4318. ProfilingHelpers::ProfiledLdElem_FastPath(
  4319. JavascriptArray::UnsafeFromVar(instance),
  4320. GetReg(playout->Element),
  4321. GetScriptContext());
  4322. }
  4323. else
  4324. #endif
  4325. {
  4326. element = JavascriptOperators::OP_GetElementI(instance, GetReg(playout->Element), GetScriptContext());
  4327. }
  4328. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall);
  4329. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4330. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4331. SetReg(playout->Value, element);
  4332. }
  4333. template <typename T>
  4334. void InterpreterStackFrame::OP_SetElementI(const unaligned T* playout, PropertyOperationFlags flags)
  4335. {
  4336. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4337. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4338. threadContext->ClearImplicitCallFlags();
  4339. // Same fast path as in the backend.
  4340. Var instance = GetReg(playout->Instance);
  4341. const Var varIndex = GetReg(playout->Element);
  4342. const Var value = GetReg(playout->Value);
  4343. #if ENABLE_PROFILE_INFO
  4344. // Only enable fast path if the javascript array is not cross site
  4345. if (!TaggedNumber::Is(instance) &&
  4346. VirtualTableInfo<JavascriptArray>::HasVirtualTable(instance) &&
  4347. !JavascriptOperators::SetElementMayHaveImplicitCalls(GetScriptContext()))
  4348. {
  4349. ProfilingHelpers::ProfiledStElem_FastPath(
  4350. JavascriptArray::UnsafeFromVar(instance),
  4351. varIndex,
  4352. value,
  4353. GetScriptContext(),
  4354. flags);
  4355. }
  4356. else
  4357. #endif
  4358. {
  4359. JavascriptOperators::OP_SetElementI(instance, varIndex, value, GetScriptContext(), flags);
  4360. }
  4361. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall);
  4362. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4363. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4364. }
  4365. #if ENABLE_PROFILE_INFO
  4366. template <typename T>
  4367. void InterpreterStackFrame::OP_ProfiledSetElementI(
  4368. const unaligned OpLayoutDynamicProfile<T>* playout,
  4369. PropertyOperationFlags flags)
  4370. {
  4371. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4372. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4373. threadContext->ClearImplicitCallFlags();
  4374. ProfilingHelpers::ProfiledStElem(
  4375. GetReg(playout->Instance),
  4376. GetReg(playout->Element),
  4377. GetReg(playout->Value),
  4378. m_functionBody,
  4379. playout->profileId,
  4380. flags,
  4381. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall),
  4382. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization));
  4383. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall | InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  4384. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4385. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4386. }
  4387. #endif
  4388. template <typename T>
  4389. void InterpreterStackFrame::OP_SetElementIStrict(const unaligned T* playout)
  4390. {
  4391. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4392. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4393. threadContext->ClearImplicitCallFlags();
  4394. OP_SetElementI(playout, PropertyOperation_StrictMode);
  4395. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4396. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4397. }
  4398. #if ENABLE_PROFILE_INFO
  4399. template <typename T>
  4400. void InterpreterStackFrame::OP_ProfiledSetElementIStrict(const unaligned OpLayoutDynamicProfile<T>* playout)
  4401. {
  4402. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4403. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4404. threadContext->ClearImplicitCallFlags();
  4405. OP_ProfiledSetElementI(playout, PropertyOperation_StrictMode);
  4406. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4407. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4408. }
  4409. #endif
  4410. template <class T>
  4411. void InterpreterStackFrame::OP_LdArrayHeadSegment(const unaligned T* playout)
  4412. {
  4413. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->R1));
  4414. // The array is create by the built-in on the same script context
  4415. Assert(array->GetScriptContext() == GetScriptContext());
  4416. SetNonVarReg(playout->R0, array->GetHead());
  4417. }
  4418. template <class T>
  4419. void InterpreterStackFrame::OP_SetArraySegmentItem_CI4(const unaligned T* playout)
  4420. {
  4421. SparseArraySegment<Var> * segment = (SparseArraySegment<Var> *)GetNonVarReg(playout->Instance);
  4422. uint32 index = playout->Element;
  4423. Var value = GetReg(playout->Value);
  4424. Assert(segment->left == 0);
  4425. Assert(index < segment->length);
  4426. segment->elements[index] = value;
  4427. }
  4428. template <class T>
  4429. void InterpreterStackFrame::OP_NewScArray(const unaligned T * playout)
  4430. {
  4431. JavascriptArray *arr;
  4432. arr = scriptContext->GetLibrary()->CreateArrayLiteral(playout->C1);
  4433. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4434. arr->CheckForceES5Array();
  4435. #endif
  4436. SetReg(playout->R0, arr);
  4437. }
  4438. #if ENABLE_PROFILE_INFO
  4439. template <bool Profiled, class T>
  4440. void InterpreterStackFrame::ProfiledNewScArray(const unaligned OpLayoutDynamicProfile<T> * playout)
  4441. {
  4442. if(!Profiled && !isAutoProfiling)
  4443. {
  4444. OP_NewScArray(playout);
  4445. return;
  4446. }
  4447. SetReg(
  4448. playout->R0,
  4449. ProfilingHelpers::ProfiledNewScArray(
  4450. playout->C1,
  4451. m_functionBody,
  4452. playout->profileId));
  4453. }
  4454. #else
  4455. template <bool Profiled, class T>
  4456. void InterpreterStackFrame::ProfiledNewScArray(const unaligned OpLayoutDynamicProfile<T> * playout)
  4457. {
  4458. Assert(!Profiled);
  4459. OP_NewScArray(playout);
  4460. }
  4461. #endif
  4462. void InterpreterStackFrame::OP_NewScIntArray(const unaligned OpLayoutAuxiliary * playout)
  4463. {
  4464. #if ENABLE_PROFILE_INFO
  4465. if(isAutoProfiling)
  4466. {
  4467. OP_ProfiledNewScIntArray(static_cast<const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> *>(playout));
  4468. return;
  4469. }
  4470. #endif
  4471. const Js::AuxArray<int32> *ints = Js::ByteCodeReader::ReadAuxArray<int32>(playout->Offset, this->GetFunctionBody());
  4472. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(ints->count);
  4473. SparseArraySegment<int32> * segment = (SparseArraySegment<int32>*)arr->GetHead();
  4474. JavascriptOperators::AddIntsToArraySegment(segment, ints);
  4475. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4476. arr->CheckForceES5Array();
  4477. #endif
  4478. SetReg(playout->R0, arr);
  4479. }
  4480. #if ENABLE_PROFILE_INFO
  4481. void InterpreterStackFrame::OP_ProfiledNewScIntArray(const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> * playout)
  4482. {
  4483. const Js::AuxArray<int32> *ints = Js::ByteCodeReader::ReadAuxArray<int32>(playout->Offset, this->GetFunctionBody());
  4484. Js::ProfileId profileId = playout->profileId;
  4485. FunctionBody *functionBody = this->m_functionBody;
  4486. ArrayCallSiteInfo *arrayInfo = functionBody->GetDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4487. Assert(arrayInfo);
  4488. JavascriptArray *arr;
  4489. if (arrayInfo && arrayInfo->IsNativeIntArray())
  4490. {
  4491. #if ENABLE_COPYONACCESS_ARRAY
  4492. JavascriptLibrary *lib = scriptContext->GetLibrary();
  4493. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, ints->count))
  4494. {
  4495. Assert(lib->cacheForCopyOnAccessArraySegments);
  4496. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  4497. }
  4498. else
  4499. #endif
  4500. {
  4501. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(ints->count);
  4502. SparseArraySegment<int32> *segment = (SparseArraySegment<int32>*)arr->GetHead();
  4503. JavascriptOperators::AddIntsToArraySegment(segment, ints);
  4504. }
  4505. JavascriptNativeIntArray *intArray = reinterpret_cast<JavascriptNativeIntArray*>(arr);
  4506. Recycler *recycler = scriptContext->GetRecycler();
  4507. intArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4508. }
  4509. else if (arrayInfo && arrayInfo->IsNativeFloatArray())
  4510. {
  4511. arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(ints->count);
  4512. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4513. for (uint i = 0; i < ints->count; i++)
  4514. {
  4515. segment->elements[i] = (double)ints->elements[i];
  4516. }
  4517. JavascriptNativeFloatArray *floatArray = reinterpret_cast<JavascriptNativeFloatArray*>(arr);
  4518. Recycler *recycler = scriptContext->GetRecycler();
  4519. floatArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4520. }
  4521. else
  4522. {
  4523. arr = scriptContext->GetLibrary()->CreateArrayLiteral(ints->count);
  4524. SparseArraySegment<Var> * segment = (SparseArraySegment<Var>*)arr->GetHead();
  4525. for (uint i = 0; i < ints->count; i++)
  4526. {
  4527. segment->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  4528. }
  4529. }
  4530. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4531. arr->CheckForceES5Array();
  4532. #endif
  4533. SetReg(playout->R0, arr);
  4534. }
  4535. #endif
  4536. void InterpreterStackFrame::OP_NewScFltArray(const unaligned OpLayoutAuxiliary * playout )
  4537. {
  4538. #if ENABLE_PROFILE_INFO
  4539. if(isAutoProfiling)
  4540. {
  4541. OP_ProfiledNewScFltArray(static_cast<const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> *>(playout));
  4542. return;
  4543. }
  4544. #endif
  4545. const Js::AuxArray<double> *doubles = Js::ByteCodeReader::ReadAuxArray<double>(playout->Offset, this->GetFunctionBody());
  4546. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(doubles->count);
  4547. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4548. JavascriptOperators::AddFloatsToArraySegment(segment, doubles);
  4549. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4550. arr->CheckForceES5Array();
  4551. #endif
  4552. SetReg(playout->R0, arr);
  4553. }
  4554. #if ENABLE_PROFILE_INFO
  4555. void InterpreterStackFrame::OP_ProfiledNewScFltArray(const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> * playout)
  4556. {
  4557. const Js::AuxArray<double> *doubles = Js::ByteCodeReader::ReadAuxArray<double>(playout->Offset, this->GetFunctionBody());
  4558. Js::ProfileId profileId = playout->profileId;
  4559. FunctionBody *functionBody = this->m_functionBody;
  4560. ArrayCallSiteInfo *arrayInfo = functionBody->GetDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4561. Assert(arrayInfo);
  4562. JavascriptArray *arr;
  4563. if (arrayInfo && arrayInfo->IsNativeFloatArray())
  4564. {
  4565. arrayInfo->SetIsNotNativeIntArray();
  4566. arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(doubles->count);
  4567. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4568. JavascriptOperators::AddFloatsToArraySegment(segment, doubles);
  4569. JavascriptNativeFloatArray *floatArray = reinterpret_cast<JavascriptNativeFloatArray*>(arr);
  4570. Recycler *recycler = scriptContext->GetRecycler();
  4571. floatArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4572. }
  4573. else
  4574. {
  4575. arr = scriptContext->GetLibrary()->CreateArrayLiteral(doubles->count);
  4576. SparseArraySegment<Var> * segment = (SparseArraySegment<Var>*)arr->GetHead();
  4577. for (uint i = 0; i < doubles->count; i++)
  4578. {
  4579. segment->elements[i] = JavascriptNumber::ToVarNoCheck(doubles->elements[i], scriptContext);
  4580. }
  4581. }
  4582. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4583. arr->CheckForceES5Array();
  4584. #endif
  4585. SetReg(playout->R0, arr);
  4586. }
  4587. #endif
  4588. void InterpreterStackFrame::OP_SetArraySegmentVars(const unaligned OpLayoutAuxiliary * playout)
  4589. {
  4590. const Js::VarArray *vars = Js::ByteCodeReader::ReadAuxArray<Var>(playout->Offset, this->GetFunctionBody());
  4591. SparseArraySegment<Var> * segment =(SparseArraySegment<Var> *)GetNonVarReg(playout->R0);
  4592. JavascriptOperators::AddVarsToArraySegment(segment, vars);
  4593. }
  4594. template <class T>
  4595. void InterpreterStackFrame::OP_SetArrayItemC_CI4(const unaligned T* playout)
  4596. {
  4597. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->Instance));
  4598. uint32 index = playout->Element;
  4599. Var value = GetReg(playout->Value);
  4600. #if ENABLE_COPYONACCESS_ARRAY
  4601. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(value);
  4602. #endif
  4603. // The array is create by the built-in on the same script context
  4604. Assert(array->GetScriptContext() == GetScriptContext());
  4605. TypeId typeId = array->GetTypeId();
  4606. if (typeId == TypeIds_NativeIntArray)
  4607. {
  4608. JavascriptArray::OP_SetNativeIntElementC(reinterpret_cast<JavascriptNativeIntArray*>(array), index, value, array->GetScriptContext());
  4609. }
  4610. else if (typeId == TypeIds_NativeFloatArray)
  4611. {
  4612. JavascriptArray::OP_SetNativeFloatElementC(reinterpret_cast<JavascriptNativeFloatArray*>(array), index, value, array->GetScriptContext());
  4613. }
  4614. else
  4615. {
  4616. array->SetArrayLiteralItem(index, value);
  4617. }
  4618. }
  4619. template <class T>
  4620. void InterpreterStackFrame::OP_SetArrayItemI_CI4(const unaligned T* playout)
  4621. {
  4622. // Note that this code assumes that we only get here when we see an array literal,
  4623. // so we know that the instance is truly an array, and the index is a uint32.
  4624. // If/when we use this for cases like "a[0] = x", we'll at least have to check
  4625. // whether "a" is really an array.
  4626. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->Instance));
  4627. // The array is create by the built-in on the same script context
  4628. Assert(array->GetScriptContext() == GetScriptContext());
  4629. uint32 index = playout->Element;
  4630. Var value = GetReg(playout->Value);
  4631. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(array));
  4632. SparseArraySegment<Var>* lastUsedSeg = (SparseArraySegment<Var>*)array->GetLastUsedSegment();
  4633. if (index >= lastUsedSeg->left)
  4634. {
  4635. uint32 index2 = index - lastUsedSeg->left;
  4636. if (index2 < lastUsedSeg->size)
  4637. {
  4638. // Successful fastpath
  4639. array->DirectSetItemInLastUsedSegmentAt(index2, value);
  4640. return;
  4641. }
  4642. }
  4643. ScriptContext* scriptContext = array->GetScriptContext();
  4644. JavascriptOperators::SetItem(array, array, index, value, scriptContext);
  4645. }
  4646. #if ENABLE_PROFILE_INFO
  4647. Var InterpreterStackFrame::OP_ProfiledLdThis(Var thisVar, int moduleID, ScriptContext *scriptContext)
  4648. {
  4649. FunctionBody * functionBody = this->m_functionBody;
  4650. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4651. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4652. if (JavascriptOperators::IsThisSelf(typeId))
  4653. {
  4654. Assert(typeId != TypeIds_GlobalObject || ((Js::GlobalObject*)thisVar)->ToThis() == thisVar);
  4655. Assert(typeId != TypeIds_ModuleRoot || JavascriptOperators::GetThisFromModuleRoot(thisVar) == thisVar);
  4656. // Record the fact that we saw a trivial LdThis.
  4657. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Simple);
  4658. return thisVar;
  4659. }
  4660. thisVar = JavascriptOperators::OP_GetThis(thisVar, moduleID, scriptContext);
  4661. // Record the fact that we saw a LdThis that had to map its source to something else, or at least
  4662. // forced us to call a helper, e.g., a FastDOM object with an unrecognized type ID.
  4663. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Mapped);
  4664. return thisVar;
  4665. }
  4666. Var InterpreterStackFrame::OP_ProfiledStrictLdThis(Var thisVar, ScriptContext* scriptContext)
  4667. {
  4668. FunctionBody * functionBody = this->m_functionBody;
  4669. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4670. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4671. if (typeId == TypeIds_ActivationObject)
  4672. {
  4673. thisVar = scriptContext->GetLibrary()->GetUndefined();
  4674. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Mapped);
  4675. return thisVar;
  4676. }
  4677. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Simple);
  4678. return thisVar;
  4679. }
  4680. #endif
  4681. void InterpreterStackFrame::OP_InitCachedFuncs(const unaligned OpLayoutAuxNoReg * playout)
  4682. {
  4683. const FuncInfoArray *info = Js::ByteCodeReader::ReadAuxArray<FuncInfoEntry>(playout->Offset, this->GetFunctionBody());
  4684. JavascriptOperators::OP_InitCachedFuncs(this->localClosure, GetLocalFrameDisplay(), info, GetScriptContext());
  4685. }
  4686. Var InterpreterStackFrame::OP_GetCachedFunc(Var instance, int32 index)
  4687. {
  4688. ActivationObjectEx *obj = ActivationObjectEx::FromVar(instance);
  4689. FuncCacheEntry *entry = obj->GetFuncCacheEntry((uint)index);
  4690. return entry->func;
  4691. }
  4692. void InterpreterStackFrame::OP_CommitScope()
  4693. {
  4694. const Js::PropertyIdArray *propIds = this->m_functionBody->GetFormalsPropIdArray();
  4695. this->OP_CommitScopeHelper(propIds);
  4696. }
  4697. void InterpreterStackFrame::OP_CommitScopeHelper(const PropertyIdArray *propIds)
  4698. {
  4699. ActivationObjectEx *obj = ActivationObjectEx::FromVar(this->localClosure);
  4700. ScriptFunction *func = obj->GetParentFunc();
  4701. Assert(obj->GetParentFunc() == func);
  4702. if (func->GetCachedScope() == obj)
  4703. {
  4704. PropertyId firstVarSlot = ActivationObjectEx::GetFirstVarSlot(propIds);
  4705. Var undef = scriptContext->GetLibrary()->GetUndefined();
  4706. for (uint i = firstVarSlot; i < propIds->count; i++)
  4707. {
  4708. obj->SetSlot(SetSlotArguments(propIds->elements[i], i, undef));
  4709. }
  4710. obj->SetCommit(true);
  4711. }
  4712. }
  4713. Var InterpreterStackFrame::OP_NewScObjectSimple()
  4714. {
  4715. Var object = scriptContext->GetLibrary()->CreateObject(true);
  4716. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  4717. #if ENABLE_DEBUG_CONFIG_OPTIONS
  4718. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  4719. {
  4720. object = JavascriptProxy::AutoProxyWrapper(object);
  4721. }
  4722. #endif
  4723. return object;
  4724. }
  4725. void InterpreterStackFrame::OP_NewScObjectLiteral(const unaligned OpLayoutAuxiliary * playout )
  4726. {
  4727. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4728. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), propIds,
  4729. this->GetFunctionBody()->GetObjectLiteralTypeRef(playout->C1));
  4730. SetReg(playout->R0, newObj);
  4731. }
  4732. void InterpreterStackFrame::OP_NewScObjectLiteral_LS(const unaligned OpLayoutAuxiliary * playout, RegSlot& target)
  4733. {
  4734. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4735. target = playout->R0;
  4736. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), propIds,
  4737. this->GetFunctionBody()->GetObjectLiteralTypeRef(playout->C1));
  4738. SetReg(playout->R0, newObj);
  4739. target = Js::Constants::NoRegister;
  4740. }
  4741. void InterpreterStackFrame::OP_LdPropIds(const unaligned OpLayoutAuxiliary * playout)
  4742. {
  4743. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4744. SetNonVarReg(playout->R0, (Var)propIds);
  4745. }
  4746. bool InterpreterStackFrame::IsCurrentLoopNativeAddr(void * codeAddr) const
  4747. {
  4748. if (this->GetCurrentLoopNum() == LoopHeader::NoLoop)
  4749. {
  4750. return false;
  4751. }
  4752. // TODO: Do more verification?
  4753. return true;
  4754. }
  4755. template <LayoutSize layoutSize, bool profiled>
  4756. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(const byte * ip)
  4757. {
  4758. uint32 loopId = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4759. return OP_ProfiledLoopBodyStart<layoutSize, profiled>(loopId);
  4760. }
  4761. #ifdef ASMJS_PLAT
  4762. template <LayoutSize layoutSize, bool profiled>
  4763. const byte * InterpreterStackFrame::OP_ProfiledWasmLoopBodyStart(const byte * ip)
  4764. {
  4765. uint32 loopId = m_reader.GetLayout<OpLayoutT_WasmLoopStart<LayoutSizePolicy<layoutSize>>>(ip)->loopId;
  4766. return OP_ProfiledLoopBodyStart<layoutSize, profiled>(loopId);
  4767. }
  4768. #endif
  4769. #if ENABLE_PROFILE_INFO
  4770. void InterpreterStackFrame::OP_RecordImplicitCall(uint loopNumber)
  4771. {
  4772. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4773. Assert(loopNumber < this->m_functionBody->GetLoopCount());
  4774. FunctionBody* functionBody = this->m_functionBody;
  4775. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4776. ThreadContext * threadContext = scriptContext->GetThreadContext();
  4777. dynamicProfileInfo->RecordLoopImplicitCallFlags(functionBody, loopNumber, threadContext->GetImplicitCallFlags());
  4778. }
  4779. template <LayoutSize layoutSize, bool profiled>
  4780. const byte * InterpreterStackFrame::OP_ProfiledLoopStart(const byte * ip)
  4781. {
  4782. const uint32 C1 = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4783. if(!profiled && !isAutoProfiling)
  4784. {
  4785. return ip;
  4786. }
  4787. ThreadContext *const threadContext = GetScriptContext()->GetThreadContext();
  4788. threadContext->IncrementLoopDepth();
  4789. // Save the implicit call flags. The interpreter may switch to profiling mode during LoopBodyStart, so always do this.
  4790. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4791. this->savedLoopImplicitCallFlags[C1] = threadContext->GetImplicitCallFlags();
  4792. threadContext->SetImplicitCallFlags(ImplicitCall_None);
  4793. this->currentLoopCounter = 0;
  4794. if(!profiled)
  4795. {
  4796. return ip;
  4797. }
  4798. LayoutSize localLayoutSize;
  4799. OpCode peekOp = m_reader.PeekOp(ip, localLayoutSize);
  4800. Assert(peekOp != OpCode::LoopBodyStart);
  4801. if (peekOp == OpCode::ProfiledLoopBodyStart)
  4802. {
  4803. Assert(localLayoutSize == layoutSize);
  4804. ip += Js::OpCodeUtil::EncodedSize(peekOp, layoutSize);
  4805. // We are doing JIT loop body. Process the first ProfiledLoopBodyStart to avoid recording
  4806. // the implicit call before the first iteration
  4807. uint32 C2 = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4808. Assert(C1 == C2);
  4809. (this->*opProfiledLoopBodyStart)(C1, layoutSize, true /* isFirstIteration */);
  4810. return m_reader.GetIP();
  4811. }
  4812. return ip;
  4813. }
  4814. template <LayoutSize layoutSize, bool profiled>
  4815. const byte * InterpreterStackFrame::OP_ProfiledLoopEnd(const byte * ip)
  4816. {
  4817. uint32 loopNumber = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4818. if(!profiled && !isAutoProfiling)
  4819. {
  4820. return ip;
  4821. }
  4822. this->CheckIfLoopIsHot(this->currentLoopCounter);
  4823. Js::FunctionBody *fn = this->function->GetFunctionBody();
  4824. if (fn->HasDynamicProfileInfo())
  4825. {
  4826. fn->GetAnyDynamicProfileInfo()->SetLoopInterpreted(loopNumber);
  4827. // If the counter is 0, there is a high chance that some config disabled tracking that information. (ie: -off:jitloopbody)
  4828. // Assume it is valid for memop in this case.
  4829. if (this->currentLoopCounter >= (uint)CONFIG_FLAG(MinMemOpCount) ||
  4830. (this->currentLoopCounter == 0 && !this->m_functionBody->DoJITLoopBody())
  4831. )
  4832. {
  4833. // This flag becomes relevant only if the loop has been interpreted
  4834. fn->GetAnyDynamicProfileInfo()->SetMemOpMinReached(loopNumber);
  4835. }
  4836. }
  4837. this->currentLoopCounter = 0;
  4838. if (profiled)
  4839. {
  4840. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4841. OP_RecordImplicitCall(loopNumber);
  4842. if(switchProfileModeOnLoopEndNumber == loopNumber)
  4843. {
  4844. // Stop profiling since the jitted loop body would be exiting the loop
  4845. Assert(!switchProfileMode);
  4846. switchProfileMode = true;
  4847. switchProfileModeOnLoopEndNumber = 0u - 1;
  4848. }
  4849. }
  4850. // Restore the implicit call flags state and add with flags in the loop as well
  4851. ThreadContext *const threadContext = GetScriptContext()->GetThreadContext();
  4852. threadContext->AddImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  4853. threadContext->DecrementLoopDepth();
  4854. return ip;
  4855. }
  4856. template <LayoutSize layoutSize, bool profiled>
  4857. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(uint loopId)
  4858. {
  4859. if (profiled || isAutoProfiling)
  4860. {
  4861. this->currentLoopCounter++;
  4862. }
  4863. if (profiled)
  4864. {
  4865. OP_RecordImplicitCall(loopId);
  4866. }
  4867. (this->*(profiled ? opProfiledLoopBodyStart : opLoopBodyStart))(loopId, layoutSize, false /* isFirstIteration */);
  4868. return m_reader.GetIP();
  4869. }
  4870. template<bool InterruptProbe, bool JITLoopBody>
  4871. void InterpreterStackFrame::ProfiledLoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, bool isFirstIteration)
  4872. {
  4873. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4874. if (InterruptProbe)
  4875. {
  4876. this->DoInterruptProbe();
  4877. }
  4878. #if ENABLE_TTD
  4879. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  4880. {
  4881. this->scriptContext->GetThreadContext()->TTDExecutionInfo->UpdateLoopCountInfo();
  4882. }
  4883. #endif
  4884. if (!JITLoopBody || this->IsInCatchOrFinallyBlock())
  4885. {
  4886. // For functions having try-catch-finally, jit loop bodies for loops that are contained only in a try block,
  4887. // not even indirect containment in a Catch or Finally.
  4888. return;
  4889. }
  4890. LoopHeader const * loopHeader = DoLoopBodyStart(loopNumber, layoutSize, false, isFirstIteration);
  4891. Assert(loopHeader == nullptr || this->m_functionBody->GetLoopNumber(loopHeader) == loopNumber);
  4892. if (loopHeader != nullptr)
  4893. {
  4894. // We executed jitted loop body, no implicit call information available for this loop
  4895. uint currentOffset = m_reader.GetCurrentOffset();
  4896. if (!loopHeader->Contains(currentOffset) || (m_reader.PeekOp() == OpCode::ProfiledLoopEnd))
  4897. {
  4898. // Restore the outer loop's implicit call flags
  4899. scriptContext->GetThreadContext()->SetImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  4900. }
  4901. else
  4902. {
  4903. // We bailout from the loop, just continue collect implicit call flags for this loop
  4904. }
  4905. }
  4906. }
  4907. #else
  4908. template <LayoutSize layoutSize, bool profiled>
  4909. const byte * InterpreterStackFrame::OP_ProfiledLoopStart(const byte * ip)
  4910. {
  4911. Assert(!profiled);
  4912. return ip;
  4913. }
  4914. template <LayoutSize layoutSize, bool profiled>
  4915. const byte * InterpreterStackFrame::OP_ProfiledLoopEnd(const byte * ip)
  4916. {
  4917. Assert(!profiled);
  4918. return ip;
  4919. }
  4920. template <LayoutSize layoutSize, bool profiled>
  4921. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(uint loopId)
  4922. {
  4923. Assert(!profiled);
  4924. (this->*opLoopBodyStart)(loopId, layoutSize, false /* isFirstIteration */);
  4925. return m_reader.GetIP();
  4926. }
  4927. #endif
  4928. template<bool InterruptProbe, bool JITLoopBody>
  4929. void InterpreterStackFrame::LoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, bool isFirstIteration)
  4930. {
  4931. if (InterruptProbe)
  4932. {
  4933. this->DoInterruptProbe();
  4934. }
  4935. #if ENABLE_TTD
  4936. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  4937. {
  4938. this->scriptContext->GetThreadContext()->TTDExecutionInfo->UpdateLoopCountInfo();
  4939. }
  4940. #endif
  4941. if (!JITLoopBody || this->IsInCatchOrFinallyBlock())
  4942. {
  4943. // For functions having try-catch-finally, jit loop bodies for loops that are contained only in a try block,
  4944. // not even indirect containment in a Catch or Finally.
  4945. return;
  4946. }
  4947. DoLoopBodyStart(loopNumber, layoutSize, true, isFirstIteration);
  4948. }
  4949. LoopHeader const * InterpreterStackFrame::DoLoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, const bool doProfileLoopCheck, const bool isFirstIteration)
  4950. {
  4951. #if ENABLE_PROFILE_INFO
  4952. class AutoRestoreLoopNumbers
  4953. {
  4954. private:
  4955. InterpreterStackFrame *const interpreterStackFrame;
  4956. uint32 loopNumber;
  4957. bool doProfileLoopCheck;
  4958. public:
  4959. AutoRestoreLoopNumbers(InterpreterStackFrame *const interpreterStackFrame, uint32 loopNumber, bool doProfileLoopCheck)
  4960. : interpreterStackFrame(interpreterStackFrame), loopNumber(loopNumber), doProfileLoopCheck(doProfileLoopCheck)
  4961. {
  4962. Assert(interpreterStackFrame->currentLoopNum == LoopHeader::NoLoop);
  4963. interpreterStackFrame->currentLoopNum = loopNumber;
  4964. interpreterStackFrame->m_functionBody->SetRecentlyBailedOutOfJittedLoopBody(false);
  4965. }
  4966. ~AutoRestoreLoopNumbers()
  4967. {
  4968. interpreterStackFrame->currentLoopNum = LoopHeader::NoLoop;
  4969. interpreterStackFrame->currentLoopCounter = 0;
  4970. Js::FunctionBody* fn = interpreterStackFrame->m_functionBody;
  4971. if (fn->RecentlyBailedOutOfJittedLoopBody())
  4972. {
  4973. if (doProfileLoopCheck && interpreterStackFrame->isAutoProfiling)
  4974. {
  4975. // Start profiling the loop after a bailout. Some bailouts require subsequent profile data collection such
  4976. // that the rejitted loop body would not bail out again for the same reason.
  4977. Assert(!interpreterStackFrame->switchProfileMode);
  4978. interpreterStackFrame->switchProfileMode = true;
  4979. Assert(interpreterStackFrame->switchProfileModeOnLoopEndNumber == 0u - 1);
  4980. interpreterStackFrame->switchProfileModeOnLoopEndNumber = loopNumber;
  4981. }
  4982. }
  4983. else
  4984. {
  4985. if (interpreterStackFrame->switchProfileModeOnLoopEndNumber == loopNumber)
  4986. {
  4987. // Stop profiling since the jitted loop body would be exiting the loop
  4988. Assert(!interpreterStackFrame->switchProfileMode);
  4989. interpreterStackFrame->switchProfileMode = true;
  4990. interpreterStackFrame->switchProfileModeOnLoopEndNumber = 0u - 1;
  4991. }
  4992. interpreterStackFrame->scriptContext->GetThreadContext()->DecrementLoopDepth();
  4993. }
  4994. }
  4995. };
  4996. #endif
  4997. Js::FunctionBody* fn = this->m_functionBody;
  4998. Assert(loopNumber < fn->GetLoopCount());
  4999. Assert(!this->IsInCatchOrFinallyBlock());
  5000. Js::LoopHeader *loopHeader = fn->GetLoopHeader(loopNumber);
  5001. loopHeader->isInTry = this->TestFlags(Js::InterpreterStackFrameFlags_WithinTryBlock);
  5002. Js::LoopEntryPointInfo * entryPointInfo = loopHeader->GetCurrentEntryPointInfo();
  5003. if (fn->ForceJITLoopBody() && loopHeader->interpretCount == 0 &&
  5004. (entryPointInfo != NULL && entryPointInfo->IsNotScheduled()))
  5005. {
  5006. #if ENABLE_PROFILE_INFO
  5007. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()))
  5008. {
  5009. scriptContext->GetThreadContext()->AddImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  5010. }
  5011. #endif
  5012. #if ENABLE_NATIVE_CODEGEN
  5013. GenerateLoopBody(scriptContext->GetNativeCodeGenerator(), fn, loopHeader, entryPointInfo, fn->GetLocalsCount(), this->m_localSlots);
  5014. #endif
  5015. }
  5016. #if ENABLE_NATIVE_CODEGEN
  5017. // If we have JITted the loop, call the JITted code
  5018. if (entryPointInfo != NULL && entryPointInfo->IsCodeGenDone())
  5019. {
  5020. #if DBG_DUMP
  5021. if (PHASE_TRACE1(Js::JITLoopBodyPhase) && CONFIG_FLAG(Verbose))
  5022. {
  5023. fn->DumpFunctionId(true);
  5024. Output::Print(_u(": %-20s LoopBody Execute Loop: %2d\n"), fn->GetDisplayName(), loopNumber);
  5025. Output::Flush();
  5026. }
  5027. loopHeader->nativeCount++;
  5028. #endif
  5029. #ifdef BGJIT_STATS
  5030. entryPointInfo->MarkAsUsed();
  5031. #endif
  5032. entryPointInfo->EnsureIsReadyToCall();
  5033. entryPointInfo->nativeEntryPointProcessed = true;
  5034. RegSlot envReg = this->m_functionBody->GetEnvRegister();
  5035. if (envReg != Constants::NoRegister)
  5036. {
  5037. this->SetNonVarReg(envReg, this->LdEnv());
  5038. }
  5039. RegSlot localClosureReg = this->m_functionBody->GetLocalClosureRegister();
  5040. RegSlot localFrameDisplayReg = this->m_functionBody->GetLocalFrameDisplayRegister();
  5041. RegSlot paramClosureReg = this->m_functionBody->GetParamClosureRegister();
  5042. if (entryPointInfo->HasJittedStackClosure())
  5043. {
  5044. // The jitted code is expecting the closure registers to point to known stack locations where
  5045. // the closures can be found and possibly boxed.
  5046. // In a jitted loop body, those locations are the local closure fields on the interpreter instance.
  5047. if (localClosureReg != Constants::NoRegister)
  5048. {
  5049. this->SetNonVarReg(localClosureReg, &this->localClosure);
  5050. }
  5051. if (localFrameDisplayReg != Constants::NoRegister)
  5052. {
  5053. this->SetNonVarReg(localFrameDisplayReg, &this->localFrameDisplay);
  5054. }
  5055. if (paramClosureReg != Constants::NoRegister)
  5056. {
  5057. this->SetNonVarReg(paramClosureReg, &this->paramClosure);
  5058. }
  5059. }
  5060. else
  5061. {
  5062. // In non-stack-closure jitted code, the closure registers are expected to hold the addresses
  5063. // of the actual structures.
  5064. if (localClosureReg != Constants::NoRegister)
  5065. {
  5066. this->SetNonVarReg(localClosureReg, this->localClosure);
  5067. }
  5068. if (localFrameDisplayReg != Constants::NoRegister)
  5069. {
  5070. this->SetNonVarReg(localFrameDisplayReg, this->localFrameDisplay);
  5071. }
  5072. if (paramClosureReg != Constants::NoRegister)
  5073. {
  5074. this->SetNonVarReg(paramClosureReg, this->paramClosure);
  5075. }
  5076. }
  5077. uint32 innerScopeCount = this->m_functionBody->GetInnerScopeCount();
  5078. for (uint32 i = 0; i < innerScopeCount; i++)
  5079. {
  5080. // As with the function-level scope, transfer the inner scopes from the interpreter's side storage
  5081. // to their dedicated register slots.
  5082. SetNonVarReg(this->m_functionBody->GetFirstInnerScopeRegister() + i, InnerScopeFromIndex(i));
  5083. }
  5084. uint newOffset = 0;
  5085. if (fn->GetIsAsmJsFunction())
  5086. {
  5087. AutoRestoreLoopNumbers autoRestore(this, loopNumber, doProfileLoopCheck);
  5088. newOffset = this->CallAsmJsLoopBody(entryPointInfo->jsMethod);
  5089. }
  5090. else
  5091. {
  5092. AutoRestoreLoopNumbers autoRestore(this, loopNumber, doProfileLoopCheck);
  5093. newOffset = this->CallLoopBody(entryPointInfo->jsMethod);
  5094. }
  5095. if (envReg != Constants::NoRegister)
  5096. {
  5097. SetNonVarReg(envReg, nullptr);
  5098. }
  5099. if (localClosureReg != Constants::NoRegister)
  5100. {
  5101. SetNonVarReg(localClosureReg, nullptr);
  5102. }
  5103. if (localFrameDisplayReg != Constants::NoRegister)
  5104. {
  5105. SetNonVarReg(localFrameDisplayReg, nullptr);
  5106. }
  5107. if (paramClosureReg != Constants::NoRegister)
  5108. {
  5109. SetNonVarReg(paramClosureReg, nullptr);
  5110. }
  5111. for (uint32 i = 0; i < innerScopeCount; i++)
  5112. {
  5113. // Get the (possibly updated) scopes from their registers and put them back in side storage.
  5114. // (Getting the updated values may not be necessary, actually, but it can't hurt.)
  5115. // Then null out the registers.
  5116. RegSlot reg = this->m_functionBody->GetFirstInnerScopeRegister() + i;
  5117. SetInnerScopeFromIndex(i, GetNonVarReg(reg));
  5118. SetNonVarReg(reg, nullptr);
  5119. }
  5120. Assert(Js::OpCodeUtil::GetOpCodeLayout(OpCode::ProfiledLoopBodyStart) == Js::OpLayoutType::Unsigned1);
  5121. Assert(Js::OpCodeUtil::GetOpCodeLayout(OpCode::LoopBodyStart) == Js::OpLayoutType::Unsigned1);
  5122. Assert(Js::OpCodeUtil::EncodedSize(Js::OpCode::LoopBodyStart, layoutSize) == Js::OpCodeUtil::EncodedSize(Js::OpCode::ProfiledLoopBodyStart, layoutSize));
  5123. uint byteCodeSize = Js::OpCodeUtil::EncodedSize(Js::OpCode::LoopBodyStart, layoutSize);
  5124. if (layoutSize == SmallLayout)
  5125. {
  5126. byteCodeSize += sizeof(OpLayoutUnsigned1_Small);
  5127. }
  5128. else if (layoutSize == MediumLayout)
  5129. {
  5130. byteCodeSize += sizeof(OpLayoutUnsigned1_Medium);
  5131. }
  5132. else
  5133. {
  5134. byteCodeSize += sizeof(OpLayoutUnsigned1_Large);
  5135. }
  5136. if (newOffset == loopHeader->startOffset || newOffset == m_reader.GetCurrentOffset() - byteCodeSize)
  5137. {
  5138. // If we bail out back the start of the loop, or start of this LoopBodyStart just skip and interpret the loop
  5139. // instead of trying to start the loop body again
  5140. // Increment the interpret count of the loop
  5141. loopHeader->interpretCount++;
  5142. }
  5143. else
  5144. {
  5145. this->CheckIfLoopIsHot(loopHeader->profiledLoopCounter);
  5146. if (newOffset >= loopHeader->endOffset)
  5147. {
  5148. // Reset the totalJittedLoopIterations for the next invocation of this loop entry point
  5149. entryPointInfo->totalJittedLoopIterations =
  5150. static_cast<uint8>(
  5151. min(
  5152. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejit))) *
  5153. (Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout() - 1),
  5154. entryPointInfo->totalJittedLoopIterations));
  5155. entryPointInfo->jittedLoopIterationsSinceLastBailout = 0;
  5156. }
  5157. m_reader.SetCurrentOffset(newOffset);
  5158. }
  5159. return loopHeader;
  5160. }
  5161. #endif
  5162. // Increment the interpret count of the loop
  5163. loopHeader->interpretCount += !isFirstIteration;
  5164. const uint loopInterpretCount = GetFunctionBody()->GetLoopInterpretCount(loopHeader);
  5165. if (loopHeader->interpretCount > loopInterpretCount)
  5166. {
  5167. if (this->scriptContext->GetConfig()->IsNoNative())
  5168. {
  5169. return nullptr;
  5170. }
  5171. if (!fn->DoJITLoopBody())
  5172. {
  5173. return nullptr;
  5174. }
  5175. #if ENABLE_NATIVE_CODEGEN
  5176. #if ENABLE_OOP_NATIVE_CODEGEN
  5177. // If for some reason OOP JIT isn't connected (e.g. it crashed), don't attempt to JIT a loop body
  5178. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !JITManager::GetJITManager()->IsConnected())
  5179. {
  5180. return nullptr;
  5181. }
  5182. #endif
  5183. // If the job is not scheduled then we need to schedule it now.
  5184. // It is possible a job was scheduled earlier and we find ourselves looking at the same entry point
  5185. // again. For example, if the function with the loop was JITed and bailed out then as we finish
  5186. // the call in the interpreter we might encounter a loop for which we had scheduled a JIT job before
  5187. // the function was initially scheduled. In such cases, that old JIT job will complete. If it completes
  5188. // successfully then we can go ahead and use it. If it fails then it will eventually revert to the
  5189. // NotScheduled state. Since transitions from NotScheduled can only occur on the main thread,
  5190. // by checking the state we are safe from racing with the JIT thread when looking at the other fields
  5191. // of the entry point.
  5192. if (entryPointInfo != NULL && entryPointInfo->IsNotScheduled())
  5193. {
  5194. GenerateLoopBody(scriptContext->GetNativeCodeGenerator(), fn, loopHeader, entryPointInfo, fn->GetLocalsCount(), this->m_localSlots);
  5195. }
  5196. #endif
  5197. }
  5198. #if ENABLE_PROFILE_INFO
  5199. else if(
  5200. doProfileLoopCheck &&
  5201. isAutoProfiling &&
  5202. loopHeader->interpretCount > fn->GetLoopProfileThreshold(loopInterpretCount))
  5203. {
  5204. // Start profiling the loop so that the jitted loop body will have some profile data to use
  5205. Assert(!switchProfileMode);
  5206. switchProfileMode = true;
  5207. Assert(switchProfileModeOnLoopEndNumber == 0u - 1);
  5208. switchProfileModeOnLoopEndNumber = loopNumber;
  5209. }
  5210. #endif
  5211. return nullptr;
  5212. }
  5213. void
  5214. InterpreterStackFrame::CheckIfLoopIsHot(uint profiledLoopCounter)
  5215. {
  5216. Js::FunctionBody *fn = this->function->GetFunctionBody();
  5217. if (!fn->GetHasHotLoop() && profiledLoopCounter > (uint)CONFIG_FLAG(JitLoopBodyHotLoopThreshold))
  5218. {
  5219. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5220. if(PHASE_TRACE(Js::JITLoopBodyPhase, fn))
  5221. {
  5222. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5223. Output::Print(
  5224. _u("Speculate Jit set for this function with loopbody: function: %s (%s)\n"),
  5225. fn->GetDisplayName(),
  5226. fn->GetDebugNumberSet(debugStringBuffer));
  5227. Output::Flush();
  5228. }
  5229. #endif
  5230. fn->SetHasHotLoop();
  5231. }
  5232. }
  5233. bool InterpreterStackFrame::CheckAndResetImplicitCall(DisableImplicitFlags prevDisableImplicitFlags, ImplicitCallFlags savedImplicitCallFlags)
  5234. {
  5235. ImplicitCallFlags curImplicitCallFlags = this->scriptContext->GetThreadContext()->GetImplicitCallFlags();
  5236. if (curImplicitCallFlags > ImplicitCall_None)
  5237. {
  5238. //error implicit bit is set , reparse without asmjs
  5239. this->scriptContext->GetThreadContext()->SetDisableImplicitFlags(prevDisableImplicitFlags);
  5240. this->scriptContext->GetThreadContext()->SetImplicitCallFlags(savedImplicitCallFlags);
  5241. return true;
  5242. }
  5243. return false;
  5244. }
  5245. uint
  5246. InterpreterStackFrame::CallLoopBody(JavascriptMethod address)
  5247. {
  5248. #ifdef _M_IX86
  5249. void *savedEsp = NULL;
  5250. __asm
  5251. {
  5252. // Save ESP
  5253. mov savedEsp, esp
  5254. // 8-byte align frame to improve floating point perf of our JIT'd code.
  5255. and esp, -8
  5256. // Add an extra 4-bytes to the stack since we'll be pushing 3 arguments
  5257. push eax
  5258. }
  5259. #endif
  5260. #if defined(_M_ARM32_OR_ARM64)
  5261. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  5262. // Note: this does not seem to affect perf, but if it was, we could add a boolean isCalled to EntryPointInfo
  5263. // and do ISB only for 1st time this entry point is called (potential working set regression though).
  5264. _InstructionSynchronizationBarrier();
  5265. #endif
  5266. uint newOffset = ::Math::PointerCastToIntegral<uint>(
  5267. CALL_ENTRYPOINT_NOASSERT(address, function, CallInfo(CallFlags_InternalFrame, 1), this));
  5268. #ifdef _M_IX86
  5269. _asm
  5270. {
  5271. // Restore ESP
  5272. mov esp, savedEsp
  5273. }
  5274. #endif
  5275. return newOffset;
  5276. }
  5277. uint
  5278. InterpreterStackFrame::CallAsmJsLoopBody(JavascriptMethod address)
  5279. {
  5280. #ifdef _M_IX86
  5281. void *savedEsp = NULL;
  5282. __asm
  5283. {
  5284. // Save ESP
  5285. mov savedEsp, esp
  5286. // Add an extra 4-bytes to the stack since we'll be pushing 3 arguments
  5287. push eax
  5288. }
  5289. #endif
  5290. #if defined(_M_ARM32_OR_ARM64)
  5291. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  5292. // Note: this does not seem to affect perf, but if it was, we could add a boolean isCalled to EntryPointInfo
  5293. // and do ISB only for 1st time this entry point is called (potential working set regression though).
  5294. _InstructionSynchronizationBarrier();
  5295. #endif
  5296. uint newOffset = ::Math::PointerCastToIntegral<uint>(
  5297. CALL_ENTRYPOINT_NOASSERT(address, function, CallInfo(CallFlags_InternalFrame, 1), this));
  5298. #ifdef _M_IX86
  5299. _asm
  5300. {
  5301. // Restore ESP
  5302. mov esp, savedEsp
  5303. }
  5304. #endif
  5305. return newOffset;
  5306. }
  5307. template <class T>
  5308. void InterpreterStackFrame::OP_NewScObjectNoCtorFull(const unaligned T* playout)
  5309. {
  5310. Var function = GetReg(playout->R1);
  5311. Var newObj = JavascriptOperators::NewScObjectNoCtorFull(function, GetScriptContext());
  5312. SetReg(playout->R0, newObj);
  5313. }
  5314. ///----------------------------------------------------------------------------
  5315. ///
  5316. /// InterpreterStackFrame::OP_NewScObject
  5317. ///
  5318. /// OP_NewScObject() allocates a new DynamicObject and initializes it with an
  5319. /// optional "constructor" function.
  5320. ///
  5321. /// NOTE: The return register must be carefully chosen to ensure proper
  5322. /// behavior:
  5323. /// 1. OpCode::NewInstance should never specify "R0" as the register to
  5324. /// store the new instance, because it will get whacked from the
  5325. /// "constructor" function's return value:
  5326. ///
  5327. /// var a1 = Date(); <-- a1 = string returned from Date() function
  5328. /// var a2 = new Date(); <-- a2 = instance return from NewInstance.
  5329. /// Date()'s return value is thrown away.
  5330. ///
  5331. /// 2. If an exception is thrown during construction, the destination
  5332. /// variable / field should __not__ be modified. Therefore, the destination
  5333. /// register should always be a temporary and never a valid local variable.
  5334. /// After successfully returning from the constructor function, the new
  5335. /// instance is valid and may be stored in its final destination variable /
  5336. /// field.
  5337. ///
  5338. /// OPCODE NewObject:
  5339. /// T1 = new DynamicObject(Function.Prototype)
  5340. /// OutArg[0] = T1
  5341. /// Call(Function, ArgCount)
  5342. /// Local[Return] = T1
  5343. ///
  5344. /// - R0: Destination "local" register
  5345. /// - R1: Optional constructor JavascriptFunction instance or 'null'
  5346. ///
  5347. ///----------------------------------------------------------------------------
  5348. template <class T, bool Profiled, bool ICIndex>
  5349. void InterpreterStackFrame::OP_NewScObject_Impl(const unaligned T* playout, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  5350. {
  5351. if (ICIndex)
  5352. {
  5353. Assert(inlineCacheIndex != Js::Constants::NoInlineCacheIndex);
  5354. }
  5355. Var newVarInstance =
  5356. #if ENABLE_PROFILE_INFO
  5357. Profiled ?
  5358. ProfiledNewScObject_Helper(
  5359. GetReg(playout->Function),
  5360. playout->ArgCount,
  5361. static_cast<const unaligned OpLayoutDynamicProfile<T> *>(playout)->profileId,
  5362. inlineCacheIndex,
  5363. spreadIndices) :
  5364. #endif
  5365. NewScObject_Helper(GetReg(playout->Function), playout->ArgCount, spreadIndices);
  5366. SetReg((RegSlot)playout->Return, newVarInstance);
  5367. }
  5368. template <class T, bool Profiled>
  5369. void InterpreterStackFrame::OP_NewScObjArray_Impl(const unaligned T* playout, const Js::AuxArray<uint32> *spreadIndices)
  5370. {
  5371. // Always profile this operation when auto-profiling so that array type changes are tracked
  5372. #if ENABLE_PROFILE_INFO
  5373. if (!Profiled && !isAutoProfiling)
  5374. #else
  5375. Assert(!Profiled);
  5376. #endif
  5377. {
  5378. OP_NewScObject_Impl<T, Profiled, false>(playout, Js::Constants::NoInlineCacheIndex, spreadIndices);
  5379. return;
  5380. }
  5381. #if ENABLE_PROFILE_INFO
  5382. Arguments args(CallInfo(CallFlags_New, playout->ArgCount), m_outParams);
  5383. uint32 spreadSize = 0;
  5384. if (spreadIndices != nullptr)
  5385. {
  5386. spreadSize = JavascriptFunction::GetSpreadSize(args, spreadIndices, scriptContext);
  5387. // Allocate room on the stack for the spread args.
  5388. Arguments outArgs(CallInfo(CallFlags_New, 0), nullptr);
  5389. outArgs.Info.Count = spreadSize;
  5390. const unsigned STACK_ARGS_ALLOCA_THRESHOLD = 8; // Number of stack args we allow before using _alloca
  5391. Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
  5392. size_t outArgsSize = 0;
  5393. if (outArgs.Info.Count > STACK_ARGS_ALLOCA_THRESHOLD)
  5394. {
  5395. PROBE_STACK(scriptContext, outArgs.Info.Count * sizeof(Var) + Js::Constants::MinStackDefault); // args + function call
  5396. outArgsSize = outArgs.Info.Count * sizeof(Var);
  5397. outArgs.Values = (Var*)_alloca(outArgsSize);
  5398. ZeroMemory(outArgs.Values, outArgsSize);
  5399. }
  5400. else
  5401. {
  5402. outArgs.Values = stackArgs;
  5403. outArgsSize = STACK_ARGS_ALLOCA_THRESHOLD * sizeof(Var);
  5404. ZeroMemory(outArgs.Values, outArgsSize); // We may not use all of the elements
  5405. }
  5406. JavascriptFunction::SpreadArgs(args, outArgs, spreadIndices, scriptContext);
  5407. SetReg(
  5408. (RegSlot)playout->Return,
  5409. ProfilingHelpers::ProfiledNewScObjArray(
  5410. GetReg(playout->Function),
  5411. outArgs,
  5412. function,
  5413. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId,
  5414. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId2));
  5415. }
  5416. else
  5417. {
  5418. SetReg(
  5419. (RegSlot)playout->Return,
  5420. ProfilingHelpers::ProfiledNewScObjArray(
  5421. GetReg(playout->Function),
  5422. args,
  5423. function,
  5424. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId,
  5425. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId2));
  5426. }
  5427. PopOut(playout->ArgCount);
  5428. #endif
  5429. }
  5430. void InterpreterStackFrame::OP_NewScObject_A_Impl(const unaligned OpLayoutAuxiliary * playout, RegSlot *target)
  5431. {
  5432. const Js::VarArrayVarCount * vars = Js::ByteCodeReader::ReadVarArrayVarCount(playout->Offset, this->GetFunctionBody());
  5433. int count = Js::TaggedInt::ToInt32(vars->count);
  5434. // Push the parameters to stack
  5435. for (int i=0;i<count; i++)
  5436. {
  5437. SetOut( (ArgSlot)(i+1), vars->elements[i]);
  5438. }
  5439. Var newVarInstance = NewScObject_Helper(GetReg((RegSlot)playout->C1), (ArgSlot)count+1);
  5440. SetReg((RegSlot)playout->R0, newVarInstance);
  5441. }
  5442. Var InterpreterStackFrame::NewScObject_Helper(Var target, ArgSlot ArgCount, const Js::AuxArray<uint32> *spreadIndices)
  5443. {
  5444. Arguments args(CallInfo(CallFlags_New, ArgCount), m_outParams);
  5445. Var newVarInstance = JavascriptOperators::NewScObject(target, args, GetScriptContext(), spreadIndices);
  5446. PopOut(ArgCount);
  5447. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newVarInstance));
  5448. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5449. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5450. {
  5451. newVarInstance = JavascriptProxy::AutoProxyWrapper(newVarInstance);
  5452. // this might come from a different scriptcontext.
  5453. newVarInstance = CrossSite::MarshalVar(GetScriptContext(), newVarInstance);
  5454. }
  5455. #endif
  5456. #ifdef ENABLE_BASIC_TELEMETRY
  5457. {
  5458. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().NewScriptObject( target, args, newVarInstance );
  5459. }
  5460. #endif
  5461. return newVarInstance;
  5462. }
  5463. #if ENABLE_PROFILE_INFO
  5464. Var InterpreterStackFrame::ProfiledNewScObject_Helper(Var target, ArgSlot ArgCount, ProfileId profileId, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  5465. {
  5466. Arguments args(CallInfo(CallFlags_New, ArgCount), m_outParams);
  5467. Var newVarInstance =
  5468. ProfilingHelpers::ProfiledNewScObject(
  5469. target,
  5470. args,
  5471. GetFunctionBody(),
  5472. profileId,
  5473. inlineCacheIndex,
  5474. spreadIndices);
  5475. PopOut(ArgCount);
  5476. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newVarInstance));
  5477. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5478. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5479. {
  5480. newVarInstance = JavascriptProxy::AutoProxyWrapper(newVarInstance);
  5481. // this might come from a different scriptcontext.
  5482. newVarInstance = CrossSite::MarshalVar(GetScriptContext(), newVarInstance);
  5483. }
  5484. #endif
  5485. #ifdef TELEMETRY_PROFILED
  5486. {
  5487. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().NewScriptObject( target, args, newVarInstance );
  5488. }
  5489. #endif
  5490. return newVarInstance;
  5491. }
  5492. #endif
  5493. template <typename T>
  5494. void InterpreterStackFrame::OP_LdElementUndefined(const unaligned OpLayoutT_ElementU<T>* playout)
  5495. {
  5496. if (this->m_functionBody->IsEval())
  5497. {
  5498. JavascriptOperators::OP_LoadUndefinedToElementDynamic(GetReg(playout->Instance),
  5499. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  5500. }
  5501. else
  5502. {
  5503. JavascriptOperators::OP_LoadUndefinedToElement(GetReg(playout->Instance),
  5504. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  5505. }
  5506. }
  5507. template <typename T>
  5508. void InterpreterStackFrame::OP_LdLocalElementUndefined(const unaligned OpLayoutT_ElementRootU<T>* playout)
  5509. {
  5510. if (this->m_functionBody->IsEval())
  5511. {
  5512. JavascriptOperators::OP_LoadUndefinedToElementDynamic(this->localClosure,
  5513. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  5514. }
  5515. else
  5516. {
  5517. JavascriptOperators::OP_LoadUndefinedToElement(this->localClosure,
  5518. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  5519. }
  5520. }
  5521. template <typename T>
  5522. void InterpreterStackFrame::OP_LdElementUndefinedScoped(const unaligned OpLayoutT_ElementScopedU<T>* playout)
  5523. {
  5524. // Implicit root object as default instance
  5525. JavascriptOperators::OP_LoadUndefinedToElementScoped(GetEnvForEvalCode(),
  5526. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  5527. }
  5528. void InterpreterStackFrame::OP_ChkUndecl(Var aValue)
  5529. {
  5530. if (this->scriptContext->IsUndeclBlockVar(aValue))
  5531. {
  5532. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  5533. }
  5534. }
  5535. void InterpreterStackFrame::OP_ChkNewCallFlag()
  5536. {
  5537. if (!(this->m_callFlags & CallFlags_New) && !this->TestFlags(InterpreterStackFrameFlags_FromBailOutInInlinee))
  5538. {
  5539. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew);
  5540. }
  5541. }
  5542. void InterpreterStackFrame::OP_EnsureNoRootProperty(uint propertyIdIndex)
  5543. {
  5544. Var instance = this->GetRootObject();
  5545. JavascriptOperators::OP_EnsureNoRootProperty(instance, this->m_functionBody->GetReferencedPropertyId(propertyIdIndex));
  5546. }
  5547. void InterpreterStackFrame::OP_EnsureNoRootRedeclProperty(uint propertyIdIndex)
  5548. {
  5549. Var instance = this->GetRootObject();
  5550. JavascriptOperators::OP_EnsureNoRootRedeclProperty(instance, this->m_functionBody->GetReferencedPropertyId(propertyIdIndex));
  5551. }
  5552. void InterpreterStackFrame::OP_ScopedEnsureNoRedeclProperty(Var aValue, uint propertyIdIndex, Var aValue2)
  5553. {
  5554. Js::PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  5555. JavascriptOperators::OP_ScopedEnsureNoRedeclProperty((FrameDisplay*)aValue, propertyId, aValue2);
  5556. }
  5557. Var InterpreterStackFrame::OP_InitUndecl()
  5558. {
  5559. return this->scriptContext->GetLibrary()->GetUndeclBlockVar();
  5560. }
  5561. void InterpreterStackFrame::OP_InitUndeclSlot(Var aValue, int32 slot)
  5562. {
  5563. this->OP_StSlot(aValue, slot, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  5564. }
  5565. void InterpreterStackFrame::OP_TryCatch(const unaligned OpLayoutBr* playout)
  5566. {
  5567. Js::JavascriptExceptionObject* exception = NULL;
  5568. try
  5569. {
  5570. this->nestedTryDepth++;
  5571. // mark the stackFrame as 'in try block'
  5572. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5573. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  5574. #ifdef ENABLE_SCRIPT_DEBUGGING
  5575. if (this->IsInDebugMode())
  5576. {
  5577. #if ENABLE_TTD
  5578. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5579. {
  5580. this->ProcessWithDebugging_PreviousStmtTracking();
  5581. }
  5582. else
  5583. {
  5584. this->ProcessWithDebugging();
  5585. }
  5586. #else
  5587. this->ProcessWithDebugging();
  5588. #endif
  5589. this->TrySetRetOffset();
  5590. }
  5591. else
  5592. #endif
  5593. {
  5594. this->Process();
  5595. this->TrySetRetOffset();
  5596. }
  5597. }
  5598. catch (const Js::JavascriptException& err)
  5599. {
  5600. // We are using C++ exception handling which does not unwind the stack in the catch block.
  5601. // For stack overflow and OOM exceptions, we cannot run user code here because the stack is not unwind.
  5602. exception = err.GetAndClear();
  5603. }
  5604. if (--this->nestedTryDepth == -1)
  5605. {
  5606. // unmark the stackFrame as 'in try block'
  5607. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5608. }
  5609. // Now that the stack is unwound, let's run the catch block.
  5610. if (exception)
  5611. {
  5612. if (exception->IsGeneratorReturnException())
  5613. {
  5614. // Generator return scenario, so no need to go into the catch block and we must rethrow to propagate the exception to down level
  5615. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5616. }
  5617. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5618. // We've got a JS exception. Grab the exception object and assign it to the
  5619. // catch object's location, then call the handler (i.e., we consume the Catch op here).
  5620. Var catchObject = exception->GetThrownObject(scriptContext);
  5621. m_reader.SetCurrentRelativeOffset((const byte *)(playout + 1), playout->RelativeJumpOffset);
  5622. LayoutSize layoutSize;
  5623. OpCode catchOp = m_reader.ReadOp(layoutSize);
  5624. #ifdef BYTECODE_BRANCH_ISLAND
  5625. if (catchOp == Js::OpCode::BrLong)
  5626. {
  5627. Assert(layoutSize == SmallLayout);
  5628. auto playoutBrLong = m_reader.BrLong();
  5629. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5630. catchOp = m_reader.ReadOp(layoutSize);
  5631. }
  5632. #endif
  5633. AssertMsg(catchOp == OpCode::Catch, "Catch op not found at catch offset");
  5634. RegSlot reg = layoutSize == SmallLayout ? m_reader.Reg1_Small()->R0 :
  5635. layoutSize == MediumLayout ? m_reader.Reg1_Medium()->R0 : m_reader.Reg1_Large()->R0;
  5636. SetReg(reg, catchObject);
  5637. ResetOut();
  5638. this->nestedCatchDepth++;
  5639. // mark the stackFrame as 'in catch block'
  5640. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5641. this->ProcessCatch();
  5642. if (--this->nestedCatchDepth == -1)
  5643. {
  5644. // unmark the stackFrame as 'in catch block'
  5645. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5646. }
  5647. }
  5648. }
  5649. void InterpreterStackFrame::ProcessCatch()
  5650. {
  5651. #if ENABLE_TTD
  5652. //Clear any previous Exception Info
  5653. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5654. {
  5655. this->scriptContext->GetThreadContext()->TTDExecutionInfo->ProcessCatchInfoForLastExecutedStatements();
  5656. }
  5657. #endif
  5658. #ifdef ENABLE_SCRIPT_DEBUGGING
  5659. if (this->IsInDebugMode())
  5660. {
  5661. this->DebugProcess();
  5662. }
  5663. else
  5664. #endif
  5665. {
  5666. this->Process();
  5667. }
  5668. }
  5669. int InterpreterStackFrame::ProcessFinally()
  5670. {
  5671. this->nestedFinallyDepth++;
  5672. int newOffset = 0;
  5673. #ifdef ENABLE_SCRIPT_DEBUGGING
  5674. if (this->IsInDebugMode())
  5675. {
  5676. newOffset = ::Math::PointerCastToIntegral<int>(this->DebugProcess());
  5677. }
  5678. else
  5679. #endif
  5680. {
  5681. newOffset = ::Math::PointerCastToIntegral<int>(this->Process());
  5682. }
  5683. return newOffset;
  5684. }
  5685. void InterpreterStackFrame::ProcessTryHandlerBailout(EHBailoutData * ehBailoutData, uint32 tryNestingDepth)
  5686. {
  5687. int catchOffset = ehBailoutData->catchOffset;
  5688. int finallyOffset = ehBailoutData->finallyOffset;
  5689. Js::JavascriptExceptionObject* exception = NULL;
  5690. if (catchOffset != 0 || finallyOffset != 0)
  5691. {
  5692. try
  5693. {
  5694. this->nestedTryDepth++;
  5695. // mark the stackFrame as 'in try block'
  5696. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5697. if (tryNestingDepth != 0)
  5698. {
  5699. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5700. }
  5701. if (catchOffset != 0)
  5702. {
  5703. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  5704. }
  5705. #ifdef ENABLE_SCRIPT_DEBUGGING
  5706. if (this->IsInDebugMode())
  5707. {
  5708. #if ENABLE_TTD
  5709. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5710. {
  5711. this->ProcessWithDebugging_PreviousStmtTracking();
  5712. }
  5713. else
  5714. {
  5715. this->ProcessWithDebugging();
  5716. }
  5717. #else
  5718. this->ProcessWithDebugging();
  5719. #endif
  5720. this->TrySetRetOffset();
  5721. }
  5722. else
  5723. #endif
  5724. {
  5725. this->Process();
  5726. this->TrySetRetOffset();
  5727. }
  5728. }
  5729. catch (const Js::JavascriptException& err)
  5730. {
  5731. // We are using C++ exception handling which does not unwind the stack in the catch block.
  5732. // For stack overflow and OOM exceptions, we cannot run user code here because the stack is not unwind.
  5733. exception = err.GetAndClear();
  5734. }
  5735. }
  5736. else if (ehBailoutData->ht == HandlerType::HT_Catch)
  5737. {
  5738. this->nestedCatchDepth++;
  5739. // mark the stackFrame as 'in catch block'
  5740. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5741. if (tryNestingDepth != 0)
  5742. {
  5743. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5744. }
  5745. this->ProcessCatch();
  5746. if (--this->nestedCatchDepth == -1)
  5747. {
  5748. // unmark the stackFrame as 'in catch block'
  5749. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5750. }
  5751. return;
  5752. }
  5753. else
  5754. {
  5755. Assert(ehBailoutData->ht == HandlerType::HT_Finally);
  5756. this->nestedFinallyDepth++;
  5757. // mark the stackFrame as 'in finally block'
  5758. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5759. if (tryNestingDepth != 0)
  5760. {
  5761. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5762. }
  5763. Js::JavascriptExceptionObject * exceptionObj = this->scriptContext->GetThreadContext()->GetPendingFinallyException();
  5764. this->scriptContext->GetThreadContext()->SetPendingFinallyException(nullptr);
  5765. int finallyEndOffset = this->ProcessFinally();
  5766. if (--this->nestedFinallyDepth == -1)
  5767. {
  5768. // unmark the stackFrame as 'in finally block'
  5769. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5770. }
  5771. // Finally exited with LeaveNull, We don't throw for early returns
  5772. if (finallyEndOffset == 0 && exceptionObj)
  5773. {
  5774. JavascriptExceptionOperators::DoThrow(const_cast<Js::JavascriptExceptionObject *>(exceptionObj), scriptContext);
  5775. }
  5776. if (finallyEndOffset != 0)
  5777. {
  5778. m_reader.SetCurrentOffset(finallyEndOffset);
  5779. }
  5780. return;
  5781. }
  5782. if (--this->nestedTryDepth == -1)
  5783. {
  5784. // unmark the stackFrame as 'in try block'
  5785. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5786. }
  5787. // Now that the stack is unwound, let's run the catch block.
  5788. if (exception)
  5789. {
  5790. if (exception->IsGeneratorReturnException())
  5791. {
  5792. // Generator return scenario, so no need to go into the catch block and we must rethrow to propagate the exception to down level
  5793. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5794. }
  5795. if (catchOffset != 0)
  5796. {
  5797. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5798. // We've got a JS exception. Grab the exception object and assign it to the
  5799. // catch object's location, then call the handler (i.e., we consume the Catch op here).
  5800. Var catchObject = exception->GetThrownObject(scriptContext);
  5801. m_reader.SetCurrentOffset(catchOffset);
  5802. LayoutSize layoutSize;
  5803. OpCode catchOp = m_reader.ReadOp(layoutSize);
  5804. #ifdef BYTECODE_BRANCH_ISLAND
  5805. if (catchOp == Js::OpCode::BrLong)
  5806. {
  5807. Assert(layoutSize == SmallLayout);
  5808. auto playoutBrLong = m_reader.BrLong();
  5809. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5810. catchOp = m_reader.ReadOp(layoutSize);
  5811. }
  5812. #endif
  5813. AssertMsg(catchOp == OpCode::Catch, "Catch op not found at catch offset");
  5814. RegSlot reg = layoutSize == SmallLayout ? m_reader.Reg1_Small()->R0 :
  5815. layoutSize == MediumLayout ? m_reader.Reg1_Medium()->R0 : m_reader.Reg1_Large()->R0;
  5816. SetReg(reg, catchObject);
  5817. ResetOut();
  5818. this->nestedCatchDepth++;
  5819. // mark the stackFrame as 'in catch block'
  5820. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5821. this->ProcessCatch();
  5822. if (--this->nestedCatchDepth == -1)
  5823. {
  5824. // unmark the stackFrame as 'in catch block'
  5825. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5826. }
  5827. }
  5828. else
  5829. {
  5830. Assert(finallyOffset != 0);
  5831. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5832. m_reader.SetCurrentOffset(finallyOffset);
  5833. ResetOut();
  5834. this->nestedFinallyDepth++;
  5835. // mark the stackFrame as 'in finally block'
  5836. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5837. LayoutSize layoutSize;
  5838. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  5839. #ifdef BYTECODE_BRANCH_ISLAND
  5840. if (finallyOp == Js::OpCode::BrLong)
  5841. {
  5842. Assert(layoutSize == SmallLayout);
  5843. auto playoutBrLong = m_reader.BrLong();
  5844. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5845. finallyOp = m_reader.ReadOp(layoutSize);
  5846. }
  5847. #endif
  5848. Assert(finallyOp == Js::OpCode::Finally);
  5849. int finallyEndOffset = this->ProcessFinally();
  5850. if (--this->nestedFinallyDepth == -1)
  5851. {
  5852. // unmark the stackFrame as 'in finally block'
  5853. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5854. }
  5855. if (finallyEndOffset == 0)
  5856. {
  5857. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5858. }
  5859. m_reader.SetCurrentOffset(finallyEndOffset);
  5860. }
  5861. }
  5862. else
  5863. {
  5864. if (finallyOffset != 0)
  5865. {
  5866. int currOffset = m_reader.GetCurrentOffset();
  5867. m_reader.SetCurrentOffset(finallyOffset);
  5868. this->nestedFinallyDepth++;
  5869. // mark the stackFrame as 'in finally block'
  5870. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5871. LayoutSize layoutSize;
  5872. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  5873. #ifdef BYTECODE_BRANCH_ISLAND
  5874. if (finallyOp == Js::OpCode::BrLong)
  5875. {
  5876. Assert(layoutSize == SmallLayout);
  5877. auto playoutBrLong = m_reader.BrLong();
  5878. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5879. finallyOp = m_reader.ReadOp(layoutSize);
  5880. }
  5881. #endif
  5882. Assert(finallyOp == Js::OpCode::Finally);
  5883. int finallyEndOffset = this->ProcessFinally();
  5884. if (--this->nestedFinallyDepth == -1)
  5885. {
  5886. // unmark the stackFrame as 'in finally block'
  5887. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5888. }
  5889. if (finallyEndOffset == 0)
  5890. {
  5891. m_reader.SetCurrentOffset(currOffset);
  5892. }
  5893. }
  5894. }
  5895. }
  5896. void InterpreterStackFrame::TrySetRetOffset()
  5897. {
  5898. Assert(this->TestFlags(Js::InterpreterStackFrameFlags_WithinTryBlock));
  5899. // It may happen that a JITted loop body returned the offset of RET. If the loop body was
  5900. // called from a try, the interpreter "Process()" should also just return.
  5901. if (this->retOffset != 0)
  5902. {
  5903. m_reader.SetCurrentOffset(this->retOffset);
  5904. }
  5905. }
  5906. bool InterpreterStackFrame::IsInCatchOrFinallyBlock()
  5907. {
  5908. return this->TestFlags(Js::InterpreterStackFrameFlags_WithinCatchBlock) ||
  5909. this->TestFlags(Js::InterpreterStackFrameFlags_WithinFinallyBlock);
  5910. }
  5911. void InterpreterStackFrame::OP_BeginBodyScope()
  5912. {
  5913. // Currently we are using the closures created for the param scope.
  5914. // This marks the beginning of the body scope, so let's create new closures for the body scope.
  5915. FunctionBody *executeFunction = this->function->GetFunctionBody();
  5916. Assert(!this->IsParamScopeDone() && !executeFunction->IsParamAndBodyScopeMerged());
  5917. // Save the current closure. We have to use this while copying the initial value of body symbols
  5918. // from the corresponding symbols in the param.
  5919. this->SetParamClosure(this->GetLocalClosure());
  5920. this->SetNonVarReg(executeFunction->GetParamClosureRegister(), nullptr);
  5921. this->SetIsParamScopeDone(true);
  5922. // Create a new local closure for the body when either body scope has scope slots allocated or
  5923. // eval is present which can leak declarations.
  5924. if (executeFunction->scopeSlotArraySize > 0 || executeFunction->HasScopeObject())
  5925. {
  5926. this->InitializeClosures();
  5927. }
  5928. }
  5929. void InterpreterStackFrame::OP_ResumeCatch()
  5930. {
  5931. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5932. #ifdef ENABLE_SCRIPT_DEBUGGING
  5933. if (this->IsInDebugMode())
  5934. {
  5935. this->DebugProcess();
  5936. }
  5937. else
  5938. #endif
  5939. {
  5940. this->Process();
  5941. }
  5942. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5943. }
  5944. /// ---------------------------------------------------------------------------------------------------
  5945. /// The behavior we want is the following:
  5946. /// - If the control leaves the user's try without throwing, execute the finally and continue
  5947. /// after the end of the try.
  5948. /// - If the user code throws, catch this exception and then execute this finally while unwinding to
  5949. /// the handler (if any).
  5950. /// ---------------------------------------------------------------------------------------------------
  5951. void InterpreterStackFrame::ProcessTryFinally(const byte* ip, Js::JumpOffset jumpOffset, Js::RegSlot regException, Js::RegSlot regOffset, bool hasYield)
  5952. {
  5953. Js::JavascriptExceptionObject* pExceptionObject = nullptr;
  5954. bool skipFinallyBlock = false;
  5955. try
  5956. {
  5957. Js::Var result = nullptr;
  5958. this->nestedTryDepth++;
  5959. // mark the stackFrame as 'in try block'
  5960. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5961. if (shouldCacheSP)
  5962. {
  5963. CacheSp();
  5964. }
  5965. #ifdef ENABLE_SCRIPT_DEBUGGING
  5966. if (this->IsInDebugMode())
  5967. {
  5968. #if ENABLE_TTD
  5969. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5970. {
  5971. result = this->ProcessWithDebugging_PreviousStmtTracking();
  5972. }
  5973. else
  5974. {
  5975. result = this->ProcessWithDebugging();
  5976. }
  5977. #else
  5978. result = this->ProcessWithDebugging();
  5979. #endif
  5980. }
  5981. else
  5982. #endif
  5983. {
  5984. result = this->Process();
  5985. }
  5986. if (result == nullptr)
  5987. {
  5988. Assert(hasYield);
  5989. skipFinallyBlock = true;
  5990. }
  5991. }
  5992. catch (const Js::JavascriptException& err)
  5993. {
  5994. pExceptionObject = err.GetAndClear();
  5995. }
  5996. if (--this->nestedTryDepth == -1)
  5997. {
  5998. // unmark the stackFrame as 'in try block'
  5999. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock);
  6000. }
  6001. shouldCacheSP = !skipFinallyBlock;
  6002. if (skipFinallyBlock)
  6003. {
  6004. // A leave occurred due to a yield
  6005. return;
  6006. }
  6007. // Save the current IP so execution can continue there if the finally doesn't
  6008. // take control of the flow.
  6009. int newOffset = 0;
  6010. int currOffset = m_reader.GetCurrentOffset();
  6011. if (hasYield)
  6012. {
  6013. // save the exception if there is one to a register in case we yield during the finally block
  6014. // and need to get that exception object back upon resume in OP_ResumeFinally
  6015. SetNonVarReg(regException, pExceptionObject);
  6016. SetNonVarReg(regOffset, reinterpret_cast<Js::Var>(currOffset));
  6017. }
  6018. if (pExceptionObject && !pExceptionObject->IsGeneratorReturnException())
  6019. {
  6020. // Clone static exception object early in case finally block overwrites it
  6021. pExceptionObject = pExceptionObject->CloneIfStaticExceptionObject(scriptContext);
  6022. }
  6023. #ifdef ENABLE_SCRIPT_DEBUGGING
  6024. if (pExceptionObject && this->IsInDebugMode() &&
  6025. pExceptionObject != scriptContext->GetThreadContext()->GetPendingSOErrorObject())
  6026. {
  6027. // Swallowing an exception that has triggered a finally is not implemented
  6028. // (This appears to be the same behavior as ie8)
  6029. pExceptionObject->SetDebuggerSkip(false);
  6030. }
  6031. #endif
  6032. // Call into the finally by setting the IP, consuming the Finally, and letting the interpreter recurse.
  6033. m_reader.SetCurrentRelativeOffset(ip, jumpOffset);
  6034. RestoreSp();
  6035. // mark the stackFrame as 'in finally block'
  6036. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6037. LayoutSize layoutSize;
  6038. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  6039. #ifdef BYTECODE_BRANCH_ISLAND
  6040. if (finallyOp == Js::OpCode::BrLong)
  6041. {
  6042. Assert(layoutSize == SmallLayout);
  6043. auto playoutBrLong = m_reader.BrLong();
  6044. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  6045. finallyOp = m_reader.ReadOp(layoutSize);
  6046. }
  6047. #endif
  6048. AssertMsg(finallyOp == OpCode::Finally, "Finally op not found at catch offset");
  6049. newOffset = this->ProcessFinally();
  6050. if (--this->nestedFinallyDepth == -1)
  6051. {
  6052. // unmark the stackFrame as 'in finally block'
  6053. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6054. }
  6055. bool endOfFinallyBlock = newOffset == 0;
  6056. if (endOfFinallyBlock)
  6057. {
  6058. // Finally completed without taking over the flow. Resume where we left off before calling it.
  6059. m_reader.SetCurrentOffset(currOffset);
  6060. }
  6061. else
  6062. {
  6063. // Finally seized the flow with a jump out of its scope. Resume at the jump target and
  6064. // force the runtime to return to this frame without executing the catch.
  6065. m_reader.SetCurrentOffset(newOffset);
  6066. return;
  6067. }
  6068. if (pExceptionObject && (endOfFinallyBlock || !pExceptionObject->IsGeneratorReturnException()))
  6069. {
  6070. JavascriptExceptionOperators::DoThrow(pExceptionObject, scriptContext);
  6071. }
  6072. }
  6073. void InterpreterStackFrame::OP_TryFinally(const unaligned OpLayoutBr* playout)
  6074. {
  6075. ProcessTryFinally((const byte*)(playout + 1), playout->RelativeJumpOffset);
  6076. }
  6077. void InterpreterStackFrame::OP_TryFinallyWithYield(const byte* ip, Js::JumpOffset jumpOffset, Js::RegSlot regException, Js::RegSlot regOffset)
  6078. {
  6079. ProcessTryFinally(ip, jumpOffset, regException, regOffset, true);
  6080. }
  6081. void InterpreterStackFrame::OP_ResumeFinally(const byte* ip, Js::JumpOffset jumpOffset, RegSlot exceptionRegSlot, RegSlot offsetRegSlot)
  6082. {
  6083. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6084. int newOffset = 0;
  6085. #ifdef ENABLE_SCRIPT_DEBUGGING
  6086. if (this->IsInDebugMode())
  6087. {
  6088. newOffset = ::Math::PointerCastToIntegral<int>(this->DebugProcess());
  6089. }
  6090. else
  6091. #endif
  6092. {
  6093. newOffset = ::Math::PointerCastToIntegral<int>(this->Process());
  6094. }
  6095. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6096. bool endOfFinallyBlock = newOffset == 0;
  6097. if (endOfFinallyBlock)
  6098. {
  6099. // Finally completed without taking over the flow. Resume where we left off before calling it.
  6100. int currOffset = ::Math::PointerCastToIntegral<int>(GetNonVarReg(offsetRegSlot));
  6101. m_reader.SetCurrentOffset(currOffset);
  6102. }
  6103. else
  6104. {
  6105. // Finally seized the flow with a jump out of its scope. Resume at the jump target and
  6106. // force the runtime to return to this frame without executing the catch.
  6107. m_reader.SetCurrentOffset(newOffset);
  6108. return;
  6109. }
  6110. Js::JavascriptExceptionObject* exceptionObj = (Js::JavascriptExceptionObject*)GetNonVarReg(exceptionRegSlot);
  6111. if (exceptionObj && (endOfFinallyBlock || !exceptionObj->IsGeneratorReturnException()))
  6112. {
  6113. JavascriptExceptionOperators::DoThrow(exceptionObj, scriptContext);
  6114. }
  6115. }
  6116. template <typename T>
  6117. void InterpreterStackFrame::OP_IsInst(const unaligned T* playout)
  6118. {
  6119. Var instance = GetReg(playout->R1);
  6120. Var function = GetReg(playout->R2);
  6121. IsInstInlineCache *inlineCache = this->GetIsInstInlineCache(playout->inlineCacheIndex);
  6122. ScriptContext* scriptContext = GetScriptContext();
  6123. Var result = JavascriptOperators::OP_IsInst(instance, function, scriptContext, inlineCache);
  6124. #ifdef ENABLE_BASIC_TELEMETRY
  6125. {
  6126. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().IsInstanceOf(instance, function, result);
  6127. }
  6128. #endif
  6129. SetReg(playout->R0, result);
  6130. }
  6131. template <typename T>
  6132. void InterpreterStackFrame::OP_ApplyArgs(const unaligned OpLayoutT_Reg5<T> * playout)
  6133. {
  6134. // Always save and restore implicit call flags when calling out
  6135. // REVIEW: Can we avoid it if we don't collect dynamic profile info?
  6136. ThreadContext * threadContext = scriptContext->GetThreadContext();
  6137. Js::ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  6138. // Currently ApplyArgs is equivalent to CallFldVoid (where we don't use the return value)
  6139. Var v=GetNonVarReg(playout->R4);
  6140. JavascriptOperators::OP_ApplyArgs(GetReg(playout->R1),GetReg(playout->R2),
  6141. (void**)GetNonVarReg(playout->R3),*((CallInfo*)&v),GetScriptContext());
  6142. threadContext->SetImplicitCallFlags(savedImplicitCallFlags);
  6143. }
  6144. void InterpreterStackFrame::OP_SpreadArrayLiteral(const unaligned OpLayoutReg2Aux * playout)
  6145. {
  6146. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  6147. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  6148. threadContext->ClearImplicitCallFlags();
  6149. Var instance = GetReg(playout->R1);
  6150. #if ENABLE_COPYONACCESS_ARRAY
  6151. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  6152. #endif
  6153. const Js::AuxArray<uint32> *spreadIndices = m_reader.ReadAuxArray<uint32>(playout->Offset, this->GetFunctionBody());
  6154. ScriptContext* scriptContext = GetScriptContext();
  6155. Var result = JavascriptArray::SpreadArrayArgs(instance, spreadIndices, scriptContext);
  6156. threadContext->CheckAndResetImplicitCallAccessorFlag();
  6157. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  6158. SetReg(playout->R0, result);
  6159. }
  6160. FrameDisplay *
  6161. InterpreterStackFrame::OP_LdInnerFrameDisplay(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6162. {
  6163. JavascriptOperators::CheckInnerFrameDisplayArgument(argHead);
  6164. return OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6165. }
  6166. FrameDisplay *
  6167. InterpreterStackFrame::OP_LdInnerFrameDisplayNoParent(void *argHead, ScriptContext *scriptContext)
  6168. {
  6169. JavascriptOperators::CheckInnerFrameDisplayArgument(argHead);
  6170. return OP_LdFrameDisplayNoParent<true>(argHead, scriptContext);
  6171. }
  6172. FrameDisplay *
  6173. InterpreterStackFrame::OP_LdFrameDisplay(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6174. {
  6175. FrameDisplay *frameDisplay;
  6176. bool strict = this->m_functionBody->GetIsStrictMode();
  6177. if (strict)
  6178. {
  6179. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplay(argHead, argEnv, scriptContext);
  6180. }
  6181. else
  6182. {
  6183. frameDisplay = JavascriptOperators::OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6184. }
  6185. return frameDisplay;
  6186. }
  6187. FrameDisplay *
  6188. InterpreterStackFrame::OP_LdFrameDisplaySetLocal(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6189. {
  6190. FrameDisplay *frameDisplay = OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6191. this->SetLocalFrameDisplay(frameDisplay);
  6192. return frameDisplay;
  6193. }
  6194. FrameDisplay *
  6195. InterpreterStackFrame::NewFrameDisplay(void *argHead, void *argEnv)
  6196. {
  6197. FrameDisplay *frameDisplay;
  6198. bool strict = this->m_functionBody->GetIsStrictMode();
  6199. if (!this->m_functionBody->DoStackFrameDisplay() || !this->GetLocalFrameDisplay())
  6200. {
  6201. // Null local frame display probably indicates that we bailed out of an inlinee.
  6202. // Once we support stack closures in inlined functions, we can just assert that this value
  6203. // is never null if we should be allocating on the stack.
  6204. return this->OP_LdFrameDisplaySetLocal(argHead, argEnv, this->GetScriptContext());
  6205. }
  6206. frameDisplay = this->GetLocalFrameDisplay();
  6207. Assert(frameDisplay != nullptr);
  6208. frameDisplay->SetTag(true);
  6209. frameDisplay->SetStrictMode(strict);
  6210. frameDisplay->SetLength(this->m_functionBody->GetEnvDepth() + 1);
  6211. Assert(frameDisplay->GetLength() == ((FrameDisplay*)argEnv)->GetLength() + 1);
  6212. for (uint i = 0; i < ((FrameDisplay*)argEnv)->GetLength(); i++)
  6213. {
  6214. frameDisplay->SetItem(i + 1, ((FrameDisplay*)argEnv)->GetItem(i));
  6215. }
  6216. frameDisplay->SetItem(0, argHead);
  6217. return frameDisplay;
  6218. }
  6219. template<bool innerFD>
  6220. FrameDisplay *
  6221. InterpreterStackFrame::OP_LdFrameDisplayNoParent(void *argHead, ScriptContext *scriptContext)
  6222. {
  6223. FrameDisplay *frameDisplay;
  6224. bool strict = this->m_functionBody->GetIsStrictMode();
  6225. Var argEnv = nullptr;
  6226. if (innerFD && this->m_functionBody->GetLocalFrameDisplayRegister() != Constants::NoRegister)
  6227. {
  6228. argEnv = this->GetLocalFrameDisplay();
  6229. }
  6230. if (argEnv == nullptr && this->m_functionBody->GetEnvRegister() != Constants::NoRegister)
  6231. {
  6232. argEnv = this->LdEnv();
  6233. }
  6234. if (argEnv == nullptr)
  6235. {
  6236. if (strict)
  6237. {
  6238. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplayNoParent(argHead, scriptContext);
  6239. }
  6240. else
  6241. {
  6242. frameDisplay = JavascriptOperators::OP_LdFrameDisplayNoParent(argHead, scriptContext);
  6243. }
  6244. }
  6245. else
  6246. {
  6247. if (strict)
  6248. {
  6249. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplay(argHead, argEnv, scriptContext);
  6250. }
  6251. else
  6252. {
  6253. frameDisplay = JavascriptOperators::OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6254. }
  6255. }
  6256. return frameDisplay;
  6257. }
  6258. FrameDisplay *
  6259. InterpreterStackFrame::OP_LdFuncExprFrameDisplaySetLocal(void *argHead1, void *argHead2, ScriptContext *scriptContext)
  6260. {
  6261. FrameDisplay *frameDisplay = OP_LdFrameDisplayNoParent<false>(argHead2, scriptContext);
  6262. frameDisplay = OP_LdFrameDisplay(argHead1, frameDisplay, scriptContext);
  6263. this->SetLocalFrameDisplay(frameDisplay);
  6264. return frameDisplay;
  6265. }
  6266. FrameDisplay* InterpreterStackFrame::GetLocalFrameDisplay() const
  6267. {
  6268. Assert(this->localFrameDisplay == nullptr || this->IsClosureInitDone() || this->localFrameDisplay->GetLength() == 0);
  6269. return this->localFrameDisplay;
  6270. }
  6271. void InterpreterStackFrame::SetLocalFrameDisplay(FrameDisplay* frameDisplay)
  6272. {
  6273. this->localFrameDisplay = frameDisplay;
  6274. }
  6275. Var InterpreterStackFrame::GetLocalClosure() const
  6276. {
  6277. return this->localClosure;
  6278. }
  6279. void InterpreterStackFrame::SetLocalClosure(Var closure)
  6280. {
  6281. this->localClosure = closure;
  6282. }
  6283. Var InterpreterStackFrame::GetParamClosure() const
  6284. {
  6285. return this->paramClosure;
  6286. }
  6287. void InterpreterStackFrame::SetParamClosure(Var closure)
  6288. {
  6289. this->paramClosure = closure;
  6290. }
  6291. void
  6292. InterpreterStackFrame::OP_NewInnerScopeSlots(uint innerScopeIndex, uint count, int scopeIndex, ScriptContext *scriptContext, FunctionBody *functionBody)
  6293. {
  6294. Field(Var)* slotArray =
  6295. JavascriptOperators::OP_NewScopeSlotsWithoutPropIds(count, scopeIndex, scriptContext, functionBody);
  6296. this->SetInnerScopeFromIndex(innerScopeIndex, slotArray);
  6297. }
  6298. template <typename T>
  6299. void InterpreterStackFrame::OP_CloneInnerScopeSlots(const unaligned OpLayoutT_Unsigned1<T> *playout)
  6300. {
  6301. uint innerScopeIndex = playout->C1;
  6302. Field(Var) * slotArray;
  6303. slotArray = (Field(Var)*)this->InnerScopeFromIndex(innerScopeIndex);
  6304. slotArray = JavascriptOperators::OP_CloneScopeSlots(slotArray, scriptContext);
  6305. this->SetInnerScopeFromIndex(innerScopeIndex, slotArray);
  6306. }
  6307. template <typename T>
  6308. void InterpreterStackFrame::OP_CloneBlockScope(const unaligned OpLayoutT_Unsigned1<T> *playout)
  6309. {
  6310. uint innerScopeIndex = playout->C1;
  6311. Var scope = this->InnerScopeFromIndex(innerScopeIndex);
  6312. BlockActivationObject* blockScope = BlockActivationObject::FromVar(scope);
  6313. scope = JavascriptOperators::OP_CloneBlockScope(blockScope, scriptContext);
  6314. this->SetInnerScopeFromIndex(innerScopeIndex, scope);
  6315. }
  6316. Field(Var)*
  6317. InterpreterStackFrame::NewScopeSlots(unsigned int size, ScriptContext *scriptContext, Var scope)
  6318. {
  6319. Field(Var)* slotArray = JavascriptOperators::OP_NewScopeSlots(size, scriptContext, scope);
  6320. this->SetLocalClosure(slotArray);
  6321. return slotArray;
  6322. }
  6323. Field(Var)*
  6324. InterpreterStackFrame::NewScopeSlots()
  6325. {
  6326. Field(Var)* slotArray;
  6327. FunctionBody * functionBody = this->m_functionBody;
  6328. uint scopeSlotCount = this->IsParamScopeDone() ? functionBody->scopeSlotArraySize : functionBody->paramScopeSlotArraySize;
  6329. Assert(scopeSlotCount != 0);
  6330. if (!functionBody->DoStackScopeSlots())
  6331. {
  6332. return this->NewScopeSlots(
  6333. scopeSlotCount + ScopeSlots::FirstSlotIndex, this->GetScriptContext(), (Var)functionBody->GetFunctionInfo());
  6334. }
  6335. slotArray = (Field(Var)*)this->GetLocalClosure();
  6336. Assert(slotArray != nullptr);
  6337. ScopeSlots scopeSlots(slotArray);
  6338. scopeSlots.SetCount(scopeSlotCount);
  6339. scopeSlots.SetScopeMetadata((Var)functionBody->GetFunctionInfo());
  6340. Var undef = functionBody->GetScriptContext()->GetLibrary()->GetUndefined();
  6341. for (unsigned int i = 0; i < scopeSlotCount; i++)
  6342. {
  6343. scopeSlots.Set(i, undef);
  6344. }
  6345. return slotArray;
  6346. }
  6347. Var
  6348. InterpreterStackFrame::NewScopeObject()
  6349. {
  6350. Var scopeObject;
  6351. if (m_functionBody->HasCachedScopePropIds())
  6352. {
  6353. const Js::PropertyIdArray *propIds = this->m_functionBody->GetFormalsPropIdArray();
  6354. JavascriptFunction* funcExpr = this->GetFunctionExpression();
  6355. PropertyId objectId = ActivationObjectEx::GetLiteralObjectRef(propIds);
  6356. scopeObject = JavascriptOperators::OP_InitCachedScope(funcExpr, propIds,
  6357. this->GetFunctionBody()->GetObjectLiteralTypeRef(objectId),
  6358. propIds->hasNonSimpleParams, GetScriptContext());
  6359. }
  6360. else
  6361. {
  6362. scopeObject = JavascriptOperators::OP_NewScopeObject(GetScriptContext());
  6363. }
  6364. this->SetLocalClosure(scopeObject);
  6365. return scopeObject;
  6366. }
  6367. FrameDisplay *
  6368. InterpreterStackFrame::GetFrameDisplayForNestedFunc() const
  6369. {
  6370. if (this->localFrameDisplay == nullptr)
  6371. {
  6372. return (FrameDisplay*)LdEnv();
  6373. }
  6374. return this->localFrameDisplay;
  6375. }
  6376. template <class T>
  6377. void InterpreterStackFrame::OP_NewStackScFunc(const unaligned T * playout)
  6378. {
  6379. uint funcIndex = playout->SlotIndex;
  6380. FrameDisplay *frameDisplay = this->GetFrameDisplayForNestedFunc();
  6381. SetRegAllowStackVarEnableOnly(playout->Value,
  6382. StackScriptFunction::OP_NewStackScFunc(frameDisplay,
  6383. this->m_functionBody->GetNestedFuncReference(funcIndex),
  6384. this->GetStackNestedFunction(funcIndex)));
  6385. }
  6386. template <class T>
  6387. void InterpreterStackFrame::OP_NewInnerStackScFunc(const unaligned T * playout)
  6388. {
  6389. uint funcIndex = playout->SlotIndex;
  6390. FrameDisplay *frameDisplay = (FrameDisplay*)GetNonVarReg(playout->Instance);
  6391. SetRegAllowStackVarEnableOnly(playout->Value,
  6392. StackScriptFunction::OP_NewStackScFunc(frameDisplay,
  6393. this->m_functionBody->GetNestedFuncReference(funcIndex),
  6394. this->GetStackNestedFunction(funcIndex)));
  6395. }
  6396. template <class T>
  6397. void InterpreterStackFrame::OP_DeleteFld(const unaligned T * playout)
  6398. {
  6399. Var result = JavascriptOperators::OP_DeleteProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6400. SetReg(playout->Value, result);
  6401. }
  6402. template <class T>
  6403. void InterpreterStackFrame::OP_DeleteLocalFld(const unaligned T * playout)
  6404. {
  6405. Var result = JavascriptOperators::OP_DeleteProperty(this->localClosure, m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6406. SetReg(playout->Instance, result);
  6407. }
  6408. template <class T>
  6409. void InterpreterStackFrame::OP_DeleteRootFld(const unaligned T * playout)
  6410. {
  6411. Var result = JavascriptOperators::OP_DeleteRootProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6412. SetReg(playout->Value, result);
  6413. }
  6414. template <class T>
  6415. void InterpreterStackFrame::OP_DeleteFldStrict(const unaligned T * playout)
  6416. {
  6417. Var result = JavascriptOperators::OP_DeleteProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext(), PropertyOperation_StrictMode);
  6418. SetReg(playout->Value, result);
  6419. }
  6420. template <class T>
  6421. void InterpreterStackFrame::OP_DeleteRootFldStrict(const unaligned T * playout)
  6422. {
  6423. Var result = JavascriptOperators::OP_DeleteRootProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext(), PropertyOperation_StrictMode);
  6424. SetReg(playout->Value, result);
  6425. }
  6426. template <typename T>
  6427. void InterpreterStackFrame::OP_ScopedDeleteFld(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6428. {
  6429. // Implicit root object as default instance
  6430. Var result = JavascriptOperators::OP_DeletePropertyScoped(GetEnvForEvalCode(),
  6431. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6432. GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  6433. SetReg(playout->Value, result);
  6434. }
  6435. template <typename T>
  6436. void InterpreterStackFrame::OP_ScopedDeleteFldStrict(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6437. {
  6438. // Implicit root object as default instance
  6439. Var result = JavascriptOperators::OP_DeletePropertyScoped(GetEnvForEvalCode(),
  6440. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6441. GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext(), PropertyOperation_StrictMode);
  6442. SetReg(playout->Value, result);
  6443. }
  6444. template <class T>
  6445. void InterpreterStackFrame::OP_ScopedLdInst(const unaligned T * playout)
  6446. {
  6447. Var thisVar = nullptr;
  6448. Var rootObject = GetFunctionBody()->GetRootObject();
  6449. Var result = JavascriptOperators::OP_GetInstanceScoped(GetEnvForEvalCode(),
  6450. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), rootObject, &thisVar, GetScriptContext());
  6451. SetReg(playout->Value, result);
  6452. SetReg(playout->Value2, thisVar);
  6453. }
  6454. template <typename T>
  6455. void InterpreterStackFrame::OP_ScopedInitFunc(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6456. {
  6457. JavascriptOperators::OP_InitFuncScoped(GetEnvForEvalCode(),
  6458. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6459. GetReg(playout->Value), GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  6460. }
  6461. template <class T>
  6462. void InterpreterStackFrame::OP_ClearAttributes(const unaligned T * playout)
  6463. {
  6464. JavascriptOperators::OP_ClearAttributes(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  6465. }
  6466. template <class T>
  6467. void InterpreterStackFrame::OP_InitGetFld(const unaligned T * playout)
  6468. {
  6469. JavascriptOperators::OP_InitGetter(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6470. }
  6471. template <class T>
  6472. void InterpreterStackFrame::OP_InitSetFld(const unaligned T * playout)
  6473. {
  6474. JavascriptOperators::OP_InitSetter(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6475. }
  6476. template <class T>
  6477. void InterpreterStackFrame::OP_InitSetElemI(const unaligned T * playout)
  6478. {
  6479. JavascriptOperators::OP_InitElemSetter(
  6480. GetReg(playout->Instance),
  6481. GetReg(playout->Element),
  6482. GetReg(playout->Value),
  6483. m_functionBody->GetScriptContext()
  6484. );
  6485. }
  6486. template <class T>
  6487. void InterpreterStackFrame::OP_InitGetElemI(const unaligned T * playout)
  6488. {
  6489. JavascriptOperators::OP_InitElemGetter(
  6490. GetReg(playout->Instance),
  6491. GetReg(playout->Element),
  6492. GetReg(playout->Value),
  6493. m_functionBody->GetScriptContext()
  6494. );
  6495. }
  6496. template <class T>
  6497. void InterpreterStackFrame::OP_InitComputedProperty(const unaligned T * playout)
  6498. {
  6499. JavascriptOperators::OP_InitComputedProperty(
  6500. GetReg(playout->Instance),
  6501. GetReg(playout->Element),
  6502. GetReg(playout->Value),
  6503. m_functionBody->GetScriptContext()
  6504. );
  6505. }
  6506. template <class T>
  6507. void InterpreterStackFrame::OP_InitProto(const unaligned T * playout)
  6508. {
  6509. JavascriptOperators::OP_InitProto(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6510. }
  6511. void InterpreterStackFrame::DoInterruptProbe()
  6512. {
  6513. PROBE_STACK(scriptContext, 0);
  6514. }
  6515. void InterpreterStackFrame::InitializeStackFunctions(StackScriptFunction * scriptFunctions)
  6516. {
  6517. this->stackNestedFunctions = scriptFunctions;
  6518. FunctionBody * functionBody = this->m_functionBody;
  6519. uint nestedCount = functionBody->GetNestedCount();
  6520. for (uint i = 0; i < nestedCount; i++)
  6521. {
  6522. StackScriptFunction * stackScriptFunction = scriptFunctions + i;
  6523. FunctionProxy* nestedProxy = functionBody->GetNestedFunctionProxy(i);
  6524. ScriptFunctionType* type = nestedProxy->EnsureDeferredPrototypeType();
  6525. new (stackScriptFunction)StackScriptFunction(nestedProxy, type);
  6526. }
  6527. }
  6528. StackScriptFunction * InterpreterStackFrame::GetStackNestedFunction(uint index)
  6529. {
  6530. Assert(index < this->m_functionBody->GetNestedCount());
  6531. // Re-check if we have disable stack nested function
  6532. if (this->m_functionBody->DoStackNestedFunc())
  6533. {
  6534. return this->stackNestedFunctions + index;
  6535. }
  6536. return nullptr;
  6537. }
  6538. void InterpreterStackFrame::SetExecutingStackFunction(ScriptFunction * scriptFunction)
  6539. {
  6540. Assert(ThreadContext::IsOnStack(this->function));
  6541. Assert(this->m_functionBody == scriptFunction->GetFunctionBody());
  6542. this->function = scriptFunction;
  6543. }
  6544. DWORD_PTR InterpreterStackFrame::GetStackAddress() const
  6545. {
  6546. return m_stackAddress;
  6547. }
  6548. void* InterpreterStackFrame::GetAddressOfReturnAddress() const
  6549. {
  6550. return this->addressOfReturnAddress;
  6551. }
  6552. template <class T>
  6553. const byte * InterpreterStackFrame::OP_Br(const unaligned T * playout)
  6554. {
  6555. return m_reader.SetCurrentRelativeOffset((const byte *)(playout + 1), playout->RelativeJumpOffset);
  6556. }
  6557. template <class T>
  6558. void InterpreterStackFrame::OP_InitClass(const unaligned OpLayoutT_Class<T> * playout)
  6559. {
  6560. JavascriptOperators::OP_InitClass(GetReg(playout->Constructor), playout->Extends != Js::Constants::NoRegister ? GetReg(playout->Extends) : NULL, GetScriptContext());
  6561. }
  6562. #ifdef ENABLE_SCRIPT_DEBUGGING
  6563. template <class T>
  6564. void InterpreterStackFrame::OP_EmitTmpRegCount(const unaligned OpLayoutT_Unsigned1<T> * playout)
  6565. {
  6566. this->scriptContext->GetDebugContext()->GetProbeContainer()->SetCurrentTmpRegCount(playout->C1);
  6567. }
  6568. #endif
  6569. Var InterpreterStackFrame::OP_LdHomeObj(ScriptContext * scriptContext)
  6570. {
  6571. return JavascriptOperators::OP_LdHomeObj(function, scriptContext);
  6572. }
  6573. Var InterpreterStackFrame::OP_LdFuncObj(ScriptContext * scriptContext)
  6574. {
  6575. return JavascriptOperators::OP_LdFuncObj(function, scriptContext);
  6576. }
  6577. Var InterpreterStackFrame::OP_ImportCall(Var specifier, ScriptContext *scriptContext)
  6578. {
  6579. return JavascriptOperators::OP_ImportCall(function, specifier, scriptContext);
  6580. }
  6581. void InterpreterStackFrame::ValidateRegValue(Var value, bool allowStackVar, bool allowStackVarOnDisabledStackNestedFunc) const
  6582. {
  6583. #if DBG
  6584. if (value != nullptr && !TaggedNumber::Is(value))
  6585. {
  6586. if (!allowStackVar || !this->m_functionBody->DoStackNestedFunc())
  6587. {
  6588. Assert(!ThreadContext::IsOnStack(value)
  6589. || (allowStackVar && allowStackVarOnDisabledStackNestedFunc && StackScriptFunction::IsBoxed(value)));
  6590. }
  6591. Assert(!CrossSite::NeedMarshalVar(value, GetScriptContext()));
  6592. }
  6593. #endif
  6594. }
  6595. template <typename RegSlotType>
  6596. Var InterpreterStackFrame::GetReg(RegSlotType localRegisterID) const
  6597. {
  6598. Var value = m_localSlots[localRegisterID];
  6599. ValidateRegValue(value);
  6600. return value;
  6601. }
  6602. template <typename RegSlotType>
  6603. void InterpreterStackFrame::SetReg(RegSlotType localRegisterID, Var value)
  6604. {
  6605. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6606. ValidateRegValue(value);
  6607. m_localSlots[localRegisterID] = value;
  6608. #if ENABLE_OBJECT_SOURCE_TRACKING
  6609. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6610. {
  6611. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6612. }
  6613. #endif
  6614. #if ENABLE_VALUE_TRACE
  6615. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6616. {
  6617. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6618. }
  6619. #endif
  6620. }
  6621. template <typename T>
  6622. T InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6623. {
  6624. return (T)m_localIntSlots[localRegisterID];
  6625. }
  6626. // specialized version for doubles
  6627. template <>
  6628. double VECTORCALL InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6629. {
  6630. return (double)m_localDoubleSlots[localRegisterID];
  6631. }
  6632. template <>
  6633. float VECTORCALL InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6634. {
  6635. return (float)m_localFloatSlots[localRegisterID];
  6636. }
  6637. template <>
  6638. int64 InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6639. {
  6640. return m_localInt64Slots[localRegisterID];
  6641. }
  6642. template <typename T>
  6643. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, T bValue)
  6644. {
  6645. m_localIntSlots[localRegisterID] = (int)bValue;
  6646. }
  6647. template <>
  6648. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, float bValue)
  6649. {
  6650. m_localFloatSlots[localRegisterID] = (float)bValue;
  6651. }
  6652. template <>
  6653. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, double bValue)
  6654. {
  6655. m_localDoubleSlots[localRegisterID] = bValue;
  6656. }
  6657. template <>
  6658. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, int64 bValue)
  6659. {
  6660. m_localInt64Slots[localRegisterID] = bValue;
  6661. }
  6662. template <typename RegSlotType>
  6663. int InterpreterStackFrame::GetRegRawInt(RegSlotType localRegisterID) const
  6664. {
  6665. return m_localIntSlots[localRegisterID];
  6666. }
  6667. template <typename RegSlotType>
  6668. double InterpreterStackFrame::GetRegRawDouble(RegSlotType localRegisterID) const
  6669. {
  6670. return m_localDoubleSlots[localRegisterID];
  6671. }
  6672. template <typename RegSlotType>
  6673. float InterpreterStackFrame::GetRegRawFloat(RegSlotType localRegisterID) const
  6674. {
  6675. return m_localFloatSlots[localRegisterID];
  6676. }
  6677. template <typename RegSlotType>
  6678. void InterpreterStackFrame::SetRegRawInt(RegSlotType localRegisterID, int bValue)
  6679. {
  6680. m_localIntSlots[localRegisterID] = bValue;
  6681. }
  6682. template <typename RegSlotType>
  6683. int64 InterpreterStackFrame::GetRegRawInt64(RegSlotType localRegisterID) const
  6684. {
  6685. return m_localInt64Slots[localRegisterID];
  6686. }
  6687. template <typename RegSlotType>
  6688. void* InterpreterStackFrame::GetRegRawPtr(RegSlotType localRegisterID) const
  6689. {
  6690. #if TARGET_32
  6691. return (void*)m_localIntSlots[localRegisterID];
  6692. #elif TARGET_64
  6693. return (void*)m_localInt64Slots[localRegisterID];
  6694. #endif
  6695. }
  6696. template <typename RegSlotType>
  6697. void InterpreterStackFrame::SetRegRawPtr(RegSlotType localRegisterID, void* val)
  6698. {
  6699. #if TARGET_32
  6700. m_localIntSlots[localRegisterID] = (int32)val;
  6701. #elif TARGET_64
  6702. m_localInt64Slots[localRegisterID] = (int64)val;
  6703. #endif
  6704. }
  6705. template <typename RegSlotType>
  6706. void InterpreterStackFrame::SetRegRawInt64(RegSlotType localRegisterID, int64 bValue)
  6707. {
  6708. m_localInt64Slots[localRegisterID] = bValue;
  6709. }
  6710. template <typename RegSlotType>
  6711. void InterpreterStackFrame::SetRegRawDouble(RegSlotType localRegisterID, double bValue)
  6712. {
  6713. m_localDoubleSlots[localRegisterID] = bValue;
  6714. }
  6715. template <typename RegSlotType>
  6716. void InterpreterStackFrame::SetRegRawFloat(RegSlotType localRegisterID, float bValue)
  6717. {
  6718. m_localFloatSlots[localRegisterID] = bValue;
  6719. }
  6720. template <typename RegSlotType>
  6721. Var InterpreterStackFrame::GetRegAllowStackVar(RegSlotType localRegisterID) const
  6722. {
  6723. Var value = m_localSlots[localRegisterID];
  6724. ValidateRegValue(value, true);
  6725. return value;
  6726. }
  6727. template <typename RegSlotType>
  6728. void InterpreterStackFrame::SetRegAllowStackVar(RegSlotType localRegisterID, Var value)
  6729. {
  6730. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6731. ValidateRegValue(value, true);
  6732. m_localSlots[localRegisterID] = value;
  6733. #if ENABLE_OBJECT_SOURCE_TRACKING
  6734. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6735. {
  6736. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6737. }
  6738. #endif
  6739. #if ENABLE_VALUE_TRACE
  6740. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6741. {
  6742. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6743. }
  6744. #endif
  6745. }
  6746. template <typename RegSlotType>
  6747. Var InterpreterStackFrame::GetRegAllowStackVarEnableOnly(RegSlotType localRegisterID) const
  6748. {
  6749. Var value = m_localSlots[localRegisterID];
  6750. ValidateRegValue(value, true, false);
  6751. return value;
  6752. }
  6753. template <typename RegSlotType>
  6754. void InterpreterStackFrame::SetRegAllowStackVarEnableOnly(RegSlotType localRegisterID, Var value)
  6755. {
  6756. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6757. ValidateRegValue(value, true, false);
  6758. m_localSlots[localRegisterID] = value;
  6759. #if ENABLE_OBJECT_SOURCE_TRACKING
  6760. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6761. {
  6762. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6763. }
  6764. #endif
  6765. #if ENABLE_VALUE_TRACE
  6766. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6767. {
  6768. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6769. }
  6770. #endif
  6771. }
  6772. template <>
  6773. AsmJsSIMDValue InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6774. {
  6775. return (AsmJsSIMDValue)m_localSimdSlots[localRegisterID];
  6776. }
  6777. template<>
  6778. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, AsmJsSIMDValue bValue)
  6779. {
  6780. m_localSimdSlots[localRegisterID] = bValue;
  6781. }
  6782. template <typename RegSlotType>
  6783. AsmJsSIMDValue InterpreterStackFrame::GetRegRawSimd(RegSlotType localRegisterID) const
  6784. {
  6785. return m_localSimdSlots[localRegisterID];
  6786. }
  6787. template <typename RegSlotType>
  6788. void InterpreterStackFrame::SetRegRawSimd(RegSlotType localRegisterID, AsmJsSIMDValue bValue)
  6789. {
  6790. m_localSimdSlots[localRegisterID] = bValue;
  6791. }
  6792. int InterpreterStackFrame::OP_GetMemorySize()
  6793. {
  6794. #ifdef ENABLE_WASM
  6795. return (int)GetWebAssemblyMemory()->GetCurrentMemoryPages();
  6796. #else
  6797. Assert(UNREACHED);
  6798. return 0;
  6799. #endif
  6800. }
  6801. int InterpreterStackFrame::OP_GrowMemory(int32 delta)
  6802. {
  6803. #ifdef ENABLE_WASM
  6804. return GetWebAssemblyMemory()->GrowInternal((uint32)delta);
  6805. #else
  6806. Assert(UNREACHED);
  6807. return 0;
  6808. #endif
  6809. }
  6810. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_UnsignedDivRemCheck(T aLeft, T aRight, ScriptContext* scriptContext)
  6811. {
  6812. if (aRight == 0)
  6813. {
  6814. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6815. }
  6816. return func(aLeft, aRight);
  6817. }
  6818. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_DivOverflow(T aLeft, T aRight, ScriptContext* scriptContext)
  6819. {
  6820. if (aRight == 0)
  6821. {
  6822. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6823. }
  6824. if (aLeft == SignedTypeTraits<T>::MinValue && aRight == -1)
  6825. {
  6826. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, VBSERR_Overflow);
  6827. }
  6828. return func(aLeft, aRight);
  6829. }
  6830. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_RemOverflow(T aLeft, T aRight, ScriptContext* scriptContext)
  6831. {
  6832. if (aRight == 0)
  6833. {
  6834. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6835. }
  6836. if (aLeft == SignedTypeTraits<T>::MinValue && aRight == -1)
  6837. {
  6838. return 0;
  6839. }
  6840. return func(aLeft, aRight);
  6841. }
  6842. void InterpreterStackFrame::OP_Unreachable()
  6843. {
  6844. JavascriptError::ThrowUnreachable(scriptContext);
  6845. }
  6846. template <class T>
  6847. void InterpreterStackFrame::OP_SimdLdArrGeneric(const unaligned T* playout)
  6848. {
  6849. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6850. const uint64 index = ((uint64)(uint32)GetRegRawInt(playout->SlotIndex) + playout->Offset /* WASM only */) & (int64)(int)ArrayBufferView::ViewMask[playout->ViewType];
  6851. ArrayBufferBase* arr =
  6852. #ifdef ENABLE_WASM_SIMD
  6853. (m_functionBody->IsWasmFunction()) ?
  6854. m_wasmMemory->GetBuffer() :
  6855. #endif
  6856. GetAsmJsBuffer();
  6857. BYTE* buffer = arr->GetBuffer();
  6858. uint8 dataWidth = playout->DataWidth;
  6859. RegSlot dstReg = playout->Value;
  6860. if (index + dataWidth > arr->GetByteLength())
  6861. {
  6862. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6863. }
  6864. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6865. AsmJsSIMDValue value;
  6866. value = SIMDUtils::SIMDLdData(data, dataWidth);
  6867. SetRegRawSimd(dstReg, value);
  6868. }
  6869. template <class T>
  6870. void InterpreterStackFrame::OP_SimdLdArrConstIndex(const unaligned T* playout)
  6871. {
  6872. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6873. const uint64 index = (uint32)playout->SlotIndex;
  6874. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  6875. BYTE* buffer = arr->GetBuffer();
  6876. uint8 dataWidth = playout->DataWidth;
  6877. RegSlot dstReg = playout->Value;
  6878. if (index + dataWidth > arr->GetByteLength())
  6879. {
  6880. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6881. }
  6882. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6883. AsmJsSIMDValue value;
  6884. value = SIMDUtils::SIMDLdData(data, dataWidth);
  6885. SetRegRawSimd(dstReg, value);
  6886. }
  6887. template <class T>
  6888. void InterpreterStackFrame::OP_SimdStArrGeneric(const unaligned T* playout)
  6889. {
  6890. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6891. const uint64 index = ((uint64)(uint32)GetRegRawInt(playout->SlotIndex) + playout->Offset /* WASM only */) & (int64)(int)ArrayBufferView::ViewMask[playout->ViewType];
  6892. ArrayBufferBase* arr =
  6893. #ifdef ENABLE_WASM_SIMD
  6894. (m_functionBody->IsWasmFunction()) ?
  6895. m_wasmMemory->GetBuffer() :
  6896. #endif
  6897. GetAsmJsBuffer();
  6898. BYTE* buffer = arr->GetBuffer();
  6899. uint8 dataWidth = playout->DataWidth;
  6900. RegSlot srcReg = playout->Value;
  6901. if (index + dataWidth > arr->GetByteLength())
  6902. {
  6903. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6904. }
  6905. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6906. AsmJsSIMDValue value = GetRegRawSimd(srcReg);
  6907. SIMDUtils::SIMDStData(data, value, dataWidth);
  6908. }
  6909. template <class T>
  6910. void InterpreterStackFrame::OP_SimdStArrConstIndex(const unaligned T* playout)
  6911. {
  6912. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6913. const uint64 index = (uint32)playout->SlotIndex;
  6914. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  6915. BYTE* buffer = arr->GetBuffer();
  6916. uint8 dataWidth = playout->DataWidth;
  6917. RegSlot srcReg = playout->Value;
  6918. if (index + dataWidth > arr->GetByteLength())
  6919. {
  6920. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6921. }
  6922. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6923. AsmJsSIMDValue value = GetRegRawSimd(srcReg);
  6924. SIMDUtils::SIMDStData(data, value, dataWidth);
  6925. }
  6926. bool InterpreterStackFrame::SIMDAnyNaN(AsmJsSIMDValue& input)
  6927. {
  6928. if (!GetFunctionBody()->IsWasmFunction())
  6929. {
  6930. return false;
  6931. }
  6932. AsmJsSIMDValue compResult = SIMDFloat32x4Operation::OpEqual(input, input);
  6933. return !SIMDBool32x4Operation::OpAllTrue(compResult);
  6934. }
  6935. // handler for SIMD.Int32x4.FromFloat32x4
  6936. template <class T>
  6937. void InterpreterStackFrame::OP_SimdInt32x4FromFloat32x4(const unaligned T* playout)
  6938. {
  6939. bool throws = false;
  6940. AsmJsSIMDValue input = GetRegRawSimd(playout->F4_1);
  6941. AsmJsSIMDValue result{ 0 };
  6942. #ifdef ENABLE_WASM_SIMD
  6943. throws = SIMDAnyNaN(input);
  6944. if (!throws)
  6945. #endif
  6946. {
  6947. result = SIMDInt32x4Operation::OpFromFloat32x4(input, throws);
  6948. }
  6949. // value is out of bound
  6950. if (throws)
  6951. {
  6952. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("SIMD.Int32x4.FromFloat32x4"));
  6953. }
  6954. SetRegRawSimd(playout->I4_0, result);
  6955. }
  6956. // handler for SIMD.Uint32x4.FromFloat32x4
  6957. template <class T>
  6958. void InterpreterStackFrame::OP_SimdUint32x4FromFloat32x4(const unaligned T* playout)
  6959. {
  6960. bool throws = false;
  6961. AsmJsSIMDValue input = GetRegRawSimd(playout->F4_1);
  6962. AsmJsSIMDValue result{ 0 };
  6963. #ifdef ENABLE_WASM_SIMD
  6964. throws = SIMDAnyNaN(input);
  6965. if (!throws)
  6966. #endif
  6967. {
  6968. result = SIMDUint32x4Operation::OpFromFloat32x4(input, throws);
  6969. }
  6970. if (throws)
  6971. {
  6972. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("SIMD.Int32x4.FromFloat32x4"));
  6973. }
  6974. SetRegRawSimd(playout->U4_0, result);
  6975. }
  6976. template <class T>
  6977. void InterpreterStackFrame::OP_WasmSimdConst(const unaligned T* playout)
  6978. {
  6979. AsmJsSIMDValue result{ playout->C1, playout->C2, playout->C3, playout->C4 };
  6980. SetRegRawSimd(playout->F4_0, result);
  6981. }
  6982. template <class T>
  6983. void InterpreterStackFrame::OP_SimdShuffleV8X16(const unaligned T* playout)
  6984. {
  6985. uint32 lanes[Wasm::Simd::MAX_LANES];
  6986. for (uint32 i = 0; i < Wasm::Simd::MAX_LANES; i++)
  6987. {
  6988. Assert(playout->INDICES[i] < Wasm::Simd::MAX_LANES * 2);
  6989. lanes[i] = playout->INDICES[i];
  6990. }
  6991. SetRegRawSimd(playout->R0, SIMDUtils::SIMD128InnerShuffle(GetRegRawSimd(playout->R1), GetRegRawSimd(playout->R2), Wasm::Simd::MAX_LANES, lanes));
  6992. }
  6993. template <class T>
  6994. void InterpreterStackFrame::OP_SimdInt16x8(const unaligned T* playout)
  6995. {
  6996. int16 values[8];
  6997. values[0] = (int16) GetRegRawInt(playout->I1);
  6998. values[1] = (int16) GetRegRawInt(playout->I2);
  6999. values[2] = (int16) GetRegRawInt(playout->I3);
  7000. values[3] = (int16) GetRegRawInt(playout->I4);
  7001. values[4] = (int16) GetRegRawInt(playout->I5);
  7002. values[5] = (int16) GetRegRawInt(playout->I6);
  7003. values[6] = (int16) GetRegRawInt(playout->I7);
  7004. values[7] = (int16) GetRegRawInt(playout->I8);
  7005. AsmJsSIMDValue result = SIMDInt16x8Operation::OpInt16x8(values);
  7006. SetRegRawSimd(playout->I8_0, result);
  7007. }
  7008. template <class T>
  7009. void InterpreterStackFrame::OP_SimdInt8x16(const unaligned T* playout)
  7010. {
  7011. int8 values[16];
  7012. values[0] = (int8)GetRegRawInt(playout->I1);
  7013. values[1] = (int8)GetRegRawInt(playout->I2);
  7014. values[2] = (int8)GetRegRawInt(playout->I3);
  7015. values[3] = (int8)GetRegRawInt(playout->I4);
  7016. values[4] = (int8)GetRegRawInt(playout->I5);
  7017. values[5] = (int8)GetRegRawInt(playout->I6);
  7018. values[6] = (int8)GetRegRawInt(playout->I7);
  7019. values[7] = (int8)GetRegRawInt(playout->I8);
  7020. values[8] = (int8)GetRegRawInt(playout->I9);
  7021. values[9] = (int8)GetRegRawInt(playout->I10);
  7022. values[10] = (int8)GetRegRawInt(playout->I11);
  7023. values[11] = (int8)GetRegRawInt(playout->I12);
  7024. values[12] = (int8)GetRegRawInt(playout->I13);
  7025. values[13] = (int8)GetRegRawInt(playout->I14);
  7026. values[14] = (int8)GetRegRawInt(playout->I15);
  7027. values[15] = (int8)GetRegRawInt(playout->I16);
  7028. AsmJsSIMDValue result = SIMDInt8x16Operation::OpInt8x16(values);
  7029. SetRegRawSimd(playout->I16_0, result);
  7030. }
  7031. template <class T>
  7032. void InterpreterStackFrame::OP_SimdUint16x8(const unaligned T* playout)
  7033. {
  7034. uint16 values[8];
  7035. values[0] = (uint16) GetRegRawInt(playout->I1);
  7036. values[1] = (uint16) GetRegRawInt(playout->I2);
  7037. values[2] = (uint16) GetRegRawInt(playout->I3);
  7038. values[3] = (uint16) GetRegRawInt(playout->I4);
  7039. values[4] = (uint16) GetRegRawInt(playout->I5);
  7040. values[5] = (uint16) GetRegRawInt(playout->I6);
  7041. values[6] = (uint16) GetRegRawInt(playout->I7);
  7042. values[7] = (uint16) GetRegRawInt(playout->I8);
  7043. AsmJsSIMDValue result = SIMDUint16x8Operation::OpUint16x8(values);
  7044. SetRegRawSimd(playout->U8_0, result);
  7045. }
  7046. template <class T>
  7047. void InterpreterStackFrame::OP_SimdUint8x16(const unaligned T* playout)
  7048. {
  7049. uint8 values[16];
  7050. values[0] = (uint8) GetRegRawInt(playout->I1);
  7051. values[1] = (uint8) GetRegRawInt(playout->I2);
  7052. values[2] = (uint8) GetRegRawInt(playout->I3);
  7053. values[3] = (uint8) GetRegRawInt(playout->I4);
  7054. values[4] = (uint8) GetRegRawInt(playout->I5);
  7055. values[5] = (uint8) GetRegRawInt(playout->I6);
  7056. values[6] = (uint8) GetRegRawInt(playout->I7);
  7057. values[7] = (uint8) GetRegRawInt(playout->I8);
  7058. values[8] = (uint8) GetRegRawInt(playout->I9);
  7059. values[9] = (uint8) GetRegRawInt(playout->I10);
  7060. values[10] = (uint8) GetRegRawInt(playout->I11);
  7061. values[11] = (uint8) GetRegRawInt(playout->I12);
  7062. values[12] = (uint8) GetRegRawInt(playout->I13);
  7063. values[13] = (uint8) GetRegRawInt(playout->I14);
  7064. values[14] = (uint8) GetRegRawInt(playout->I15);
  7065. values[15] = (uint8) GetRegRawInt(playout->I16);
  7066. AsmJsSIMDValue result = SIMDUint8x16Operation::OpUint8x16(values);
  7067. SetRegRawSimd(playout->U16_0, result);
  7068. }
  7069. // Bool constructors
  7070. template <class T>
  7071. void InterpreterStackFrame::OP_SimdBool32x4(const unaligned T* playout)
  7072. {
  7073. bool arg1 = GetRegRawInt(playout->I1) ? true : false;
  7074. bool arg2 = GetRegRawInt(playout->I2) ? true : false;
  7075. bool arg3 = GetRegRawInt(playout->I3) ? true : false;
  7076. bool arg4 = GetRegRawInt(playout->I4) ? true : false;
  7077. AsmJsSIMDValue result = SIMDBool32x4Operation::OpBool32x4(arg1, arg2, arg3, arg4);
  7078. SetRegRawSimd(playout->B4_0, result);
  7079. }
  7080. template <class T>
  7081. void InterpreterStackFrame::OP_SimdBool16x8(const unaligned T* playout)
  7082. {
  7083. bool values[8];
  7084. values[0] = GetRegRawInt(playout->I1) ? true : false;
  7085. values[1] = GetRegRawInt(playout->I2) ? true : false;
  7086. values[2] = GetRegRawInt(playout->I3) ? true : false;
  7087. values[3] = GetRegRawInt(playout->I4) ? true : false;
  7088. values[4] = GetRegRawInt(playout->I5) ? true : false;
  7089. values[5] = GetRegRawInt(playout->I6) ? true : false;
  7090. values[6] = GetRegRawInt(playout->I7) ? true : false;
  7091. values[7] = GetRegRawInt(playout->I8) ? true : false;
  7092. AsmJsSIMDValue result = SIMDBool16x8Operation::OpBool16x8(values);
  7093. SetRegRawSimd(playout->B8_0, result);
  7094. }
  7095. template <class T>
  7096. void InterpreterStackFrame::OP_SimdBool8x16(const unaligned T* playout)
  7097. {
  7098. bool values[16];
  7099. values[0] = GetRegRawInt(playout->I1) ? true : false;
  7100. values[1] = GetRegRawInt(playout->I2) ? true : false;
  7101. values[2] = GetRegRawInt(playout->I3) ? true : false;
  7102. values[3] = GetRegRawInt(playout->I4) ? true : false;
  7103. values[4] = GetRegRawInt(playout->I5) ? true : false;
  7104. values[5] = GetRegRawInt(playout->I6) ? true : false;
  7105. values[6] = GetRegRawInt(playout->I7) ? true : false;
  7106. values[7] = GetRegRawInt(playout->I8) ? true : false;
  7107. values[8] = GetRegRawInt(playout->I9) ? true : false;
  7108. values[9] = GetRegRawInt(playout->I10) ? true : false;
  7109. values[10] = GetRegRawInt(playout->I11) ? true : false;
  7110. values[11] = GetRegRawInt(playout->I12) ? true : false;
  7111. values[12] = GetRegRawInt(playout->I13) ? true : false;
  7112. values[13] = GetRegRawInt(playout->I14) ? true : false;
  7113. values[14] = GetRegRawInt(playout->I15) ? true : false;
  7114. values[15] = GetRegRawInt(playout->I16) ? true : false;
  7115. AsmJsSIMDValue result = SIMDBool8x16Operation::OpBool8x16(values);
  7116. SetRegRawSimd(playout->B16_0, result);
  7117. }
  7118. Var InterpreterStackFrame::GetNonVarReg(RegSlot localRegisterID) const
  7119. {
  7120. return m_localSlots[localRegisterID];
  7121. }
  7122. void InterpreterStackFrame::SetNonVarReg(RegSlot localRegisterID, Var aValue)
  7123. {
  7124. m_localSlots[localRegisterID] = aValue;
  7125. }
  7126. Var InterpreterStackFrame::GetRootObject() const
  7127. {
  7128. Assert(!this->GetFunctionBody()->IsJsBuiltInInitCode());
  7129. Var rootObject = GetReg(Js::FunctionBody::RootObjectRegSlot);
  7130. Assert(rootObject == this->GetFunctionBody()->LoadRootObject());
  7131. return rootObject;
  7132. }
  7133. Var InterpreterStackFrame::OP_ArgIn0()
  7134. {
  7135. return m_inParams[0];
  7136. }
  7137. #if ENABLE_PROFILE_INFO
  7138. template <class T>
  7139. void InterpreterStackFrame::OP_ProfiledArgOut_A(const unaligned T * playout)
  7140. {
  7141. FunctionBody* functionBody = this->m_functionBody;
  7142. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  7143. Assert(playout->Reg > FunctionBody::FirstRegSlot && playout->Reg < functionBody->GetConstantCount());
  7144. Var value = GetReg(playout->Reg);
  7145. if (value != nullptr && TaggedInt::Is(value))
  7146. {
  7147. dynamicProfileInfo->RecordConstParameterAtCallSite(playout->profileId, playout->Arg);
  7148. }
  7149. SetOut(playout->Arg, GetReg(playout->Reg));
  7150. }
  7151. #endif
  7152. template <class T>
  7153. void InterpreterStackFrame::OP_ArgOut_A(const unaligned T * playout)
  7154. {
  7155. SetOut(playout->Arg, GetReg(playout->Reg));
  7156. }
  7157. #if DBG
  7158. template <class T>
  7159. void InterpreterStackFrame::OP_ArgOut_ANonVar(const unaligned T * playout)
  7160. {
  7161. SetOut(playout->Arg, GetNonVarReg(playout->Reg));
  7162. }
  7163. #endif
  7164. template <class T>
  7165. void InterpreterStackFrame::OP_ArgOut_Env(const unaligned T * playout)
  7166. {
  7167. Var argEnv;
  7168. if (this->m_functionBody->GetLocalFrameDisplayRegister() != Constants::NoRegister)
  7169. {
  7170. argEnv = this->GetLocalFrameDisplay();
  7171. }
  7172. else
  7173. {
  7174. argEnv = this->LdEnv();
  7175. }
  7176. SetOut(playout->Arg, argEnv);
  7177. }
  7178. BOOL InterpreterStackFrame::OP_BrFalse_A(Var aValue, ScriptContext* scriptContext)
  7179. {
  7180. return !JavascriptConversion::ToBoolean(aValue, scriptContext);
  7181. }
  7182. BOOL InterpreterStackFrame::OP_BrTrue_A(Var aValue, ScriptContext* scriptContext)
  7183. {
  7184. return JavascriptConversion::ToBoolean(aValue, scriptContext);
  7185. }
  7186. BOOL InterpreterStackFrame::OP_BrNotNull_A(Var aValue)
  7187. {
  7188. return aValue != NULL;
  7189. }
  7190. BOOL InterpreterStackFrame::OP_BrUndecl_A(Var aValue)
  7191. {
  7192. return this->scriptContext->GetLibrary()->IsUndeclBlockVar(aValue);
  7193. }
  7194. BOOL InterpreterStackFrame::OP_BrNotUndecl_A(Var aValue)
  7195. {
  7196. return !this->scriptContext->GetLibrary()->IsUndeclBlockVar(aValue);
  7197. }
  7198. BOOL InterpreterStackFrame::OP_BrOnHasProperty(Var argInstance, uint propertyIdIndex, ScriptContext* scriptContext)
  7199. {
  7200. return JavascriptOperators::OP_HasProperty(argInstance,
  7201. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7202. }
  7203. BOOL InterpreterStackFrame::OP_BrOnNoProperty(Var argInstance, uint propertyIdIndex, ScriptContext* scriptContext)
  7204. {
  7205. return !JavascriptOperators::OP_HasProperty(argInstance,
  7206. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7207. }
  7208. BOOL InterpreterStackFrame::OP_BrOnNoEnvProperty(Var envInstance, int32 slotIndex, uint propertyIdIndex, ScriptContext* scriptContext)
  7209. {
  7210. Var instance = OP_LdFrameDisplaySlot(envInstance, slotIndex);
  7211. return !JavascriptOperators::OP_HasProperty(instance,
  7212. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7213. }
  7214. BOOL InterpreterStackFrame::OP_BrOnClassConstructor(Var aValue)
  7215. {
  7216. return JavascriptOperators::IsClassConstructor(aValue);
  7217. }
  7218. BOOL InterpreterStackFrame::OP_BrOnBaseConstructorKind(Var aValue)
  7219. {
  7220. return JavascriptOperators::IsBaseConstructorKind(aValue);
  7221. }
  7222. template<class T>
  7223. void InterpreterStackFrame::OP_LdLen(const unaligned T * const playout)
  7224. {
  7225. Assert(playout);
  7226. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  7227. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  7228. threadContext->ClearImplicitCallFlags();
  7229. Var instance = GetReg(playout->Instance);
  7230. Var length = JavascriptOperators::OP_GetLength(instance, GetScriptContext());
  7231. threadContext->CheckAndResetImplicitCallAccessorFlag();
  7232. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  7233. SetReg(playout->Value, length);
  7234. }
  7235. #if ENABLE_PROFILE_INFO
  7236. template<class T>
  7237. void InterpreterStackFrame::OP_ProfiledLdLen(const unaligned OpLayoutDynamicProfile<T> *const playout)
  7238. {
  7239. Assert(playout);
  7240. FunctionBody * functionBody = m_functionBody;
  7241. DynamicProfileInfo * profileData = functionBody->GetDynamicProfileInfo();
  7242. Var instance = GetReg(playout->Instance);
  7243. LdLenInfo ldLenInfo;
  7244. ldLenInfo.arrayType = ValueType::Uninitialized.Merge(instance);
  7245. profileData->RecordLengthLoad(functionBody, playout->profileId, ldLenInfo);
  7246. if (this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization))
  7247. {
  7248. ldLenInfo.disableAggressiveSpecialization = true;
  7249. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  7250. }
  7251. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  7252. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  7253. threadContext->ClearImplicitCallFlags();
  7254. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  7255. Var value = ProfilingHelpers::ProfiledLdFld<false, false, false>(
  7256. instance,
  7257. propertyId,
  7258. GetInlineCache(playout->inlineCacheIndex),
  7259. playout->inlineCacheIndex,
  7260. GetFunctionBody(),
  7261. instance);
  7262. SetReg(playout->Value, value);
  7263. threadContext->CheckAndResetImplicitCallAccessorFlag();
  7264. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  7265. }
  7266. #endif
  7267. JavascriptFunction* InterpreterStackFrame::GetFunctionExpression()
  7268. {
  7269. // Make sure we get the boxed function object if is there, (or the function itself)
  7270. return StackScriptFunction::GetCurrentFunctionObject(this->function->GetRealFunctionObject());
  7271. }
  7272. template <class T>
  7273. void InterpreterStackFrame::OP_LdFunctionExpression(const unaligned T * playout)
  7274. {
  7275. SetRegAllowStackVar(playout->R0, this->GetFunctionExpression());
  7276. }
  7277. template <class T>
  7278. void InterpreterStackFrame::OP_StFunctionExpression(const unaligned T * playout)
  7279. {
  7280. OP_StFunctionExpression(GetReg(playout->Instance), GetReg(playout->Value), playout->PropertyIdIndex);
  7281. }
  7282. template <class T>
  7283. void InterpreterStackFrame::OP_StLocalFunctionExpression(const unaligned T * playout)
  7284. {
  7285. OP_StFunctionExpression(this->localClosure, GetReg(playout->Instance), playout->PropertyIdIndex);
  7286. }
  7287. void InterpreterStackFrame::OP_StFunctionExpression(Var instance, Var value, PropertyIdIndexType index)
  7288. {
  7289. JavascriptOperators::OP_StFunctionExpression(instance,
  7290. this->m_functionBody->GetReferencedPropertyId(index), value);
  7291. }
  7292. template <class T>
  7293. void InterpreterStackFrame::OP_LdNewTarget(const unaligned T* playout)
  7294. {
  7295. if (Js::CallInfo::HasNewTarget(this->m_callFlags))
  7296. {
  7297. SetRegAllowStackVar(playout->R0, (Js::RecyclableObject*)Js::CallInfo::GetNewTarget(this->m_callFlags, this->m_inParams, (ArgSlot)this->m_inSlotsCount));
  7298. }
  7299. else if (this->m_callFlags & CallFlags_New)
  7300. {
  7301. SetRegAllowStackVar(playout->R0, this->GetFunctionExpression());
  7302. }
  7303. else
  7304. {
  7305. SetReg(playout->R0, this->GetScriptContext()->GetLibrary()->GetUndefined());
  7306. }
  7307. }
  7308. Var InterpreterStackFrame::OP_Ld_A(Var aValue)
  7309. {
  7310. return aValue;
  7311. }
  7312. Var InterpreterStackFrame::LdEnv() const
  7313. {
  7314. return this->function->GetEnvironment();
  7315. }
  7316. void InterpreterStackFrame::SetEnv(FrameDisplay *frameDisplay)
  7317. {
  7318. this->function->SetEnvironment(frameDisplay);
  7319. }
  7320. Var InterpreterStackFrame::OP_LdLocalObj()
  7321. {
  7322. if (!VirtualTableInfo<ActivationObject>::HasVirtualTable(this->localClosure) &&
  7323. !VirtualTableInfo<ActivationObjectEx>::HasVirtualTable(this->localClosure))
  7324. {
  7325. Js::Throw::FatalInternalError();
  7326. }
  7327. return this->localClosure;
  7328. }
  7329. Var InterpreterStackFrame::OP_LdParamObj()
  7330. {
  7331. if (!VirtualTableInfo<ActivationObject>::HasVirtualTable(this->paramClosure) &&
  7332. !VirtualTableInfo<ActivationObjectEx>::HasVirtualTable(this->paramClosure))
  7333. {
  7334. Js::Throw::FatalInternalError();
  7335. }
  7336. return this->paramClosure;
  7337. }
  7338. #ifdef ASMJS_PLAT
  7339. template <typename ArrayType, typename RegType>
  7340. void InterpreterStackFrame::OP_StArr(uint32 index, RegSlot regSlot)
  7341. {
  7342. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  7343. if (index < arr->GetByteLength())
  7344. {
  7345. BYTE* buffer = arr->GetBuffer();
  7346. *(ArrayType*)(buffer + index) = (ArrayType)GetRegRaw<RegType>(regSlot);
  7347. }
  7348. }
  7349. #endif
  7350. template<> inline double InterpreterStackFrame::GetArrayViewOverflowVal()
  7351. {
  7352. return *(double*)&NumberConstants::k_Nan;
  7353. }
  7354. template<> inline float InterpreterStackFrame::GetArrayViewOverflowVal()
  7355. {
  7356. return (float)*(double*)&NumberConstants::k_Nan;
  7357. }
  7358. template<typename T> T InterpreterStackFrame::GetArrayViewOverflowVal()
  7359. {
  7360. return 0;
  7361. }
  7362. template <class T>
  7363. void InterpreterStackFrame::OP_LdArrFunc(const unaligned T* playout)
  7364. {
  7365. Var* arr = (Var*)GetRegRawPtr(playout->Instance);
  7366. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7367. SetRegRawPtr(playout->Value, arr[index]);
  7368. }
  7369. template <class T>
  7370. void InterpreterStackFrame::OP_LdArrWasmFunc(const unaligned T* playout)
  7371. {
  7372. #ifdef ENABLE_WASM
  7373. WebAssemblyTable * table = WebAssemblyTable::FromVar(GetRegRawPtr(playout->Instance));
  7374. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7375. if (index >= table->GetCurrentLength())
  7376. {
  7377. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_TableIndexOutOfRange);
  7378. }
  7379. Var func = table->DirectGetValue(index);
  7380. if (!func)
  7381. {
  7382. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7383. }
  7384. SetRegRawPtr(playout->Value, func);
  7385. #endif
  7386. }
  7387. template <class T>
  7388. void InterpreterStackFrame::OP_CheckSignature(const unaligned T* playout)
  7389. {
  7390. #ifdef ENABLE_WASM
  7391. ScriptFunction * func = ScriptFunction::FromVar(GetRegRawPtr(playout->R0));
  7392. int sigIndex = playout->C1;
  7393. Wasm::WasmSignature * expected = &m_signatures[sigIndex];
  7394. if (func->GetFunctionInfo()->IsDeferredParseFunction())
  7395. {
  7396. // TODO: should be able to assert this once imports are converted to wasm functions
  7397. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7398. }
  7399. AsmJsFunctionInfo * asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  7400. if (!asmInfo)
  7401. {
  7402. // TODO: should be able to assert this once imports are converted to wasm functions
  7403. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7404. }
  7405. if (!expected->IsEquivalent(asmInfo->GetWasmSignature()))
  7406. {
  7407. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_SignatureMismatch);
  7408. }
  7409. #endif
  7410. }
  7411. #ifdef ASMJS_PLAT
  7412. template <typename ArrayType, typename RegType>
  7413. void InterpreterStackFrame::OP_LdArr(uint32 index, RegSlot regSlot)
  7414. {
  7415. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  7416. BYTE* buffer = arr->GetBuffer();
  7417. ArrayType val = index < (arr->GetByteLength()) ? *(ArrayType*)(buffer + index) : GetArrayViewOverflowVal<ArrayType>();
  7418. SetRegRaw<RegType>(regSlot, (RegType)val);
  7419. }
  7420. #endif
  7421. template <class T, typename T2>
  7422. void InterpreterStackFrame::OP_StSlotPrimitive(const unaligned T* playout)
  7423. {
  7424. T2* buffer = (T2*)GetNonVarReg(playout->Instance);
  7425. buffer[playout->SlotIndex] = GetRegRaw<T2>(playout->Value);
  7426. }
  7427. template <class T>
  7428. void InterpreterStackFrame::OP_LdAsmJsSlot(const unaligned T* playout)
  7429. {
  7430. Var * slotArray = (Var*)GetNonVarReg(playout->Instance);
  7431. SetRegRawPtr(playout->Value, slotArray[playout->SlotIndex]);
  7432. }
  7433. template <class T, typename T2>
  7434. void InterpreterStackFrame::OP_LdSlotPrimitive(const unaligned T* playout)
  7435. {
  7436. T2* buffer = (T2*)GetNonVarReg(playout->Instance);
  7437. SetRegRaw<T2>(playout->Value, buffer[playout->SlotIndex]);
  7438. }
  7439. #ifndef TEMP_DISABLE_ASMJS
  7440. template <class T>
  7441. void InterpreterStackFrame::OP_LdArrGeneric(const unaligned T* playout)
  7442. {
  7443. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7444. switch (playout->ViewType)
  7445. {
  7446. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7447. case ArrayBufferView::ViewType::TYPE_##name: \
  7448. OP_LdArr<MemType, RegType>(index & ARRAYBUFFER_VIEW_MASK(align), playout->Value); \
  7449. return;
  7450. #include "AsmJsArrayBufferViews.h"
  7451. default:Assert(UNREACHED);
  7452. }
  7453. }
  7454. template<typename MemType>
  7455. void InterpreterStackFrame::WasmArrayBoundsCheck(uint64 index, uint32 byteLength)
  7456. {
  7457. if (index + sizeof(MemType) > byteLength)
  7458. {
  7459. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_ArrayIndexOutOfRange);
  7460. }
  7461. }
  7462. template<typename MemType>
  7463. MemType* InterpreterStackFrame::WasmAtomicsArrayBoundsCheck(byte* buffer, uint64 index, uint32 byteLength)
  7464. {
  7465. MemType* readBuffer = (MemType*)(buffer + index);
  7466. // Do alignment check to be coherent with the order the jit does the checks
  7467. if (!::Math::IsAligned<intptr_t>((intptr_t)readBuffer, sizeof(MemType)))
  7468. {
  7469. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_UnalignedAtomicAccess);
  7470. }
  7471. WasmArrayBoundsCheck<MemType>(index, byteLength);
  7472. return readBuffer;
  7473. }
  7474. template <class T>
  7475. void InterpreterStackFrame::OP_LdArrWasm(const unaligned T* playout)
  7476. {
  7477. #ifdef ENABLE_WASM
  7478. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7479. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7480. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7481. uint32 byteLength = arr->GetByteLength();
  7482. BYTE* buffer = arr->GetBuffer();
  7483. switch (playout->ViewType)
  7484. {
  7485. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7486. case ArrayBufferView::ViewType::TYPE_##name: \
  7487. WasmArrayBoundsCheck<MemType>(index, byteLength); \
  7488. SetRegRaw<RegType>(playout->Value, (RegType)*(MemType*)(buffer + index)); \
  7489. return;
  7490. #include "AsmJsArrayBufferViews.h"
  7491. default:Assert(UNREACHED);
  7492. }
  7493. #else
  7494. Assert(UNREACHED);
  7495. #endif
  7496. }
  7497. template <class T>
  7498. void InterpreterStackFrame::OP_LdArrAtomic(const unaligned T* playout)
  7499. {
  7500. #ifdef ENABLE_WASM
  7501. Assert(Wasm::Threads::IsEnabled());
  7502. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7503. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7504. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7505. uint32 byteLength = arr->GetByteLength();
  7506. BYTE* buffer = arr->GetBuffer();
  7507. switch (playout->ViewType)
  7508. {
  7509. #define ARRAYBUFFER_VIEW_INT(name, align, RegType, MemType, ...) \
  7510. case ArrayBufferView::ViewType::TYPE_##name: {\
  7511. MemType* readBuffer = WasmAtomicsArrayBoundsCheck<MemType>(buffer, index, byteLength); \
  7512. MemType value = AtomicsOperations::Load<MemType>(readBuffer); \
  7513. SetRegRaw<RegType>(playout->Value, (RegType)value); \
  7514. return; \
  7515. }
  7516. #include "AsmJsArrayBufferViews.h"
  7517. default:Assert(UNREACHED);
  7518. }
  7519. #else
  7520. Assert(UNREACHED);
  7521. #endif
  7522. }
  7523. template <class T>
  7524. void InterpreterStackFrame::OP_StArrAtomic(const unaligned T* playout)
  7525. {
  7526. #ifdef ENABLE_WASM
  7527. Assert(Wasm::Threads::IsEnabled());
  7528. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7529. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7530. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7531. uint32 byteLength = arr->GetByteLength();
  7532. BYTE* buffer = arr->GetBuffer();
  7533. switch (playout->ViewType)
  7534. {
  7535. #define ARRAYBUFFER_VIEW_INT(name, align, RegType, MemType, ...) \
  7536. case ArrayBufferView::ViewType::TYPE_##name: {\
  7537. MemType* readBuffer = WasmAtomicsArrayBoundsCheck<MemType>(buffer, index, byteLength); \
  7538. MemType value = (MemType)GetRegRaw<RegType>(playout->Value); \
  7539. MemType storedValue = AtomicsOperations::Store<MemType>(readBuffer, value); \
  7540. Assert(storedValue == value); \
  7541. return; \
  7542. }
  7543. #include "AsmJsArrayBufferViews.h"
  7544. default:Assert(UNREACHED);
  7545. }
  7546. #else
  7547. Assert(UNREACHED);
  7548. #endif
  7549. }
  7550. template <class T>
  7551. void InterpreterStackFrame::OP_LdArrConstIndex(const unaligned T* playout)
  7552. {
  7553. switch (playout->ViewType)
  7554. {
  7555. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7556. case ArrayBufferView::ViewType::TYPE_##name: \
  7557. OP_LdArr<MemType, RegType>(playout->SlotIndex, playout->Value); \
  7558. return;
  7559. #include "AsmJsArrayBufferViews.h"
  7560. default:Assert(UNREACHED);
  7561. }
  7562. }
  7563. template <class T>
  7564. void InterpreterStackFrame::OP_StArrGeneric(const unaligned T* playout)
  7565. {
  7566. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7567. switch (playout->ViewType)
  7568. {
  7569. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7570. case ArrayBufferView::ViewType::TYPE_##name: \
  7571. OP_StArr<MemType, RegType>(index & ARRAYBUFFER_VIEW_MASK(align), playout->Value); \
  7572. return;
  7573. #include "AsmJsArrayBufferViews.h"
  7574. default:Assert(UNREACHED);
  7575. }
  7576. }
  7577. template <class T>
  7578. void InterpreterStackFrame::OP_StArrWasm(const unaligned T* playout)
  7579. {
  7580. #ifdef ENABLE_WASM
  7581. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7582. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7583. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7584. uint32 byteLength = arr->GetByteLength();
  7585. BYTE* buffer = arr->GetBuffer();
  7586. switch (playout->ViewType)
  7587. {
  7588. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7589. case ArrayBufferView::ViewType::TYPE_##name: \
  7590. WasmArrayBoundsCheck<MemType>(index, byteLength); \
  7591. *(MemType*)(buffer + index) = (MemType)(GetRegRaw<RegType>(playout->Value)); \
  7592. break;
  7593. #include "AsmJsArrayBufferViews.h"
  7594. default:Assert(UNREACHED);
  7595. }
  7596. CompileAssert(ArrayBufferView::ViewType::TYPE_COUNT == 15);
  7597. #if DBG
  7598. if (PHASE_TRACE(WasmMemWritesPhase, m_functionBody))
  7599. {
  7600. GetWebAssemblyMemory()->TraceMemWrite(GetWebAssemblyMemory(), (uint32)GetRegRawInt(playout->SlotIndex), playout->Offset, playout->ViewType, (uint32)(size_t)this->DEBUG_currentByteOffset, scriptContext);
  7601. }
  7602. #endif
  7603. return;
  7604. #else
  7605. Assert(UNREACHED);
  7606. #endif
  7607. }
  7608. template <class T>
  7609. void InterpreterStackFrame::OP_StArrConstIndex(const unaligned T* playout)
  7610. {
  7611. switch (playout->ViewType)
  7612. {
  7613. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7614. case ArrayBufferView::ViewType::TYPE_##name: \
  7615. OP_StArr<MemType, RegType>(playout->SlotIndex, playout->Value); \
  7616. return;
  7617. #include "AsmJsArrayBufferViews.h"
  7618. default:Assert(UNREACHED);
  7619. }
  7620. }
  7621. #endif
  7622. Var InterpreterStackFrame::OP_LdSlot(Var instance, int32 slotIndex)
  7623. {
  7624. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7625. {
  7626. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7627. {
  7628. Js::Throw::FatalInternalError();
  7629. }
  7630. }
  7631. return ((Var*)(instance))[slotIndex];
  7632. }
  7633. template <class T>
  7634. Var InterpreterStackFrame::OP_LdSlot(Var instance, const unaligned T* playout)
  7635. {
  7636. return OP_LdSlot(instance, playout->SlotIndex);
  7637. }
  7638. #if ENABLE_PROFILE_INFO
  7639. template <class T>
  7640. Var InterpreterStackFrame::OP_ProfiledLdSlot(Var instance, const unaligned T* playout)
  7641. {
  7642. Var value = OP_LdSlot(instance, playout->SlotIndex);
  7643. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7644. return value;
  7645. }
  7646. #endif
  7647. template <class T>
  7648. Var InterpreterStackFrame::OP_LdInnerSlot(Var slotArray, const unaligned T* playout)
  7649. {
  7650. return OP_LdSlot(slotArray, playout->SlotIndex2);
  7651. }
  7652. #if ENABLE_PROFILE_INFO
  7653. template <class T>
  7654. Var InterpreterStackFrame::OP_ProfiledLdInnerSlot(Var slotArray, const unaligned T* playout)
  7655. {
  7656. Var value = OP_LdInnerSlot(slotArray, playout);
  7657. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7658. return value;
  7659. }
  7660. #endif
  7661. template <class T>
  7662. Var InterpreterStackFrame::OP_LdInnerObjSlot(Var slotArray, const unaligned T* playout)
  7663. {
  7664. return OP_LdObjSlot(slotArray, playout->SlotIndex2);
  7665. }
  7666. #if ENABLE_PROFILE_INFO
  7667. template <class T>
  7668. Var InterpreterStackFrame::OP_ProfiledLdInnerObjSlot(Var slotArray, const unaligned T* playout)
  7669. {
  7670. Var value = OP_LdInnerObjSlot(slotArray, playout);
  7671. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7672. return value;
  7673. }
  7674. #endif
  7675. Var InterpreterStackFrame::OP_LdFrameDisplaySlot(Var instance, int32 slotIndex)
  7676. {
  7677. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7678. {
  7679. if (((FrameDisplay*)instance)->GetLength() <= slotIndex - Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Var))
  7680. {
  7681. Js::Throw::FatalInternalError();
  7682. }
  7683. }
  7684. return ((Var*)instance)[slotIndex];
  7685. }
  7686. template <class T>
  7687. Var InterpreterStackFrame::OP_LdEnvObj(Var instance, const unaligned T* playout)
  7688. {
  7689. return OP_LdFrameDisplaySlot(instance, playout->SlotIndex);
  7690. }
  7691. template <class T>
  7692. Var InterpreterStackFrame::OP_LdEnvSlot(Var instance, const unaligned T* playout)
  7693. {
  7694. Var slotArray = OP_LdFrameDisplaySlot(instance, playout->SlotIndex1);
  7695. return OP_LdSlot(slotArray, playout->SlotIndex2);
  7696. }
  7697. #if ENABLE_PROFILE_INFO
  7698. template <class T>
  7699. Var InterpreterStackFrame::OP_ProfiledLdEnvSlot(Var instance, const unaligned T* playout)
  7700. {
  7701. Var value = OP_LdEnvSlot(instance, playout);
  7702. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7703. return value;
  7704. }
  7705. #endif
  7706. Var InterpreterStackFrame::OP_LdObjSlot(Var instance, int32 slotIndex)
  7707. {
  7708. Var *slotArray = *(Var**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7709. return slotArray[slotIndex];
  7710. }
  7711. template <class T>
  7712. Var InterpreterStackFrame::OP_LdObjSlot(Var instance, const unaligned T* playout)
  7713. {
  7714. return OP_LdObjSlot(instance, playout->SlotIndex);
  7715. }
  7716. #if ENABLE_PROFILE_INFO
  7717. template <class T>
  7718. Var InterpreterStackFrame::OP_ProfiledLdObjSlot(Var instance, const unaligned T* playout)
  7719. {
  7720. Var value = OP_LdObjSlot(instance, playout->SlotIndex);
  7721. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7722. return value;
  7723. }
  7724. #endif
  7725. template <class T>
  7726. Var InterpreterStackFrame::OP_LdEnvObjSlot(Var instance, const unaligned T* playout)
  7727. {
  7728. Var slotArray = OP_LdFrameDisplaySlot(instance, playout->SlotIndex1);
  7729. return OP_LdObjSlot(slotArray, playout->SlotIndex2);
  7730. }
  7731. template <class T>
  7732. Var InterpreterStackFrame::OP_LdModuleSlot(Var instance, const unaligned T* playout)
  7733. {
  7734. return JavascriptOperators::OP_LdModuleSlot(playout->SlotIndex1, playout->SlotIndex2, scriptContext);
  7735. }
  7736. inline void InterpreterStackFrame::OP_StModuleSlot(Var instance, uint32 slotIndex1, uint32 slotIndex2, Var value)
  7737. {
  7738. JavascriptOperators::OP_StModuleSlot(slotIndex1, slotIndex2, value, scriptContext);
  7739. }
  7740. #if ENABLE_PROFILE_INFO
  7741. template <class T>
  7742. Var InterpreterStackFrame::OP_ProfiledLdEnvObjSlot(Var instance, const unaligned T* playout)
  7743. {
  7744. Var value = OP_LdEnvObjSlot(instance, playout);
  7745. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7746. return value;
  7747. }
  7748. #endif
  7749. void InterpreterStackFrame::OP_StSlot(Var instance, int32 slotIndex, Var value)
  7750. {
  7751. // We emit OpCode::StSlot in the bytecode only for scope slot arrays, which are not recyclable objects.
  7752. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7753. {
  7754. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7755. {
  7756. Js::Throw::FatalInternalError();
  7757. }
  7758. }
  7759. ((Field(Var)*)(instance))[slotIndex] = value;
  7760. }
  7761. void InterpreterStackFrame::OP_StEnvSlot(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7762. {
  7763. Var slotArray = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7764. OP_StSlot(slotArray, slotIndex2, value);
  7765. }
  7766. void InterpreterStackFrame::OP_StSlotChkUndecl(Var instance, int32 slotIndex, Var value)
  7767. {
  7768. // We emit OpCode::StSlot in the bytecode only for scope slot arrays, which are not recyclable objects.
  7769. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7770. {
  7771. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7772. {
  7773. Js::Throw::FatalInternalError();
  7774. }
  7775. }
  7776. OP_ChkUndecl(((Field(Var)*)instance)[slotIndex]);
  7777. ((Field(Var)*)(instance))[slotIndex] = value;
  7778. }
  7779. void InterpreterStackFrame::OP_StEnvSlotChkUndecl(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7780. {
  7781. Var slotArray = OP_LdFrameDisplaySlot(instance, slotIndex1);
  7782. OP_StSlotChkUndecl(slotArray, slotIndex2, value);
  7783. }
  7784. void InterpreterStackFrame::OP_StObjSlot(Var instance, int32 slotIndex, Var value)
  7785. {
  7786. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7787. Field(Var) *slotArray = *(Field(Var)**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7788. slotArray[slotIndex] = value;
  7789. }
  7790. void InterpreterStackFrame::OP_StObjSlotChkUndecl(Var instance, int32 slotIndex, Var value)
  7791. {
  7792. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7793. Field(Var) *slotArray = *(Field(Var)**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7794. OP_ChkUndecl(slotArray[slotIndex]);
  7795. slotArray[slotIndex] = value;
  7796. }
  7797. void InterpreterStackFrame::OP_StEnvObjSlot(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7798. {
  7799. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7800. Var envInstance = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7801. OP_StObjSlot(envInstance, slotIndex2, value);
  7802. }
  7803. void InterpreterStackFrame::OP_StEnvObjSlotChkUndecl(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7804. {
  7805. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7806. Var envInstance = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7807. OP_StObjSlotChkUndecl(envInstance, slotIndex2, value);
  7808. }
  7809. Var InterpreterStackFrame::OP_LdStackArgPtr(void)
  7810. {
  7811. // Return the address of the first param after "this".
  7812. return m_inParams + 1;
  7813. }
  7814. ForInObjectEnumerator * InterpreterStackFrame::GetForInEnumerator(uint forInLoopLevel)
  7815. {
  7816. Assert(forInLoopLevel < this->m_functionBody->GetForInLoopDepth());
  7817. return &this->forInObjectEnumerators[forInLoopLevel];
  7818. }
  7819. void InterpreterStackFrame::OP_InitForInEnumerator(Var object, uint forInLoopLevel)
  7820. {
  7821. JavascriptOperators::OP_InitForInEnumerator(object, GetForInEnumerator(forInLoopLevel), this->GetScriptContext());
  7822. }
  7823. void InterpreterStackFrame::OP_InitForInEnumeratorWithCache(Var object, uint forInLoopLevel, ProfileId profileId)
  7824. {
  7825. JavascriptOperators::OP_InitForInEnumerator(object, GetForInEnumerator(forInLoopLevel), this->GetScriptContext(),
  7826. m_functionBody->GetForInCache(profileId));
  7827. }
  7828. // Called for the debug purpose, to create the arguments object explicitly even though script has not declared it.
  7829. Var InterpreterStackFrame::CreateHeapArguments(ScriptContext* scriptContext)
  7830. {
  7831. return JavascriptOperators::LoadHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, &this->m_inParams[1], scriptContext->GetLibrary()->GetNull(), scriptContext->GetLibrary()->GetNull(), scriptContext, false);
  7832. }
  7833. template <bool letArgs>
  7834. Var InterpreterStackFrame::LdHeapArgumentsImpl(Var argsArray, ScriptContext* scriptContext)
  7835. {
  7836. Var frameObj;
  7837. if (m_functionBody->HasScopeObject() && argsArray != scriptContext->GetLibrary()->GetNull())
  7838. {
  7839. frameObj = this->localClosure;
  7840. Assert(frameObj);
  7841. }
  7842. else
  7843. {
  7844. frameObj = scriptContext->GetLibrary()->GetNull();
  7845. }
  7846. Var args = JavascriptOperators::LoadHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, &this->m_inParams[1], frameObj, argsArray, scriptContext, letArgs);
  7847. this->m_arguments = args;
  7848. return args;
  7849. }
  7850. Var InterpreterStackFrame::OP_LdHeapArguments(ScriptContext* scriptContext)
  7851. {
  7852. Var argsArray = m_functionBody->GetFormalsPropIdArrayOrNullObj();
  7853. return LdHeapArgumentsImpl<false>(argsArray, scriptContext);
  7854. }
  7855. Var InterpreterStackFrame::OP_LdLetHeapArguments(ScriptContext* scriptContext)
  7856. {
  7857. Var argsArray = m_functionBody->GetFormalsPropIdArrayOrNullObj();
  7858. return LdHeapArgumentsImpl<true>(argsArray, scriptContext);
  7859. }
  7860. Var InterpreterStackFrame::OP_LdHeapArgsCached(ScriptContext* scriptContext)
  7861. {
  7862. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7863. Var args = JavascriptOperators::LoadHeapArgsCached(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, &this->m_inParams[1], this->localClosure, scriptContext, false);
  7864. this->m_arguments = args;
  7865. return args;
  7866. }
  7867. Var InterpreterStackFrame::OP_LdLetHeapArgsCached(ScriptContext* scriptContext)
  7868. {
  7869. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7870. Var args = JavascriptOperators::LoadHeapArgsCached(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, &this->m_inParams[1], this->localClosure, scriptContext, true);
  7871. this->m_arguments = args;
  7872. return args;
  7873. }
  7874. HeapArgumentsObject * InterpreterStackFrame::CreateEmptyHeapArgumentsObject(ScriptContext* scriptContext)
  7875. {
  7876. HeapArgumentsObject * args = JavascriptOperators::CreateHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, 0, nullptr, scriptContext);
  7877. this->m_arguments = args;
  7878. return args;
  7879. }
  7880. void InterpreterStackFrame::TrySetFrameObjectInHeapArgObj(ScriptContext * scriptContext, bool hasNonSimpleParams, bool isScopeObjRestored)
  7881. {
  7882. Var frameObject = nullptr;
  7883. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7884. Js::PropertyIdArray * propIds = nullptr;
  7885. Js::HeapArgumentsObject* heapArgObj = nullptr;
  7886. //We always set the Frame object to nullptr in BailOutRecord::EnsureArguments for stack args optimization.
  7887. if (m_arguments != nullptr && ((Js::HeapArgumentsObject*)(m_arguments))->GetFrameObject() == nullptr)
  7888. {
  7889. heapArgObj = (Js::HeapArgumentsObject*)m_arguments;
  7890. }
  7891. bool isCachedScope = false;
  7892. //For Non-simple params, we don't have a scope object created.
  7893. if (this->m_functionBody->NeedScopeObjectForArguments(hasNonSimpleParams))
  7894. {
  7895. frameObject = GetLocalClosure();
  7896. isCachedScope = m_functionBody->HasCachedScopePropIds();
  7897. propIds = this->m_functionBody->GetFormalsPropIdArray();
  7898. if(isScopeObjRestored && ActivationObject::Is(frameObject))
  7899. {
  7900. Assert(this->GetFunctionBody()->GetDoScopeObjectCreation());
  7901. isCachedScope = true;
  7902. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && m_functionBody->GetInParamsCount() > 1)
  7903. {
  7904. Output::Print(_u("StackArgFormals : %s (%d) :Using the restored scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7905. Output::Flush();
  7906. }
  7907. }
  7908. else
  7909. {
  7910. if (isCachedScope)
  7911. {
  7912. Field(DynamicType*) literalType = nullptr;
  7913. Assert(!propIds->hasNonSimpleParams && !hasNonSimpleParams);
  7914. frameObject = JavascriptOperators::OP_InitCachedScope(this->GetJavascriptFunction(), propIds, &literalType, hasNonSimpleParams, scriptContext);
  7915. }
  7916. else
  7917. {
  7918. frameObject = JavascriptOperators::OP_NewScopeObject(GetScriptContext());
  7919. }
  7920. Assert(propIds != nullptr);
  7921. SetLocalClosure(frameObject);
  7922. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && m_functionBody->GetInParamsCount() > 1)
  7923. {
  7924. Output::Print(_u("StackArgFormals : %s (%d) :Creating scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7925. Output::Flush();
  7926. }
  7927. }
  7928. }
  7929. else
  7930. {
  7931. //We reached here because, either we don't have any formals or we don't have a scope object (it could be in strict mode or have non-simple param list)
  7932. Assert(formalsCount == 0 || (m_functionBody->GetIsStrictMode() || hasNonSimpleParams));
  7933. frameObject = nullptr;
  7934. formalsCount = 0;
  7935. if (PHASE_VERBOSE_TRACE1(Js::StackArgOptPhase))
  7936. {
  7937. Output::Print(_u("StackArgOpt : %s (%d) :Creating NULL scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7938. Output::Flush();
  7939. }
  7940. }
  7941. if (heapArgObj)
  7942. {
  7943. Assert(frameObject == nullptr || ActivationObject::Is(frameObject));
  7944. heapArgObj->SetFormalCount(formalsCount);
  7945. heapArgObj->SetFrameObject(frameObject != nullptr ?
  7946. static_cast<ActivationObject*>(frameObject) : nullptr);
  7947. if (PHASE_TRACE1(Js::StackArgFormalsOptPhase) && formalsCount > 0)
  7948. {
  7949. Output::Print(_u("StackArgFormals : %s (%d) :Attaching the scope object with the heap arguments object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7950. Output::Flush();
  7951. }
  7952. }
  7953. //Fill the Heap arguments and scope object with values
  7954. // If there is no heap arguments object, then fill only the scope object with actuals.
  7955. JavascriptOperators::FillScopeObject(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, frameObject, &this->m_inParams[1], propIds, heapArgObj, scriptContext, hasNonSimpleParams, isCachedScope);
  7956. }
  7957. Var InterpreterStackFrame::OP_LdArgumentsFromFrame()
  7958. {
  7959. return this->m_arguments;
  7960. }
  7961. void* InterpreterStackFrame::OP_LdArgCnt()
  7962. {
  7963. return (void*)m_inSlotsCount;
  7964. }
  7965. Var InterpreterStackFrame::OP_ResumeYield(Var yieldDataVar, RegSlot yieldStarIterator)
  7966. {
  7967. ResumeYieldData* yieldData = static_cast<ResumeYieldData*>(yieldDataVar);
  7968. RecyclableObject* iterator = yieldStarIterator != Constants::NoRegister ? RecyclableObject::FromVar(GetNonVarReg(yieldStarIterator)) : nullptr;
  7969. return JavascriptOperators::OP_ResumeYield(yieldData, iterator);
  7970. }
  7971. void* InterpreterStackFrame::operator new(size_t byteSize, void* previousAllocation) throw()
  7972. {
  7973. //
  7974. // Placement 'new' is used by InterpreterStackFrame to initialize the C++ object on the RcInterpreter's
  7975. // program stack:
  7976. // - Unlike most other allocations, the previously allocated memory will __not__ be
  7977. // zero-initialized, as we do not want the overhead of zero-initializing the frame when
  7978. // calling functions.
  7979. //
  7980. // NOTE: If we wanted to add C# semantics of all locals are automatically zero-initialized,
  7981. // need to determine the most efficient mechanism for this.
  7982. //
  7983. return previousAllocation;
  7984. }
  7985. void __cdecl InterpreterStackFrame::operator delete(void * allocationToFree, void * previousAllocation) throw()
  7986. {
  7987. AssertMsg(allocationToFree == previousAllocation, "Memory locations should match");
  7988. AssertMsg(false, "This function should never actually be called");
  7989. }
  7990. void InterpreterStackFrame::OP_WasmPrintFunc(int regIndex)
  7991. {
  7992. #if defined(ENABLE_DEBUG_CONFIG_OPTIONS) && defined(ENABLE_WASM)
  7993. Assert(m_functionBody->IsWasmFunction());
  7994. uint index = GetRegRawInt(regIndex);
  7995. Wasm::WasmFunctionInfo* info = m_functionBody->GetAsmJsFunctionInfo()->GetWebAssemblyModule()->GetWasmFunctionInfo(index);
  7996. int col = WAsmJs::Tracing::GetPrintCol();
  7997. if (col > 0)
  7998. {
  7999. Output::SkipToColumn(col);
  8000. }
  8001. info->GetBody()->DumpFullFunctionName();
  8002. Output::Print(_u("("));
  8003. #endif
  8004. }
  8005. JavascriptArrayBuffer* InterpreterStackFrame::GetAsmJsBuffer() const
  8006. {
  8007. AssertMsg(!m_functionBody->IsWasmFunction(), "Do not use GetAsmJsBuffer for WebAssembly, Use GetWebAssemblyMemory instead");
  8008. return m_asmJsBuffer;
  8009. }
  8010. #ifdef ENABLE_WASM
  8011. WebAssemblyMemory* InterpreterStackFrame::GetWebAssemblyMemory() const
  8012. {
  8013. AssertMsg(m_functionBody->IsWasmFunction(), "Do not use GetWebAssemblyMemory for Asm.js, Use GetAsmJsBuffer instead");
  8014. return m_wasmMemory;
  8015. }
  8016. #endif
  8017. template void* Js::InterpreterStackFrame::GetReg<unsigned int>(unsigned int) const;
  8018. template void Js::InterpreterStackFrame::SetReg<unsigned int>(unsigned int, void*);
  8019. } // namespace Js
  8020. // Make sure the macro and the layout for the op is consistent
  8021. #define DEF2(x, op, ...) \
  8022. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8023. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8024. #define DEF3(x, op, ...) DEF2(x, op)
  8025. #define EXDEF2(x, op, ...) \
  8026. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8027. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8028. #define EXDEF3(x, op, ...) EXDEF2(x, op)
  8029. #define DEF2_WMS(x, op, ...) \
  8030. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8031. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8032. #define DEF3_WMS(x, op, ...) DEF2_WMS(x, op)
  8033. #define EXDEF2_WMS(x, op, ...) \
  8034. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8035. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8036. #define EXDEF3_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8037. #include "InterpreterHandler.inl"
  8038. // Make sure the macro and the layout for the op is consistent
  8039. #define DEF2(x, op, ...) \
  8040. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8041. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8042. #define DEF3(x, op, ...) DEF2(x, op)
  8043. #define DEF4(x, op, ...) DEF2(x, op)
  8044. #define EXDEF2(x, op, ...) \
  8045. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8046. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8047. #define EXDEF3(x, op, ...) EXDEF2(x, op)
  8048. #define EXDEF4(x, op, ...) EXDEF2(x, op)
  8049. #define DEF2_WMS(x, op, ...) \
  8050. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8051. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8052. #define DEF3_WMS(x, op, ...) DEF2_WMS(x, op)
  8053. #define DEF4_WMS(x, op, ...) DEF2_WMS(x, op)
  8054. #define EXDEF2_WMS(x, op, ...) \
  8055. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8056. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8057. #define EXDEF3_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8058. #define EXDEF4_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8059. #include "InterpreterHandlerAsmJs.inl"