ByteCodeEmitter.cpp 469 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeByteCodePch.h"
  6. #include "FormalsUtil.h"
  7. #include "Language/AsmJs.h"
  8. #include "ConfigFlagsList.h"
  9. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  10. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  12. void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
  13. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator = Js::Constants::NoRegister);
  14. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  15. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  16. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  17. bool CallTargetIsArray(ParseNode *pnode)
  18. {
  19. return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
  20. }
  21. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  22. if ((isTopLevel)) \
  23. { \
  24. byteCodeGenerator->StartStatement(pnode); \
  25. }
  26. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  27. if ((isTopLevel)) \
  28. { \
  29. byteCodeGenerator->EndStatement(pnode); \
  30. }
  31. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE, ByteCodeGenerator *byteCodeGenerator)
  32. {
  33. // Try to determine whether pnodeSE (SE = side effect) may kill the named var represented by pnode.
  34. if (pnode->nop == knopComputedName)
  35. {
  36. pnode = pnode->AsParseNodeUni()->pnode1;
  37. }
  38. if (pnode->nop != knopName)
  39. {
  40. // Only investigating named vars here.
  41. return false;
  42. }
  43. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  44. SList<ParseNode*> pNodeSEStack(alloc);
  45. pNodeSEStack.Push(pnodeSE);
  46. // A pnodeSE can have children that can cause a side effect on pnode. A stack is used to check
  47. // pnodeSE and all potential pnodeSE children that could cause a side effect on pnode. When a
  48. // child pnodeSE can cause a side effect on pnode, immediately return true. Otherwise continue
  49. // checking children of pnodeSE until none exist
  50. while (!pNodeSEStack.Empty())
  51. {
  52. ParseNode *currPnodeSE = pNodeSEStack.Pop();
  53. uint fnop = ParseNode::Grfnop(currPnodeSE->nop);
  54. if (fnop & fnopLeaf)
  55. {
  56. // pnodeSE is a leaf and can't kill anything.
  57. continue;
  58. }
  59. else if (fnop & fnopAsg)
  60. {
  61. // pnodeSE is an assignment (=, ++, +=, etc.)
  62. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  63. // maybe because of code layout or some other subtle effect.
  64. return true;
  65. }
  66. else if (fnop & fnopUni)
  67. {
  68. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  69. if (currPnodeSE->nop == knopTempRef)
  70. {
  71. continue;
  72. }
  73. else if (currPnodeSE->AsParseNodeUni()->pnode1)
  74. {
  75. pNodeSEStack.Push(currPnodeSE->AsParseNodeUni()->pnode1);
  76. }
  77. }
  78. else if (fnop & fnopBin)
  79. {
  80. // currPnodeSE is a binary (or ternary) op, so check sources (if present).
  81. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode1);
  82. if (currPnodeSE->AsParseNodeBin()->pnode2)
  83. {
  84. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode2);
  85. }
  86. }
  87. else if (currPnodeSE->nop == knopQmark)
  88. {
  89. ParseNodeTri * pnodeTriSE = currPnodeSE->AsParseNodeTri();
  90. pNodeSEStack.Push(pnodeTriSE->pnode1);
  91. pNodeSEStack.Push(pnodeTriSE->pnode2);
  92. pNodeSEStack.Push(pnodeTriSE->pnode3);
  93. }
  94. else if (currPnodeSE->nop == knopCall || currPnodeSE->nop == knopNew)
  95. {
  96. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeTarget);
  97. if (currPnodeSE->AsParseNodeCall()->pnodeArgs)
  98. {
  99. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeArgs);
  100. }
  101. }
  102. else if (currPnodeSE->nop == knopList)
  103. {
  104. return true;
  105. }
  106. }
  107. return false;
  108. }
  109. bool IsCallOfConstants(ParseNode *pnode);
  110. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  111. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  112. bool IsArguments(ParseNode *pnode)
  113. {
  114. for (;;)
  115. {
  116. switch (pnode->nop)
  117. {
  118. case knopName:
  119. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  120. case knopCall:
  121. case knopNew:
  122. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  123. {
  124. return true;
  125. }
  126. if (pnode->AsParseNodeCall()->pnodeArgs)
  127. {
  128. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  129. while (pnodeArg->nop == knopList)
  130. {
  131. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  132. return true;
  133. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  134. }
  135. pnode = pnodeArg;
  136. break;
  137. }
  138. return false;
  139. case knopArray:
  140. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  141. {
  142. return false;
  143. }
  144. pnode = pnode->AsParseNodeUni()->pnode1;
  145. break;
  146. case knopQmark:
  147. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  148. {
  149. return true;
  150. }
  151. pnode = pnode->AsParseNodeTri()->pnode3;
  152. break;
  153. //
  154. // Cases where we don't check for "arguments" yet.
  155. // Assume that they might have it. Disable the optimization is such scenarios
  156. //
  157. case knopList:
  158. case knopObject:
  159. case knopVarDecl:
  160. case knopConstDecl:
  161. case knopLetDecl:
  162. case knopFncDecl:
  163. case knopClassDecl:
  164. case knopFor:
  165. case knopIf:
  166. case knopDoWhile:
  167. case knopWhile:
  168. case knopForIn:
  169. case knopForOf:
  170. case knopReturn:
  171. case knopBlock:
  172. case knopBreak:
  173. case knopContinue:
  174. case knopTypeof:
  175. case knopThrow:
  176. case knopWith:
  177. case knopFinally:
  178. case knopTry:
  179. case knopTryCatch:
  180. case knopTryFinally:
  181. case knopArrayPattern:
  182. case knopObjectPattern:
  183. case knopParamPattern:
  184. return true;
  185. default:
  186. {
  187. uint flags = ParseNode::Grfnop(pnode->nop);
  188. if (flags&fnopUni)
  189. {
  190. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  191. Assert(pnodeUni->pnode1);
  192. pnode = pnodeUni->pnode1;
  193. break;
  194. }
  195. else if (flags&fnopBin)
  196. {
  197. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  198. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  199. if (IsArguments(pnodeBin->pnode1))
  200. {
  201. return true;
  202. }
  203. pnode = pnodeBin->pnode2;
  204. break;
  205. }
  206. return false;
  207. }
  208. }
  209. }
  210. }
  211. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  212. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
  213. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  214. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  215. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  216. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  217. static const Js::OpCode nopToOp[knopLim] =
  218. {
  219. #define OP(x) Br##x##_A
  220. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  221. #include "ptlist.h"
  222. };
  223. static const Js::OpCode nopToCMOp[knopLim] =
  224. {
  225. #define OP(x) Cm##x##_A
  226. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  227. #include "ptlist.h"
  228. };
  229. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  230. {
  231. switch (op)
  232. {
  233. case Js::OpCode::StLocalSlot:
  234. return Js::OpCode::StLocalSlotChkUndecl;
  235. case Js::OpCode::StParamSlot:
  236. return Js::OpCode::StParamSlotChkUndecl;
  237. case Js::OpCode::StInnerSlot:
  238. return Js::OpCode::StInnerSlotChkUndecl;
  239. case Js::OpCode::StEnvSlot:
  240. return Js::OpCode::StEnvSlotChkUndecl;
  241. case Js::OpCode::StObjSlot:
  242. return Js::OpCode::StObjSlotChkUndecl;
  243. case Js::OpCode::StLocalObjSlot:
  244. return Js::OpCode::StLocalObjSlotChkUndecl;
  245. case Js::OpCode::StParamObjSlot:
  246. return Js::OpCode::StParamObjSlotChkUndecl;
  247. case Js::OpCode::StInnerObjSlot:
  248. return Js::OpCode::StInnerObjSlotChkUndecl;
  249. case Js::OpCode::StEnvObjSlot:
  250. return Js::OpCode::StEnvObjSlotChkUndecl;
  251. default:
  252. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  253. return Js::OpCode::InvalidOpCode;
  254. }
  255. }
  256. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  257. // debuggerScope - The scope to add the variable to.
  258. // symbol - The symbol that represents the register property.
  259. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  260. // flags - The flags to assign to the property.
  261. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  262. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  263. Js::DebuggerScope *debuggerScope,
  264. Symbol *symbol,
  265. FuncInfo *funcInfo,
  266. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  267. bool isFunctionDeclaration /*= false*/)
  268. {
  269. Assert(debuggerScope);
  270. Assert(symbol);
  271. Assert(funcInfo);
  272. Js::RegSlot location = symbol->GetLocation();
  273. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  274. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  275. {
  276. // We have to get the appropriate scope and add property over there.
  277. // Make sure the scope is created whether we're in debug mode or not, because we
  278. // need the empty scopes present during reparsing for debug mode.
  279. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  280. }
  281. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  282. {
  283. // Only track the property if we're in debug mode since it's only needed by the debugger.
  284. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  285. this->Writer()->AddPropertyToDebuggerScope(
  286. correctDebuggerScope,
  287. location,
  288. propertyId,
  289. /*shouldConsumeRegister*/ true,
  290. flags,
  291. isFunctionDeclaration);
  292. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  293. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  294. symbol->SetIsTrackedForDebugger(true);
  295. }
  296. }
  297. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  298. Js::DebuggerScope *debuggerScope,
  299. Symbol *symbol,
  300. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  301. bool isFunctionDeclaration /*= false*/)
  302. {
  303. Assert(debuggerScope);
  304. Assert(symbol);
  305. // Only need to track activation object properties in debug mode.
  306. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  307. {
  308. Js::RegSlot location = symbol->GetLocation();
  309. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  310. this->Writer()->AddPropertyToDebuggerScope(
  311. debuggerScope,
  312. location,
  313. propertyId,
  314. /*shouldConsumeRegister*/ false,
  315. flags,
  316. isFunctionDeclaration);
  317. symbol->SetIsTrackedForDebugger(true);
  318. }
  319. }
  320. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  321. Js::DebuggerScope *debuggerScope,
  322. Symbol* symbol,
  323. Js::PropertyId propertyId,
  324. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  325. bool isFunctionDeclaration /*= false*/)
  326. {
  327. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  328. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  329. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  330. Assert(debuggerScope);
  331. Assert(symbol);
  332. if (!symbol->GetIsTrackedForDebugger())
  333. {
  334. Js::RegSlot location = symbol->GetScopeSlot();
  335. Assert(location != Js::Constants::NoRegister);
  336. Assert(propertyId != Js::Constants::NoProperty);
  337. this->Writer()->AddPropertyToDebuggerScope(
  338. debuggerScope,
  339. location,
  340. propertyId,
  341. /*shouldConsumeRegister*/ false,
  342. flags,
  343. isFunctionDeclaration);
  344. symbol->SetIsTrackedForDebugger(true);
  345. }
  346. }
  347. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  348. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  349. {
  350. Assert(functionDeclarationSymbol);
  351. Assert(funcInfoParent);
  352. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  353. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  354. // which is done in other Track* functions that we call.
  355. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  356. {
  357. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  358. {
  359. this->TrackActivationObjectPropertyForDebugger(
  360. this->Writer()->GetCurrentDebuggerScope(),
  361. functionDeclarationSymbol,
  362. Js::DebuggerScopePropertyFlags_None,
  363. true /*isFunctionDeclaration*/);
  364. }
  365. else
  366. {
  367. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  368. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  369. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  370. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  371. functionDeclarationSymbol->EnsurePosition(this);
  372. this->TrackSlotArrayPropertyForDebugger(
  373. this->Writer()->GetCurrentDebuggerScope(),
  374. functionDeclarationSymbol,
  375. functionDeclarationSymbol->GetPosition(),
  376. Js::DebuggerScopePropertyFlags_None,
  377. true /*isFunctionDeclaration*/);
  378. }
  379. }
  380. else
  381. {
  382. this->TrackRegisterPropertyForDebugger(
  383. this->Writer()->GetCurrentDebuggerScope(),
  384. functionDeclarationSymbol,
  385. funcInfoParent,
  386. Js::DebuggerScopePropertyFlags_None,
  387. true /*isFunctionDeclaration*/);
  388. }
  389. }
  390. // Updates the byte code offset of the property with the passed in location and ID.
  391. // Used to track let/const variables that are in the dead zone debugger side.
  392. // location - The activation object, scope slot index, or register location for the property.
  393. // propertyId - The ID of the property to update.
  394. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  395. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  396. {
  397. Assert(this->Writer());
  398. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  399. Assert(currentDebuggerScope);
  400. if (currentDebuggerScope != nullptr)
  401. {
  402. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  403. currentDebuggerScope,
  404. location,
  405. propertyId,
  406. shouldConsumeRegister);
  407. }
  408. }
  409. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  410. {
  411. if (funcInfo->GetHasCachedScope())
  412. {
  413. this->LoadCachedHeapArguments(funcInfo);
  414. }
  415. else
  416. {
  417. this->LoadUncachedHeapArguments(funcInfo);
  418. }
  419. }
  420. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  421. {
  422. Assert(funcInfo);
  423. Assert(propIds);
  424. Assert(byteCodeGenerator);
  425. bool hadDuplicates = false;
  426. Js::ArgSlot i = 0;
  427. auto processArg = [&](ParseNode *pnode)
  428. {
  429. if (pnode->IsVarLetOrConst())
  430. {
  431. Assert(i < propIds->count);
  432. Symbol *sym = pnode->AsParseNodeVar()->sym;
  433. Assert(sym);
  434. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  435. //
  436. // Check if the function has any same name parameters
  437. // For the same name param, only the last one will be passed the correct propertyid
  438. // For remaining dup param names, pass Constants::NoProperty
  439. //
  440. for (Js::ArgSlot j = 0; j < i; j++)
  441. {
  442. if (propIds->elements[j] == symPos)
  443. {
  444. // Found a dup parameter name
  445. propIds->elements[j] = Js::Constants::NoProperty;
  446. hadDuplicates = true;
  447. break;
  448. }
  449. }
  450. propIds->elements[i] = symPos;
  451. }
  452. else
  453. {
  454. propIds->elements[i] = Js::Constants::NoProperty;
  455. }
  456. ++i;
  457. };
  458. MapFormals(funcInfo->root, processArg);
  459. propIds->hadDuplicates = hadDuplicates;
  460. }
  461. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  462. {
  463. Assert(funcInfo->GetHasHeapArguments());
  464. Scope *scope = funcInfo->GetBodyScope();
  465. Assert(scope);
  466. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  467. Assert(argSym && argSym->IsArguments());
  468. Js::RegSlot argumentsLoc = argSym->GetLocation();
  469. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  470. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  471. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  472. if (count == 0)
  473. {
  474. // If no formals to function (only "this"), then no need to create the scope object.
  475. // Leave both the arguments location and the propertyIds location as null.
  476. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  477. }
  478. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  479. {
  480. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  481. }
  482. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  483. {
  484. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  485. // at the expected location.
  486. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  487. GetFormalArgsArray(this, funcInfo, propIds);
  488. }
  489. this->m_writer.Reg1(opcode, argumentsLoc);
  490. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  491. }
  492. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  493. {
  494. Assert(funcInfo->GetHasHeapArguments());
  495. Scope *scope = funcInfo->GetBodyScope();
  496. Assert(scope);
  497. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  498. Assert(argSym && argSym->IsArguments());
  499. Js::RegSlot argumentsLoc = argSym->GetLocation();
  500. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  501. this->m_writer.Reg1(op, argumentsLoc);
  502. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  503. }
  504. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  505. {
  506. Assert(stringNodeList);
  507. uint index = 0;
  508. Js::Var str;
  509. IdentPtr pid;
  510. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  511. while (stringNodeList->nop == knopList)
  512. {
  513. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  514. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  515. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  516. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  517. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  518. index++;
  519. }
  520. Assert(stringNodeList->nop == knopStr);
  521. pid = stringNodeList->AsParseNodeStr()->pid;
  522. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  523. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  524. return pArr;
  525. }
  526. // For now, this just assigns field ids for the current script.
  527. // Later, we will combine this information with the global field id map.
  528. // This temporary code will not work if a global member is accessed both with and without a LHS.
  529. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  530. {
  531. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  532. {
  533. this->AssignPropertyId(sym, functionInfo);
  534. });
  535. }
  536. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  537. {
  538. Assert(pnodeBlock->nop == knopBlock);
  539. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  540. {
  541. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  542. // the debugger scope will not be created.
  543. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  544. FuncInfo *funcInfo = this->TopFuncInfo();
  545. Symbol *sym = pnode->AsParseNodeVar()->sym;
  546. Scope *scope = sym->GetScope();
  547. if (sym->GetIsGlobal())
  548. {
  549. Js::PropertyId propertyId = sym->EnsurePosition(this);
  550. if (this->flags & fscrEval)
  551. {
  552. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  553. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  554. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  555. }
  556. else
  557. {
  558. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  559. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  560. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  561. }
  562. }
  563. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  564. {
  565. if (scope->GetIsObject())
  566. {
  567. Js::RegSlot scopeLocation = scope->GetLocation();
  568. Js::PropertyId propertyId = sym->EnsurePosition(this);
  569. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  570. {
  571. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  572. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  573. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  574. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  575. }
  576. else
  577. {
  578. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  579. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  580. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  581. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  582. }
  583. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  584. }
  585. else
  586. {
  587. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  588. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  589. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  590. funcInfo->ReleaseTmpRegister(tmpReg);
  591. // Slot array properties are tracked in non-debug mode as well because they need to stay
  592. // around for heap enumeration and escaping during attach/detach.
  593. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  594. }
  595. }
  596. else if (!sym->GetIsModuleExportStorage())
  597. {
  598. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  599. {
  600. // let/const declared in a switch is the only case of a variable that must be checked for
  601. // use-before-declaration dynamically within its own function.
  602. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  603. }
  604. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  605. // will live only in slots, so tell the debugger to find them there.
  606. if (sym->NeedsSlotAlloc(this, funcInfo))
  607. {
  608. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  609. }
  610. else
  611. {
  612. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  613. }
  614. }
  615. };
  616. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  617. }
  618. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  619. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  620. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  621. {
  622. Assert(pnode);
  623. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  624. {
  625. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  626. // don't add a block to the chain if it has no let/const variables at all.
  627. return nullptr;
  628. }
  629. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  630. }
  631. // Records the end of the current scope, but only if the current block has block scoped content.
  632. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  633. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  634. {
  635. Assert(pnodeBlock);
  636. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  637. {
  638. return;
  639. }
  640. this->Writer()->RecordEndScopeObject();
  641. }
  642. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  643. {
  644. Js::DebuggerScope* debuggerScope = nullptr;
  645. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  646. {
  647. Scope *scope = pnodeBlock->scope;
  648. byteCodeGenerator->PushScope(scope);
  649. Js::RegSlot scopeLocation = scope->GetLocation();
  650. if (scope->GetMustInstantiate())
  651. {
  652. Assert(scopeLocation == Js::Constants::NoRegister);
  653. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  654. if (scope->GetIsObject())
  655. {
  656. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  657. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  658. }
  659. else
  660. {
  661. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  662. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  663. // TODO: Handle heap enumeration
  664. int scopeSlotCount = scope->GetScopeSlotCount();
  665. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  666. }
  667. }
  668. else
  669. {
  670. // In the direct register access case, there is no block scope emitted but we can still track
  671. // the start and end offset of the block. The location registers for let/const variables will still be
  672. // captured along with this range in InitBlockScopedContent().
  673. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  674. }
  675. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  676. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  677. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  678. ParseNodePtr pnodeScope;
  679. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  680. {
  681. switch (pnodeScope->nop)
  682. {
  683. case knopFncDecl:
  684. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  685. {
  686. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  687. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  688. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  689. // So we'll supply a temp that we allocate and release here.
  690. if (frameDisplayLoc == Js::Constants::NoRegister)
  691. {
  692. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  693. {
  694. frameDisplayLoc = funcInfo->frameDisplayRegister;
  695. }
  696. else
  697. {
  698. frameDisplayLoc = funcInfo->GetEnvRegister();
  699. }
  700. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  701. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  702. }
  703. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  704. }
  705. // If this is the global eval block scope, the function is actually assigned to the global
  706. // so we don't need to keep the registers.
  707. if (isGlobalEvalBlockScope)
  708. {
  709. funcInfo->ReleaseLoc(pnodeScope);
  710. pnodeScope->location = Js::Constants::NoRegister;
  711. }
  712. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  713. break;
  714. case knopBlock:
  715. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  716. break;
  717. case knopCatch:
  718. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  719. break;
  720. case knopWith:
  721. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  722. break;
  723. }
  724. }
  725. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  726. {
  727. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  728. }
  729. }
  730. else
  731. {
  732. Scope *scope = pnodeBlock->scope;
  733. if (scope)
  734. {
  735. if (scope->GetMustInstantiate())
  736. {
  737. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  738. }
  739. else
  740. {
  741. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  742. }
  743. }
  744. else
  745. {
  746. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  747. }
  748. }
  749. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  750. }
  751. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  752. {
  753. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  754. {
  755. Scope *scope = pnodeBlock->scope;
  756. Assert(scope);
  757. Assert(scope == byteCodeGenerator->GetCurrentScope());
  758. byteCodeGenerator->PopScope();
  759. }
  760. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  761. }
  762. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  763. {
  764. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  765. {
  766. // Only let variables have observable behavior when there are per iteration
  767. // bindings. const variables do not since they are immutable. Therefore,
  768. // (and the spec agrees), only create new scope clones if the loop variable
  769. // is a let declaration.
  770. bool isConst = false;
  771. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  772. // Exploit the fact that a for loop sxBlock can only have let and const
  773. // declarations, and can only have one or the other, regardless of how
  774. // many syms there might be. Thus only check the first sym.
  775. isConst = sym->GetDecl()->nop == knopConstDecl;
  776. return true;
  777. });
  778. if (!isConst)
  779. {
  780. Scope *scope = pnodeBlock->scope;
  781. Assert(scope == byteCodeGenerator->GetCurrentScope());
  782. if (scope->GetMustInstantiate())
  783. {
  784. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  785. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  786. }
  787. }
  788. }
  789. }
  790. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  791. {
  792. Assert(pnodeBlock->nop == knopBlock);
  793. ParseNode *pnode = pnodeBlock->pnodeStmt;
  794. if (pnode == nullptr)
  795. {
  796. return;
  797. }
  798. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  799. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  800. while (pnode->nop == knopList)
  801. {
  802. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  803. if (stmt == pnodeLastValStmt)
  804. {
  805. // This is the last guaranteed return value, so any potential return values have to be
  806. // copied to the return register from this point forward.
  807. pnodeLastValStmt = nullptr;
  808. }
  809. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  810. pnode = pnode->AsParseNodeBin()->pnode2;
  811. }
  812. if (pnode == pnodeLastValStmt)
  813. {
  814. pnodeLastValStmt = nullptr;
  815. }
  816. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  817. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  818. }
  819. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  820. {
  821. if (emitFunc->IsTmpReg(pnode->location))
  822. {
  823. pnode->location = Js::Constants::NoRegister;
  824. }
  825. }
  826. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  827. {
  828. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  829. {
  830. // Function declarations (not function-declaration RHS's) are already fully processed.
  831. // Skip them here so the temp registers don't get messed up.
  832. return;
  833. }
  834. if (stmt->nop == knopName || stmt->nop == knopDot)
  835. {
  836. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  837. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  838. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  839. StartStatement(stmt);
  840. Writer()->Empty(Js::OpCode::Nop);
  841. EndStatement(stmt);
  842. }
  843. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
  844. if (funcInfo->IsTmpReg(stmt->location))
  845. {
  846. if (!stmt->isUsed && !fReturnValue)
  847. {
  848. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  849. }
  850. funcInfo->ReleaseLoc(stmt);
  851. }
  852. }
  853. // ByteCodeGenerator::DefineFunctions
  854. //
  855. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  856. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  857. // to make sure that sources of the stores have been defined.
  858. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  859. {
  860. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  861. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  862. if (funcInfoParent->GetHasCachedScope())
  863. {
  864. this->DefineCachedFunctions(funcInfoParent);
  865. }
  866. else
  867. {
  868. this->DefineUncachedFunctions(funcInfoParent);
  869. }
  870. }
  871. // Iterate over all child functions in a function's parameter and body scopes.
  872. template<typename Fn>
  873. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  874. {
  875. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  876. {
  877. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  878. {
  879. switch (pnode->nop)
  880. {
  881. case knopFncDecl:
  882. fn(pnode);
  883. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  884. break;
  885. case knopBlock:
  886. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  887. break;
  888. case knopCatch:
  889. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  890. break;
  891. case knopWith:
  892. pnode = pnode->AsParseNodeWith()->pnodeNext;
  893. break;
  894. default:
  895. AssertMsg(false, "Unexpected opcode in tree of scopes");
  896. return;
  897. }
  898. }
  899. };
  900. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  901. }
  902. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  903. {
  904. ParseNode *pnodeParent = funcInfoParent->root;
  905. uint slotCount = 0;
  906. auto countFncSlots = [&](ParseNode *pnodeFnc)
  907. {
  908. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  909. {
  910. slotCount++;
  911. }
  912. };
  913. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  914. if (slotCount == 0)
  915. {
  916. return;
  917. }
  918. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  919. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  920. if (extraBytesActual > INT_MAX)
  921. {
  922. Js::Throw::OutOfMemory();
  923. }
  924. int extraBytes = (int)extraBytesActual;
  925. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  926. // slotCount is guaranteed to be non-zero here.
  927. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  928. slotCount = 0;
  929. auto fillEntries = [&](ParseNode *pnodeFnc)
  930. {
  931. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  932. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration()))
  933. {
  934. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  935. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  936. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  937. entry->scopeSlot = sym->GetScopeSlot();
  938. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  939. slotCount++;
  940. }
  941. };
  942. MapContainerScopeFunctions(pnodeParent, fillEntries);
  943. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  944. info,
  945. sizeof(Js::FuncInfoArray) + extraBytes,
  946. sizeof(Js::FuncInfoArray) + extraBytes);
  947. slotCount = 0;
  948. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  949. {
  950. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  951. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  952. {
  953. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  954. // Only happens if the sym is null (e.g., function x.y(){}).
  955. if (sym == nullptr)
  956. {
  957. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  958. }
  959. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  960. {
  961. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  962. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  963. }
  964. // The "x = function() {...}" case is being generated on the fly, during emission,
  965. // so the caller expects to be able to release this register.
  966. funcInfoParent->ReleaseLoc(pnodeFnc);
  967. pnodeFnc->location = Js::Constants::NoRegister;
  968. slotCount++;
  969. }
  970. };
  971. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  972. AdeletePlus(alloc, extraBytes, info);
  973. }
  974. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  975. {
  976. ParseNode *pnodeParent = funcInfoParent->root;
  977. auto defineCheck = [&](ParseNode *pnodeFnc)
  978. {
  979. Assert(pnodeFnc->nop == knopFncDecl);
  980. //
  981. // Don't define the function upfront in following cases
  982. // 1. x = function() {...};
  983. // Don't define the function for all modes.
  984. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  985. // rather than the scope entry to save a register (and possibly save the whole definition).
  986. //
  987. // 2. x = function f() {...};
  988. // f is not visible in the enclosing scope.
  989. // Such function expressions should be emitted only at the assignment point, as can be used only
  990. // after the assignment. Might save register.
  991. //
  992. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  993. {
  994. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  995. // The "x = function() {...}" case is being generated on the fly, during emission,
  996. // so the caller expects to be able to release this register.
  997. funcInfoParent->ReleaseLoc(pnodeFnc);
  998. pnodeFnc->location = Js::Constants::NoRegister;
  999. }
  1000. };
  1001. MapContainerScopeFunctions(pnodeParent, defineCheck);
  1002. }
  1003. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  1004. {
  1005. // Assign the location holding the func object reference to the given name.
  1006. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  1007. Symbol *sym = pnodeFnc->pnodeName->sym;
  1008. if (sym != nullptr && !sym->GetIsFuncExpr())
  1009. {
  1010. if (sym->GetIsModuleExportStorage())
  1011. {
  1012. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1013. }
  1014. else if (sym->GetIsGlobal())
  1015. {
  1016. Js::PropertyId propertyId = sym->GetPosition();
  1017. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1018. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1019. {
  1020. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1026. {
  1027. if (!sym->GetHasNonCommittedReference() ||
  1028. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1029. {
  1030. // No point in trying to optimize if there are no references before we have to commit to slot.
  1031. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1032. sym->SetIsCommittedToSlot();
  1033. }
  1034. }
  1035. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1036. {
  1037. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1038. }
  1039. else
  1040. {
  1041. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1042. }
  1043. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1044. if (fncScopeSym)
  1045. {
  1046. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1047. {
  1048. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1049. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1050. }
  1051. else
  1052. {
  1053. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1054. }
  1055. }
  1056. }
  1057. }
  1058. }
  1059. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1060. {
  1061. Assert(pnodeFnc->nop == knopFncDecl);
  1062. funcInfoParent->AcquireLoc(pnodeFnc);
  1063. if (regEnv == Js::Constants::NoRegister)
  1064. {
  1065. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1066. if (frameDisplayTemp != Js::Constants::NoRegister)
  1067. {
  1068. // We allocated a temp to hold a local frame display value. Use that.
  1069. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1070. regEnv = frameDisplayTemp;
  1071. }
  1072. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1073. {
  1074. // This function has built a frame display, so pass it down.
  1075. regEnv = funcInfoParent->frameDisplayRegister;
  1076. }
  1077. else
  1078. {
  1079. // This function has no captured locals but inherits a closure environment, so pass it down.
  1080. regEnv = funcInfoParent->GetEnvRegister();
  1081. }
  1082. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1083. }
  1084. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1085. // "We need a closure for the nested function");
  1086. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1087. // If we are in a parameter scope and it is not merged with body scope then we have to create the child function as an inner function
  1088. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1089. {
  1090. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1091. }
  1092. else
  1093. {
  1094. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1095. }
  1096. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1097. {
  1098. // A function declared at global scope in eval is untrackable,
  1099. // so make sure the caller's cached scope is invalidated.
  1100. this->funcEscapes = true;
  1101. }
  1102. else
  1103. {
  1104. if (pnodeFnc->IsDeclaration())
  1105. {
  1106. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1107. if (funcSymbol)
  1108. {
  1109. // In the case where a let/const declaration is the same symbol name
  1110. // as the function declaration (shadowing case), the let/const var and
  1111. // the function declaration symbol are the same and share the same flags
  1112. // (particularly, sym->GetIsBlockVar() for this code path).
  1113. //
  1114. // For example:
  1115. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1116. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1117. //
  1118. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1119. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1120. //
  1121. // In order to tell if the function is actually part
  1122. // of a block scope, we compare against the function scope here.
  1123. // Note that having a function with the same name as a let/const declaration
  1124. // is a redeclaration error, but we're pushing the fix for this out since it's
  1125. // a bit involved.
  1126. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1127. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1128. // Track all vars/lets/consts register slot function declarations.
  1129. if (ShouldTrackDebuggerMetadata()
  1130. // If this is a let binding function declaration at global level, we want to
  1131. // be sure to track the register location as well.
  1132. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1133. {
  1134. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1135. {
  1136. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1137. }
  1138. }
  1139. if (isFunctionDeclarationInBlock)
  1140. {
  1141. // We only track inner let bindings for the debugger side.
  1142. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. if (pnodeFnc->IsDefaultModuleExport())
  1148. {
  1149. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1150. }
  1151. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1152. {
  1153. return regEnv;
  1154. }
  1155. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1156. return regEnv;
  1157. }
  1158. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1159. {
  1160. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1161. // by an existing initialization.
  1162. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1163. ParseNode *pnode;
  1164. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1165. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1166. // Just assign one on the fly and re-use it for all initializations.
  1167. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1168. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1169. {
  1170. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1171. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1172. {
  1173. if (sym->IsSpecialSymbol())
  1174. {
  1175. // Special symbols have already had their initial values stored into their registers.
  1176. // In default-argument case we've stored those values into their slot locations, as well.
  1177. // We must do that because a default parameter may access a special symbol through a scope slot.
  1178. // In the non-default-argument case, though, we didn't yet store the values into the
  1179. // slots so let's do that now.
  1180. if (!funcInfo->root->HasNonSimpleParameterList())
  1181. {
  1182. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1183. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1184. {
  1185. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1186. }
  1187. }
  1188. continue;
  1189. }
  1190. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1191. {
  1192. // The init node was bound to the catch object, because it's inside a catch and has the
  1193. // same name as the catch object. But we want to define a user var at function scope,
  1194. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1195. // This also applies to a var declaration in the same scope as a let declaration.
  1196. #if DBG
  1197. if (sym->IsArguments())
  1198. {
  1199. // There is a block scoped var named arguments
  1200. Assert(!funcInfo->GetHasArguments());
  1201. continue;
  1202. }
  1203. else if (!sym->GetIsCatch())
  1204. {
  1205. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1206. Assert(funcInfo->bodyScope != sym->GetScope());
  1207. }
  1208. #endif
  1209. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1210. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1211. }
  1212. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1213. {
  1214. if (fGlobal)
  1215. {
  1216. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1217. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1218. // But we first need to make sure we're not trashing built-ins.
  1219. if (this->flags & fscrEval)
  1220. {
  1221. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1222. {
  1223. // Check/Init the property of the frame object
  1224. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1225. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1226. }
  1227. else
  1228. {
  1229. // The check and the init involve the first element in the scope chain.
  1230. this->m_writer.ElementScopedU(
  1231. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1232. }
  1233. }
  1234. else
  1235. {
  1236. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1237. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1238. }
  1239. }
  1240. else if (!sym->IsArguments())
  1241. {
  1242. if (sym->NeedsSlotAlloc(this, funcInfo))
  1243. {
  1244. if (!sym->GetHasNonCommittedReference() ||
  1245. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1246. {
  1247. // No point in trying to optimize if there are no references before we have to commit to slot.
  1248. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1249. sym->SetIsCommittedToSlot();
  1250. }
  1251. }
  1252. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1253. // is delayed) or a property of an object.
  1254. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1255. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1256. {
  1257. Js::RegSlot reg = sym->GetLocation();
  1258. if (reg == Js::Constants::NoRegister)
  1259. {
  1260. Assert(sym->IsInSlot(this, funcInfo));
  1261. reg = funcInfo->AcquireTmpRegister();
  1262. }
  1263. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1264. this->EmitLocalPropInit(reg, sym, funcInfo);
  1265. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1266. {
  1267. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1268. }
  1269. funcInfo->ReleaseTmpRegister(reg);
  1270. }
  1271. }
  1272. else if (ShouldTrackDebuggerMetadata())
  1273. {
  1274. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1275. {
  1276. Js::RegSlot reg = sym->GetLocation();
  1277. if (reg != Js::Constants::NoRegister)
  1278. {
  1279. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1280. }
  1281. }
  1282. }
  1283. sym->SetHasInit(TRUE);
  1284. }
  1285. }
  1286. }
  1287. if (tmpReg != Js::Constants::NoRegister)
  1288. {
  1289. funcInfo->ReleaseTmpRegister(tmpReg);
  1290. }
  1291. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1292. {
  1293. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1294. }
  1295. }
  1296. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1297. {
  1298. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1299. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1300. // This protects us from, for instance, trying to restore garbage on bailout.
  1301. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1302. // garbage on exit from jitted loop bodies.
  1303. while (pnode)
  1304. {
  1305. switch (pnode->nop)
  1306. {
  1307. case knopFncDecl:
  1308. {
  1309. // If this is a block-scoped function, initialize it.
  1310. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1311. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1312. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1313. {
  1314. Symbol *sym = pnodeName->sym;
  1315. Assert(sym);
  1316. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1317. sym->GetScope()->IsBlockScope(funcInfo) &&
  1318. sym->GetScope()->GetFunc() == funcInfo)
  1319. {
  1320. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1321. }
  1322. }
  1323. // No need to recurse to the nested scopes, as they belong to a nested function.
  1324. pnode = pnodeFnc->pnodeNext;
  1325. break;
  1326. }
  1327. case knopBlock:
  1328. {
  1329. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1330. Scope *scope = pnodeBlock->scope;
  1331. if (scope)
  1332. {
  1333. if (scope->IsBlockScope(funcInfo))
  1334. {
  1335. Js::RegSlot scopeLoc = scope->GetLocation();
  1336. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1337. {
  1338. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1339. }
  1340. }
  1341. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1342. {
  1343. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1344. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1345. {
  1346. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1347. }
  1348. };
  1349. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1350. }
  1351. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1352. pnode = pnodeBlock->pnodeNext;
  1353. break;
  1354. }
  1355. case knopCatch:
  1356. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1357. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1358. break;
  1359. case knopWith:
  1360. {
  1361. Js::RegSlot withLoc = pnode->location;
  1362. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1363. "We should put with objects at known stack locations in debug mode");
  1364. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1365. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1366. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1367. break;
  1368. }
  1369. default:
  1370. Assert(false);
  1371. return;
  1372. }
  1373. }
  1374. }
  1375. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1376. {
  1377. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1378. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1379. {
  1380. return;
  1381. }
  1382. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1383. uint slotCount = currentScope->GetScopeSlotCount();
  1384. uint cachedFuncCount = 0;
  1385. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1386. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1387. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1388. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1389. // Create and fill the array of local property ID's.
  1390. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1391. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1392. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1393. ParseNode *pnode;
  1394. Symbol *sym;
  1395. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1396. {
  1397. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1398. }
  1399. if (funcInfo->GetHasArguments())
  1400. {
  1401. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1402. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1403. Js::PropertyId slot = 0;
  1404. auto initArg = [&](ParseNode *pnode)
  1405. {
  1406. if (pnode->IsVarLetOrConst())
  1407. {
  1408. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1409. Assert(sym);
  1410. if (sym->GetScopeSlot() == slot)
  1411. {
  1412. // This is the last appearance of the formal, so record the ID.
  1413. Symbol::SaveToPropIdArray(sym, propIds, this);
  1414. }
  1415. else
  1416. {
  1417. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1418. // since this slot can't be accessed by name.
  1419. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1420. propIds->elements[slot] = Js::Constants::NoProperty;
  1421. }
  1422. }
  1423. else
  1424. {
  1425. // This is for patterns
  1426. propIds->elements[slot] = Js::Constants::NoProperty;
  1427. }
  1428. slot++;
  1429. };
  1430. MapFormalsWithoutRest(pnodeFnc, initArg);
  1431. // If the rest is in the slot - we need to keep that slot.
  1432. if (pnodeFnc->pnodeRest != nullptr && pnodeFnc->pnodeRest->sym->IsInSlot(this, funcInfo))
  1433. {
  1434. Symbol::SaveToPropIdArray(pnodeFnc->pnodeRest->sym, propIds, this);
  1435. }
  1436. }
  1437. else
  1438. {
  1439. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1440. {
  1441. if (pnode->IsVarLetOrConst())
  1442. {
  1443. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1444. }
  1445. });
  1446. }
  1447. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1448. {
  1449. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1450. {
  1451. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1452. if (pnodeName != nullptr)
  1453. {
  1454. while (pnodeName->nop == knopList)
  1455. {
  1456. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1457. {
  1458. sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1459. if (sym)
  1460. {
  1461. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1462. }
  1463. }
  1464. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1465. }
  1466. if (pnodeName->nop == knopVarDecl)
  1467. {
  1468. sym = pnodeName->AsParseNodeVar()->sym;
  1469. if (sym)
  1470. {
  1471. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1472. cachedFuncCount++;
  1473. }
  1474. }
  1475. }
  1476. }
  1477. };
  1478. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1479. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1480. {
  1481. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1482. {
  1483. sym = pnode->AsParseNodeVar()->sym;
  1484. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1485. {
  1486. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1487. {
  1488. sym = currentScope->FindLocalSymbol(sym->GetName());
  1489. }
  1490. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1491. }
  1492. }
  1493. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1494. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1495. {
  1496. sym = pnode->AsParseNodeVar()->sym;
  1497. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1498. }
  1499. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1500. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1501. {
  1502. sym = pnode->AsParseNodeVar()->sym;
  1503. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1504. }
  1505. }
  1506. else
  1507. {
  1508. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1509. }
  1510. // Write the first func slot and first var slot into the auxiliary data
  1511. Js::PropertyId *slots = propIds->elements + slotCount;
  1512. slots[0] = cachedFuncCount;
  1513. slots[1] = firstFuncSlot;
  1514. slots[2] = firstVarSlot;
  1515. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1516. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1517. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1518. }
  1519. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1520. {
  1521. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1522. {
  1523. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1524. }
  1525. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1526. {
  1527. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1528. byteCodeFunction->SetHasScopeObject(true);
  1529. }
  1530. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1531. {
  1532. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1533. }
  1534. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1535. {
  1536. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1537. }
  1538. }
  1539. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1540. {
  1541. if (byteCodeFunction->IsCoroutine())
  1542. {
  1543. // EmitYield uses 'false' to create the IteratorResult object
  1544. funcInfo->AssignFalseConstRegister();
  1545. }
  1546. if (funcInfo->NeedEnvRegister())
  1547. {
  1548. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1549. funcInfo->AssignEnvRegister(constReg);
  1550. }
  1551. // Set the function body's constant count before emitting anything so that the byte code writer
  1552. // can distinguish constants from variables.
  1553. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1554. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1555. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1556. {
  1557. // Give permanent registers to the inner scopes in debug mode.
  1558. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1559. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1560. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1561. // EmitOneFunction.
  1562. uint innerScopeCount = funcInfo->InnerScopeCount();
  1563. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1564. if (innerScopeCount)
  1565. {
  1566. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1567. for (uint i = 1; i < innerScopeCount; i++)
  1568. {
  1569. funcInfo->NextVarRegister();
  1570. }
  1571. }
  1572. }
  1573. // NOTE: The FB expects the yield reg to be the final non-temp.
  1574. if (byteCodeFunction->IsCoroutine())
  1575. {
  1576. funcInfo->AssignYieldRegister();
  1577. }
  1578. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1579. funcInfo->SetFirstTmpReg(firstTmpReg);
  1580. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1581. }
  1582. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1583. {
  1584. // Record slots info for ScopeSlots/ScopeObject.
  1585. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1586. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1587. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1588. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1589. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1590. {
  1591. return;
  1592. }
  1593. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1594. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1595. {
  1596. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1597. }
  1598. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1599. if (scopeSlotCount)
  1600. {
  1601. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1602. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1603. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1604. "The slot array size is different between debug and non-debug mode");
  1605. #if DEBUG
  1606. for (UINT i = 0; i < scopeSlotCount; i++)
  1607. {
  1608. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1609. }
  1610. #endif
  1611. auto setPropertyIdForScopeSlotArray =
  1612. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1613. (Js::PropertyId slot, Js::PropertyId propId)
  1614. {
  1615. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1616. {
  1617. Js::Throw::FatalInternalError();
  1618. }
  1619. propertyIdsForScopeSlotArray[slot] = propId;
  1620. };
  1621. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1622. {
  1623. if (sym->NeedsSlotAlloc(this, funcInfo))
  1624. {
  1625. // All properties should get correct propertyId here.
  1626. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1627. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1628. }
  1629. };
  1630. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1631. #if DEBUG
  1632. for (UINT i = 0; i < scopeSlotCount; i++)
  1633. {
  1634. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1635. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1636. }
  1637. #endif
  1638. }
  1639. }
  1640. // temporarily load all constants and special registers in a single block
  1641. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1642. {
  1643. Symbol *sym;
  1644. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1645. byteCodeFunction->CreateConstantTable();
  1646. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1647. {
  1648. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1649. }
  1650. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1651. {
  1652. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1653. }
  1654. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1655. {
  1656. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1657. }
  1658. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1659. {
  1660. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1661. }
  1662. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1663. {
  1664. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1665. if (!funcInfo->GetApplyEnclosesArgs())
  1666. {
  1667. this->EmitScopeObjectInit(funcInfo);
  1668. }
  1669. #if DBG
  1670. uint count = 0;
  1671. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1672. {
  1673. if (sym->NeedsSlotAlloc(this, funcInfo))
  1674. {
  1675. // All properties should get correct propertyId here.
  1676. count++;
  1677. }
  1678. });
  1679. if (funcInfo->GetParamScope() != nullptr)
  1680. {
  1681. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1682. {
  1683. if (sym->NeedsSlotAlloc(this, funcInfo))
  1684. {
  1685. // All properties should get correct propertyId here.
  1686. count++;
  1687. }
  1688. });
  1689. }
  1690. // A reparse should result in the same size of the activation object.
  1691. // Exclude functions which were created from the ByteCodeCache.
  1692. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1693. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1694. "The activation object size is different between debug and non-debug mode");
  1695. byteCodeFunction->scopeObjectSize = count;
  1696. #endif
  1697. }
  1698. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1699. {
  1700. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1701. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1702. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1703. {
  1704. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1705. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1706. }
  1707. }
  1708. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1709. {
  1710. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1711. byteCodeFunction->SetEnvDepth((uint16)-1);
  1712. }
  1713. bool thisLoadedFromParams = false;
  1714. if (funcInfo->NeedEnvRegister())
  1715. {
  1716. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1717. if (funcInfo->GetIsTopLevelEventHandler())
  1718. {
  1719. if (funcInfo->GetThisSymbol())
  1720. {
  1721. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1722. }
  1723. // The environment is the namespace hierarchy starting with "this".
  1724. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1725. thisLoadedFromParams = true;
  1726. this->InvalidateCachedOuterScopes(funcInfo);
  1727. }
  1728. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1729. {
  1730. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1731. if (funcInfo->GetIsStrictMode())
  1732. {
  1733. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1734. }
  1735. else
  1736. {
  1737. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1738. }
  1739. }
  1740. else
  1741. {
  1742. // environment may be required to load "this"
  1743. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1744. this->InvalidateCachedOuterScopes(funcInfo);
  1745. }
  1746. }
  1747. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1748. {
  1749. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1750. }
  1751. this->RecordAllIntConstants(funcInfo);
  1752. this->RecordAllStrConstants(funcInfo);
  1753. this->RecordAllBigIntConstants(funcInfo);
  1754. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1755. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1756. {
  1757. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1758. });
  1759. // WARNING !!!
  1760. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1761. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1762. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1763. if (funcInfo->GetHasArguments())
  1764. {
  1765. sym = funcInfo->GetArgumentsSymbol();
  1766. Assert(sym);
  1767. Assert(funcInfo->GetHasHeapArguments());
  1768. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1769. {
  1770. this->LoadHeapArguments(funcInfo);
  1771. }
  1772. }
  1773. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1774. {
  1775. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1776. if (count != 0)
  1777. {
  1778. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1779. GetFormalArgsArray(this, funcInfo, propIds);
  1780. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1781. }
  1782. }
  1783. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1784. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1785. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1786. if (funcInfo->IsClassConstructor())
  1787. {
  1788. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1789. }
  1790. // new.target may be used to construct the 'this' register so make sure to load it first
  1791. if (funcInfo->GetNewTargetSymbol())
  1792. {
  1793. this->LoadNewTargetObject(funcInfo);
  1794. }
  1795. if (funcInfo->GetThisSymbol())
  1796. {
  1797. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1798. }
  1799. else if (ShouldLoadConstThis(funcInfo))
  1800. {
  1801. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1802. }
  1803. if (funcInfo->GetSuperSymbol())
  1804. {
  1805. this->LoadSuperObject(funcInfo);
  1806. }
  1807. if (funcInfo->GetSuperConstructorSymbol())
  1808. {
  1809. this->LoadSuperConstructorObject(funcInfo);
  1810. }
  1811. //
  1812. // If the function is a function expression with a name,
  1813. // load the function object at runtime to its activation object.
  1814. //
  1815. sym = funcInfo->root->GetFuncSymbol();
  1816. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1817. if (funcExprWithName)
  1818. {
  1819. if (funcInfo->GetFuncExprNameReference() ||
  1820. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1821. {
  1822. //
  1823. // x = function f(...) { ... }
  1824. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1825. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1826. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1827. // scope's register namespace. So use a tmp register.
  1828. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1829. // from it's register namespace, which LdFuncExpr can use.
  1830. //
  1831. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1832. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1833. if (sym->IsInSlot(this, funcInfo))
  1834. {
  1835. Js::RegSlot scopeLocation;
  1836. AnalysisAssert(funcInfo->funcExprScope);
  1837. if (funcInfo->funcExprScope->GetIsObject())
  1838. {
  1839. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1840. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1841. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1842. }
  1843. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1844. {
  1845. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1846. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1847. }
  1848. else
  1849. {
  1850. Assert(sym->HasScopeSlot());
  1851. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1852. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1853. }
  1854. }
  1855. else if (ShouldTrackDebuggerMetadata())
  1856. {
  1857. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1863. {
  1864. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1865. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1866. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1867. uint32 envIndex = 0;
  1868. while (scope && scope->GetFunc() == funcInfo)
  1869. {
  1870. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1871. scope = scope->GetEnclosingScope();
  1872. }
  1873. for (; scope; scope = scope->GetEnclosingScope())
  1874. {
  1875. FuncInfo *func = scope->GetFunc();
  1876. if (scope == func->GetBodyScope())
  1877. {
  1878. if (func->Escapes() && func->GetHasCachedScope())
  1879. {
  1880. AssertOrFailFast(scope->GetIsObject());
  1881. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1882. }
  1883. }
  1884. if (scope->GetMustInstantiate())
  1885. {
  1886. envIndex++;
  1887. }
  1888. }
  1889. }
  1890. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1891. {
  1892. Symbol* thisSym = funcInfo->GetThisSymbol();
  1893. Assert(thisSym);
  1894. Assert(!funcInfo->IsLambda());
  1895. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1896. {
  1897. // Derived class constructors initialize 'this' to be Undecl
  1898. // - we'll check this value during a super call and during 'this' access
  1899. //
  1900. // Base class constructors initialize 'this' to a new object using new.target
  1901. if (funcInfo->IsBaseClassConstructor())
  1902. {
  1903. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1904. Assert(newTargetSym);
  1905. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1906. }
  1907. else
  1908. {
  1909. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1910. }
  1911. }
  1912. else if (!funcInfo->IsGlobalFunction())
  1913. {
  1914. //
  1915. // thisLoadedFromParams would be true for the event Handler case,
  1916. // "this" would have been loaded from parameters to put in the environment
  1917. //
  1918. if (!thisLoadedFromParams)
  1919. {
  1920. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1921. m_writer.ArgIn0(tmpReg);
  1922. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1923. funcInfo->ReleaseTmpRegister(tmpReg);
  1924. }
  1925. else
  1926. {
  1927. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1928. }
  1929. }
  1930. else
  1931. {
  1932. Assert(funcInfo->IsGlobalFunction());
  1933. Js::RegSlot root = funcInfo->nullConstantRegister;
  1934. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1935. }
  1936. }
  1937. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1938. {
  1939. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1940. Assert(newTargetSym);
  1941. if (funcInfo->IsClassConstructor())
  1942. {
  1943. Assert(!funcInfo->IsLambda());
  1944. m_writer.ArgIn0(newTargetSym->GetLocation());
  1945. }
  1946. else if (funcInfo->IsGlobalFunction())
  1947. {
  1948. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1949. }
  1950. else
  1951. {
  1952. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1953. }
  1954. }
  1955. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1956. {
  1957. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1958. Assert(superConstructorSym);
  1959. Assert(!funcInfo->IsLambda());
  1960. if (funcInfo->IsDerivedClassConstructor())
  1961. {
  1962. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1963. }
  1964. else
  1965. {
  1966. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1967. }
  1968. }
  1969. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1970. {
  1971. Symbol* superSym = funcInfo->GetSuperSymbol();
  1972. Assert(superSym);
  1973. Assert(!funcInfo->IsLambda());
  1974. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1975. }
  1976. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue)
  1977. {
  1978. FuncInfo* nonLambdaFunc = funcInfo;
  1979. bool isResultUsed = pnodeSuperCall->isUsed;
  1980. if (funcInfo->IsLambda())
  1981. {
  1982. nonLambdaFunc = this->FindEnclosingNonLambda();
  1983. }
  1984. if (nonLambdaFunc->IsBaseClassConstructor())
  1985. {
  1986. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  1987. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  1988. return;
  1989. }
  1990. pnodeSuperCall->isUsed = true;
  1991. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  1992. // and the result of the super() expression itself
  1993. funcInfo->AcquireLoc(pnodeSuperCall);
  1994. // We need to emit 'this' directly so we can skip throwing a reference error if 'this' is currently undecl (we want to get undecl if 'this' is undecl)
  1995. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  1996. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  1997. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  1998. Assert(pnodeSuperCall->isSuperCall);
  1999. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  2000. //
  2001. // if (super is class constructor) {
  2002. // _this = new.target;
  2003. // } else {
  2004. // _this = NewScObjFull(new.target);
  2005. // }
  2006. //
  2007. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2008. // if (temp is object) {
  2009. // _this = temp;
  2010. // }
  2011. //
  2012. // if (UndeclBlockVar === this) {
  2013. // this = _this;
  2014. // } else {
  2015. // throw ReferenceError;
  2016. // }
  2017. //
  2018. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2019. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2020. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2021. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2022. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2023. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2024. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2025. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2026. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2027. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2028. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2029. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2030. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2031. this->Writer()->MarkLabel(makeCallLabel);
  2032. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2033. // We have to use another temp for the this value before assigning to this register.
  2034. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2035. // Ex:
  2036. // _this = new.target;
  2037. // temp = super.call(_this);
  2038. // if (temp is object) {
  2039. // _this = temp; // creates a new sym for _this as it was previously used
  2040. // }
  2041. // this = _this; // tries to loads a value from the old sym (which is dead)
  2042. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2043. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2044. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2045. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2046. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnodeSuperCall->location);
  2047. this->Writer()->MarkLabel(doneLabel);
  2048. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2049. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2050. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2051. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2052. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2053. this->Writer()->MarkLabel(skipLabel);
  2054. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2055. if (isResultUsed)
  2056. {
  2057. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2058. }
  2059. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2060. this->Writer()->Reg2(Js::OpCode::StrictLdThis, pnodeSuperCall->pnodeThis->location, valueForThis);
  2061. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2062. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2063. funcInfo->ReleaseTmpRegister(valueForThis);
  2064. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2065. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2066. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2067. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2068. }
  2069. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2070. {
  2071. Symbol* thisSym = funcInfo->GetThisSymbol();
  2072. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2073. {
  2074. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2075. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2076. }
  2077. }
  2078. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2079. {
  2080. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2081. {
  2082. m_writer.Reg2(Js::OpCode::StrictLdThis, lhsLocation, fromRegister);
  2083. }
  2084. else
  2085. {
  2086. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2087. }
  2088. }
  2089. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2090. {
  2091. if (pnodeFormal->IsVarLetOrConst())
  2092. {
  2093. // Get the param from its argument position into its assigned register.
  2094. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2095. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2096. if (formal->GetLocation() + 1 == pos)
  2097. {
  2098. // Transfer to the frame object, etc., if necessary.
  2099. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2100. }
  2101. }
  2102. }
  2103. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2104. {
  2105. if (ShouldTrackDebuggerMetadata())
  2106. {
  2107. // Add formals to the debugger propertyidcontainer for reg slots
  2108. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2109. {
  2110. if (pnodeFormal->IsVarLetOrConst())
  2111. {
  2112. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2113. if (!formal->IsInSlot(this, funcInfo))
  2114. {
  2115. Assert(!formal->GetHasInit());
  2116. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2117. }
  2118. }
  2119. };
  2120. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2121. }
  2122. // Transfer formal parameters to their home locations on the local frame.
  2123. if (funcInfo->GetHasArguments())
  2124. {
  2125. if (funcInfo->root->pnodeRest != nullptr)
  2126. {
  2127. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2128. EmitLoadFormalIntoRegister(funcInfo->root->pnodeRest, funcInfo->root->pnodeRest->sym->GetLocation() + 1, funcInfo);
  2129. }
  2130. // The arguments object creation helper does this work for us.
  2131. return;
  2132. }
  2133. Js::ArgSlot pos = 1;
  2134. auto loadFormal = [&](ParseNode *pnodeFormal)
  2135. {
  2136. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2137. pos++;
  2138. };
  2139. MapFormals(funcInfo->root, loadFormal);
  2140. }
  2141. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2142. {
  2143. funcInfo->singleExit = m_writer.DefineLabel();
  2144. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2145. while (iter.Next())
  2146. {
  2147. ParseNodeStmt * node = iter.Data();
  2148. node->breakLabel = m_writer.DefineLabel();
  2149. node->continueLabel = m_writer.DefineLabel();
  2150. node->emitLabels = true;
  2151. }
  2152. }
  2153. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2154. {
  2155. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2156. // return value.
  2157. ParseNode *pnode = funcInfo->root->pnodeBody;
  2158. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2159. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2160. {
  2161. // We're not guaranteed to compute any values, so fix up the return register at the top
  2162. // in case.
  2163. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2164. }
  2165. while (pnode->nop == knopList)
  2166. {
  2167. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2168. if (stmt == pnodeLastVal)
  2169. {
  2170. pnodeLastVal = nullptr;
  2171. }
  2172. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2173. {
  2174. EmitTopLevelStatement(stmt, funcInfo, true);
  2175. }
  2176. else
  2177. {
  2178. // Haven't hit the post-dominating return value yet,
  2179. // so don't bother with the return register.
  2180. EmitTopLevelStatement(stmt, funcInfo, false);
  2181. }
  2182. pnode = pnode->AsParseNodeBin()->pnode2;
  2183. }
  2184. EmitTopLevelStatement(pnode, funcInfo, false);
  2185. }
  2186. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2187. {
  2188. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2189. // get copied to the return register.
  2190. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2191. ParseNode *pnode = pnodeBody;
  2192. while (pnode->nop == knopList)
  2193. {
  2194. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2195. if (stmt->CapturesSyms())
  2196. {
  2197. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2198. SList<Symbol*> *list = map->Item(stmt);
  2199. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2200. {
  2201. if (!sym->GetIsCommittedToSlot())
  2202. {
  2203. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2204. sym->SetIsCommittedToSlot();
  2205. ParseNode *decl = sym->GetDecl();
  2206. Assert(decl);
  2207. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2208. {
  2209. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2210. sym->GetName().GetBuffer());
  2211. Output::Flush();
  2212. }
  2213. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2214. // what is this doing? Why are we assigning sym to itself?
  2215. bool old = sym->GetNeedDeclaration();
  2216. sym->SetNeedDeclaration(false);
  2217. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2218. sym->SetNeedDeclaration(old);
  2219. }
  2220. }
  2221. NEXT_SLIST_ENTRY;
  2222. }
  2223. EmitTopLevelStatement(stmt, funcInfo, false);
  2224. pnode = pnode->AsParseNodeBin()->pnode2;
  2225. }
  2226. Assert(!pnode->CapturesSyms());
  2227. EmitTopLevelStatement(pnode, funcInfo, false);
  2228. }
  2229. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2230. {
  2231. // Indicate that the binding phase is over.
  2232. this->isBinding = false;
  2233. this->trackEnvDepth = true;
  2234. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2235. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2236. // Use the temp allocator in bytecode write temp buffer.
  2237. m_writer.InitData(this->alloc, initSize);
  2238. #ifdef LOG_BYTECODE_AST_RATIO
  2239. // log the max Ast size
  2240. Output::Print(_u("Max Ast size: %d"), initSize);
  2241. #endif
  2242. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2243. if (this->parentScopeInfo)
  2244. {
  2245. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2246. // Start emitting with the nested scope (i.e., the deferred function).
  2247. this->EmitScopeList(pnodeProg->pnodeScopes);
  2248. }
  2249. else
  2250. {
  2251. this->EmitScopeList(pnodeProg);
  2252. }
  2253. }
  2254. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2255. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2256. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2257. {
  2258. Js::DebuggerScope *debuggerScope = nullptr;
  2259. auto processArg = [&](ParseNode *pnodeArg) {
  2260. if (pnodeArg->IsVarLetOrConst())
  2261. {
  2262. if (debuggerScope == nullptr)
  2263. {
  2264. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2265. debuggerScope->SetBegin(beginOffset);
  2266. }
  2267. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2268. }
  2269. };
  2270. MapFormals(pnodeFnc, processArg);
  2271. MapFormalsFromPattern(pnodeFnc, processArg);
  2272. if (debuggerScope != nullptr)
  2273. {
  2274. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2275. {
  2276. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2277. }
  2278. RecordEndScopeObject(pnodeFnc);
  2279. }
  2280. }
  2281. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2282. {
  2283. if (sym)
  2284. {
  2285. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2286. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2287. Js::RegSlot location = sym->GetLocation();
  2288. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2289. {
  2290. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2291. location = funcBody->MapRegSlot(location);
  2292. }
  2293. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2294. }
  2295. }
  2296. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2297. {
  2298. uint beginOffset = m_writer.GetCurrentOffset();
  2299. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2300. {
  2301. if (pnodeArg->nop == knopParamPattern)
  2302. {
  2303. this->StartStatement(pnodeArg);
  2304. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2305. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2306. if (pnode1->IsPattern())
  2307. {
  2308. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2309. }
  2310. else
  2311. {
  2312. Assert(pnode1->nop == knopAsg);
  2313. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2314. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2315. pnodeArg->AsParseNodeParamPattern()->location,
  2316. pnode1->AsParseNodeBin()->pnode2,
  2317. false /*isNonPatternAssignmentTarget*/,
  2318. this,
  2319. funcInfo);
  2320. }
  2321. this->EndStatement(pnodeArg);
  2322. return;
  2323. }
  2324. else if (pnodeArg->IsVarLetOrConst())
  2325. {
  2326. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2327. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2328. {
  2329. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2330. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2331. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2332. return;
  2333. }
  2334. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2335. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2336. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2337. this->StartStatement(pnodeArg);
  2338. // Let us use strict not equal to differentiate between null and undefined
  2339. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2340. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2341. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2342. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2343. {
  2344. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2345. m_writer.Br(endLabel);
  2346. }
  2347. else
  2348. {
  2349. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2350. }
  2351. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2352. m_writer.MarkLabel(noDefaultLabel);
  2353. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2354. {
  2355. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2356. m_writer.MarkLabel(endLabel);
  2357. }
  2358. this->EndStatement(pnodeArg);
  2359. }
  2360. };
  2361. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2362. if (pnodeFnc->IsAsync())
  2363. {
  2364. uint cacheId;
  2365. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2366. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2367. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2368. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2369. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2370. // try
  2371. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2372. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2373. // Rest cannot have a default argument, so we ignore it.
  2374. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2375. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2376. m_writer.Empty(Js::OpCode::Leave);
  2377. m_writer.Br(doneLabel);
  2378. // catch
  2379. m_writer.MarkLabel(catchLabel);
  2380. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2381. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2382. m_writer.Empty(Js::OpCode::Nop);
  2383. // return Promise.reject(error);
  2384. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2385. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2386. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2387. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2388. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2389. m_writer.Empty(Js::OpCode::Leave);
  2390. m_writer.Br(funcInfo->singleExit);
  2391. m_writer.Empty(Js::OpCode::Leave);
  2392. m_writer.MarkLabel(doneLabel);
  2393. this->SetHasTry(true);
  2394. funcInfo->ReleaseTmpRegister(rejectLocation);
  2395. funcInfo->ReleaseTmpRegister(promiseLocation);
  2396. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2397. }
  2398. else
  2399. {
  2400. // Rest cannot have a default argument, so we ignore it.
  2401. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2402. }
  2403. if (m_writer.GetCurrentOffset() > beginOffset)
  2404. {
  2405. PopulateFormalsScope(beginOffset, funcInfo, pnodeFnc);
  2406. }
  2407. }
  2408. void ByteCodeGenerator::EmitOneFunction(ParseNodeFnc *pnodeFnc)
  2409. {
  2410. Assert(pnodeFnc && (pnodeFnc->nop == knopProg || pnodeFnc->nop == knopFncDecl));
  2411. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2412. Assert(funcInfo != nullptr);
  2413. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2414. {
  2415. return;
  2416. }
  2417. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2418. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2419. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2420. funcInfo->root,
  2421. !!(this->flags & fscrEvalCode),
  2422. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2423. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2424. if (pnodeFnc->HasDefaultArguments())
  2425. {
  2426. deferParseFunction->SetReportedInParamsCount(pnodeFnc->firstDefaultArg + 1);
  2427. }
  2428. else
  2429. {
  2430. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2431. }
  2432. // Note: Don't check the actual attributes on the functionInfo here, since CanDefer has been cleared while
  2433. // we're generating byte code.
  2434. if (deferParseFunction->IsDeferred() || funcInfo->canDefer)
  2435. {
  2436. Js::ScopeInfo::SaveEnclosingScopeInfo(this, funcInfo);
  2437. }
  2438. if (funcInfo->root->pnodeBody == nullptr)
  2439. {
  2440. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase) && (this->GetFlags() & fscrCreateParserState) == fscrCreateParserState && deferParseFunction->GetCompileCount() == 0)
  2441. {
  2442. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2443. }
  2444. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2445. return;
  2446. }
  2447. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2448. try
  2449. {
  2450. if (!funcInfo->IsGlobalFunction())
  2451. {
  2452. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2453. // In that case the flag already has the value we want.
  2454. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2455. {
  2456. #if DBG
  2457. byteCodeFunction->SetCanDoStackNestedFunc();
  2458. #endif
  2459. if (funcInfo->root->astSize <= ParseNodeFnc::MaxStackClosureAST)
  2460. {
  2461. byteCodeFunction->SetStackNestedFunc(true);
  2462. }
  2463. }
  2464. }
  2465. if (byteCodeFunction->DoStackNestedFunc())
  2466. {
  2467. uint nestedCount = byteCodeFunction->GetNestedCount();
  2468. for (uint i = 0; i < nestedCount; i++)
  2469. {
  2470. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2471. if (nested->IsFunctionBody())
  2472. {
  2473. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2474. }
  2475. }
  2476. }
  2477. if (byteCodeFunction->GetByteCode() != nullptr)
  2478. {
  2479. // Previously compiled function nested within a re-deferred and re-compiled function.
  2480. return;
  2481. }
  2482. // Bug : 301517
  2483. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2484. // and do operation on 'this' and its property, which may not be defined yet.
  2485. if (funcInfo->root->HasOnlyThisStmts() && !IsInDebugMode())
  2486. {
  2487. byteCodeFunction->SetHasOnlyThisStmts(true);
  2488. }
  2489. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2490. {
  2491. if ((pnodeFnc->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnodeFnc, this))
  2492. {
  2493. bool applyEnclosesArgs = true;
  2494. for (ParseNode* pnodeVar = funcInfo->root->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2495. {
  2496. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2497. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2498. {
  2499. applyEnclosesArgs = false;
  2500. break;
  2501. }
  2502. }
  2503. auto constAndLetCheck = [](ParseNodeBlock *pnodeBlock, bool *applyEnclosesArgs)
  2504. {
  2505. if (*applyEnclosesArgs)
  2506. {
  2507. for (auto lexvar = pnodeBlock->pnodeLexVars; lexvar; lexvar = lexvar->AsParseNodeVar()->pnodeNext)
  2508. {
  2509. Symbol* sym = lexvar->AsParseNodeVar()->sym;
  2510. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2511. {
  2512. *applyEnclosesArgs = false;
  2513. break;
  2514. }
  2515. }
  2516. }
  2517. };
  2518. constAndLetCheck(funcInfo->root->pnodeScopes, &applyEnclosesArgs);
  2519. constAndLetCheck(funcInfo->root->pnodeBodyScope, &applyEnclosesArgs);
  2520. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2521. }
  2522. }
  2523. InitScopeSlotArray(funcInfo);
  2524. FinalizeRegisters(funcInfo, byteCodeFunction);
  2525. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2526. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2527. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2528. // Need to revisit the condition when enabling JitES6Generators.
  2529. uint innerScopeCount = funcInfo->InnerScopeCount();
  2530. if (!this->IsInDebugMode() && !byteCodeFunction->IsCoroutine())
  2531. {
  2532. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2533. if (innerScopeCount)
  2534. {
  2535. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2536. for (uint i = 1; i < innerScopeCount; i++)
  2537. {
  2538. funcInfo->AcquireTmpRegister();
  2539. }
  2540. }
  2541. }
  2542. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2543. alloc,
  2544. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2545. );
  2546. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2547. alloc,
  2548. 10);
  2549. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2550. alloc,
  2551. 10);
  2552. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2553. alloc,
  2554. 10);
  2555. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2556. alloc,
  2557. 10);
  2558. byteCodeFunction->AllocateLiteralRegexArray();
  2559. m_callSiteId = 0;
  2560. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2561. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2562. this->inPrologue = true;
  2563. Scope* paramScope = funcInfo->GetParamScope();
  2564. Scope* bodyScope = funcInfo->GetBodyScope();
  2565. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2566. LoadAllConstants(funcInfo);
  2567. HomeArguments(funcInfo);
  2568. if (!funcInfo->IsBodyAndParamScopeMerged())
  2569. {
  2570. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2571. // Pop the body scope before emitting the default args
  2572. PopScope();
  2573. Assert(this->GetCurrentScope() == paramScope);
  2574. }
  2575. if (funcInfo->root->pnodeRest != nullptr)
  2576. {
  2577. byteCodeFunction->SetHasRestParameter();
  2578. }
  2579. if (funcInfo->IsGlobalFunction())
  2580. {
  2581. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2582. }
  2583. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2584. DefineLabels(funcInfo);
  2585. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2586. // argument expressions reference those special names.
  2587. if (pnodeFnc->HasNonSimpleParameterList())
  2588. {
  2589. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2590. // need to walk over the var list.
  2591. if (funcInfo->IsBodyAndParamScopeMerged())
  2592. {
  2593. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2594. {
  2595. #if DBG
  2596. bool reachedEndOfSpecialSymbols = false;
  2597. #endif
  2598. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2599. if (sym != nullptr && sym->IsSpecialSymbol())
  2600. {
  2601. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2602. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2603. {
  2604. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2605. }
  2606. }
  2607. else
  2608. {
  2609. #if DBG
  2610. reachedEndOfSpecialSymbols = true;
  2611. #else
  2612. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2613. // so we can quit walking at the first non-special one we see.
  2614. break;
  2615. #endif
  2616. }
  2617. #if DBG
  2618. if (reachedEndOfSpecialSymbols)
  2619. {
  2620. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2621. }
  2622. #endif
  2623. }
  2624. }
  2625. else
  2626. {
  2627. paramScope->ForEachSymbol([&](Symbol* sym) {
  2628. if (sym && sym->IsSpecialSymbol())
  2629. {
  2630. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2631. }
  2632. });
  2633. }
  2634. }
  2635. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2636. {
  2637. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2638. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2639. EmitDefaultArgs(funcInfo, pnodeFnc);
  2640. if (!funcInfo->IsBodyAndParamScopeMerged())
  2641. {
  2642. Assert(this->GetCurrentScope() == paramScope);
  2643. // Push the body scope
  2644. PushScope(bodyScope);
  2645. funcInfo->SetCurrentChildScope(bodyScope);
  2646. // Mark the beginning of the body scope so that new scope slots can be created.
  2647. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2648. }
  2649. }
  2650. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2651. // (that is when the function is called). This yield opcode is to mark the begining of the function body.
  2652. // TODO: Inserting a yield should have almost no impact on perf as it is a direct return from the function. But this needs
  2653. // to be verified. Ideally if the function has simple parameter list then we can avoid inserting the opcode and the additional call.
  2654. if (pnodeFnc->IsGenerator())
  2655. {
  2656. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2657. EmitYield(funcInfo->AssignUndefinedConstRegister(), tempReg, this, funcInfo);
  2658. m_writer.Reg1(Js::OpCode::Unused, tempReg);
  2659. funcInfo->ReleaseTmpRegister(tempReg);
  2660. }
  2661. DefineUserVars(funcInfo);
  2662. // Emit all scope-wide function definitions before emitting function bodies
  2663. // so that calls may reference functions they precede lexically.
  2664. // Note, global eval scope is a fake local scope and is handled as if it were
  2665. // a lexical block instead of a true global scope, so do not define the functions
  2666. // here. They will be defined during BeginEmitBlock.
  2667. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2668. {
  2669. // This only handles function declarations, which param scope cannot have any.
  2670. DefineFunctions(funcInfo);
  2671. }
  2672. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2673. {
  2674. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2675. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2676. }
  2677. else
  2678. {
  2679. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2680. }
  2681. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2682. {
  2683. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2684. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2685. }
  2686. // Rest needs to trigger use before declaration until all default args have been processed.
  2687. if (pnodeFnc->pnodeRest != nullptr)
  2688. {
  2689. pnodeFnc->pnodeRest->sym->SetNeedDeclaration(false);
  2690. }
  2691. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2692. if (!funcInfo->IsBodyAndParamScopeMerged())
  2693. {
  2694. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2695. // We have to do this after the rest param is marked as false for need declaration.
  2696. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2697. paramScope->ForEachSymbol([&](Symbol* param) {
  2698. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2699. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2700. // is expected to stay inside the function expression scope
  2701. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2702. {
  2703. if (!varSym->GetNeedDeclaration())
  2704. {
  2705. if (param->IsInSlot(this, funcInfo))
  2706. {
  2707. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2708. // Walking the scope chain is not possible at this time.
  2709. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2710. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2711. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2712. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2713. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2714. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2715. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2716. funcInfo->ReleaseTmpRegister(tempReg);
  2717. }
  2718. else if (param->GetLocation() != Js::Constants::NoRegister)
  2719. {
  2720. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2721. }
  2722. else
  2723. {
  2724. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2725. }
  2726. }
  2727. else
  2728. {
  2729. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2730. // re-declaration error.
  2731. Assert(param->IsArguments());
  2732. }
  2733. }
  2734. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2735. {
  2736. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2737. {
  2738. formalsUpperBound = param->GetLocation();
  2739. }
  2740. }
  2741. });
  2742. }
  2743. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2744. {
  2745. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2746. }
  2747. if (pnodeFnc->pnodeBodyScope != nullptr)
  2748. {
  2749. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2750. }
  2751. this->inPrologue = false;
  2752. if (funcInfo->IsGlobalFunction())
  2753. {
  2754. EmitGlobalBody(funcInfo);
  2755. }
  2756. else
  2757. {
  2758. EmitFunctionBody(funcInfo);
  2759. }
  2760. if (pnodeFnc->pnodeBodyScope != nullptr)
  2761. {
  2762. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2763. }
  2764. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2765. if (!this->IsInDebugMode())
  2766. {
  2767. // Release the temp registers that we reserved for inner scopes above.
  2768. if (innerScopeCount)
  2769. {
  2770. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2771. for (uint i = 0; i < innerScopeCount; i++)
  2772. {
  2773. funcInfo->ReleaseTmpRegister(tmpReg);
  2774. tmpReg--;
  2775. }
  2776. }
  2777. }
  2778. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2779. Assert(funcInfo->curTmpReg == firstTmpReg);
  2780. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2781. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2782. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2783. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2784. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2785. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2786. #if DBG_DUMP
  2787. if (PHASE_STATS1(Js::ByteCodePhase))
  2788. {
  2789. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2790. m_writer.ByteCodeDataSize(),
  2791. m_writer.AuxiliaryDataSize(),
  2792. m_writer.AuxiliaryContextDataSize(),
  2793. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2794. funcInfo->name);
  2795. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2796. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2797. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2798. }
  2799. #endif
  2800. this->MapCacheIdsToPropertyIds(funcInfo);
  2801. this->MapReferencedPropertyIds(funcInfo);
  2802. Assert(this->TopFuncInfo() == funcInfo);
  2803. PopFuncInfo(_u("EmitOneFunction"));
  2804. m_writer.SetCallSiteCount(m_callSiteId);
  2805. #ifdef LOG_BYTECODE_AST_RATIO
  2806. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2807. #else
  2808. m_writer.End();
  2809. #endif
  2810. }
  2811. catch (...)
  2812. {
  2813. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2814. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2815. byteCodeFunction->ResetByteCodeGenState();
  2816. m_writer.Reset();
  2817. throw;
  2818. }
  2819. #ifdef PERF_HINT
  2820. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2821. {
  2822. if (byteCodeFunction->GetHasTry())
  2823. {
  2824. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2825. }
  2826. if (funcInfo->GetCallsEval())
  2827. {
  2828. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2829. }
  2830. else if (funcInfo->GetChildCallsEval())
  2831. {
  2832. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2833. }
  2834. }
  2835. #endif
  2836. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2837. {
  2838. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2839. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2840. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2841. {
  2842. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2843. {
  2844. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2845. }
  2846. return true;
  2847. });
  2848. }
  2849. byteCodeFunction->SetInitialDefaultEntryPoint();
  2850. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2851. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2852. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2853. {
  2854. if (m_utf8SourceInfo->GetIsLibraryCode())
  2855. {
  2856. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2857. }
  2858. else
  2859. {
  2860. Js::Throw::FatalInternalError();
  2861. }
  2862. }
  2863. #endif
  2864. #if DBG_DUMP
  2865. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2866. {
  2867. pnodeFnc->Dump();
  2868. }
  2869. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2870. {
  2871. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2872. }
  2873. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2874. {
  2875. byteCodeFunction->DumpScopes();
  2876. }
  2877. #endif
  2878. #if ENABLE_NATIVE_CODEGEN
  2879. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2880. && !this->forceNoNative
  2881. && !this->scriptContext->GetConfig()->IsNoNative())
  2882. {
  2883. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2884. }
  2885. #endif
  2886. }
  2887. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2888. {
  2889. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2890. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2891. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2892. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2893. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2894. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2895. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2896. if (totalFieldAccessInlineCacheCount == 0)
  2897. {
  2898. return;
  2899. }
  2900. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2901. {
  2902. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2903. {
  2904. if (inlineCacheList)
  2905. {
  2906. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2907. {
  2908. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2909. if (cacheUnit.loadCacheId != -1)
  2910. {
  2911. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2912. }
  2913. if (cacheUnit.loadMethodCacheId != -1)
  2914. {
  2915. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2916. }
  2917. if (cacheUnit.storeCacheId != -1)
  2918. {
  2919. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2920. }
  2921. });
  2922. }
  2923. });
  2924. });
  2925. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2926. {
  2927. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2928. });
  2929. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2930. {
  2931. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2932. });
  2933. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2934. {
  2935. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2936. });
  2937. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2938. while (valueOfIter.Next())
  2939. {
  2940. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2941. }
  2942. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2943. while (toStringIter.Next())
  2944. {
  2945. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2946. }
  2947. #if DBG
  2948. functionBody->VerifyCacheIdToPropertyIdMap();
  2949. #endif
  2950. }
  2951. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2952. {
  2953. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2954. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2955. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2956. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2957. {
  2958. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2959. });
  2960. #if DBG
  2961. functionBody->VerifyReferencedPropertyIdMap();
  2962. #endif
  2963. }
  2964. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2965. {
  2966. while (pnode)
  2967. {
  2968. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2969. {
  2970. break;
  2971. }
  2972. switch (pnode->nop)
  2973. {
  2974. case knopFncDecl:
  2975. #ifdef ASMJS_PLAT
  2976. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2977. {
  2978. Js::ExclusiveContext context(this, GetScriptContext());
  2979. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2980. {
  2981. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2982. break;
  2983. }
  2984. else if (CONFIG_FLAG(AsmJsStopOnError))
  2985. {
  2986. exit(JSERR_AsmJsCompileError);
  2987. }
  2988. else
  2989. {
  2990. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2991. throw Js::AsmJsParseException();
  2992. }
  2993. }
  2994. #endif
  2995. // FALLTHROUGH
  2996. case knopProg:
  2997. if (pnode->AsParseNodeFnc()->funcInfo)
  2998. {
  2999. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  3000. Scope* paramScope = funcInfo->GetParamScope();
  3001. if (!funcInfo->IsBodyAndParamScopeMerged())
  3002. {
  3003. funcInfo->SetCurrentChildScope(paramScope);
  3004. }
  3005. else
  3006. {
  3007. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  3008. }
  3009. this->StartEmitFunction(pnode->AsParseNodeFnc());
  3010. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3011. if (!funcInfo->IsBodyAndParamScopeMerged())
  3012. {
  3013. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  3014. }
  3015. else
  3016. {
  3017. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  3018. }
  3019. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3020. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3021. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3022. funcInfo->SetCurrentChildScope(nullptr);
  3023. }
  3024. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3025. break;
  3026. case knopBlock:
  3027. {
  3028. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3029. this->StartEmitBlock(pnodeBlock);
  3030. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3031. this->EndEmitBlock(pnodeBlock);
  3032. pnode = pnodeBlock->pnodeNext;
  3033. break;
  3034. }
  3035. case knopCatch:
  3036. {
  3037. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3038. this->StartEmitCatch(pnodeCatch);
  3039. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3040. this->EndEmitCatch(pnodeCatch);
  3041. pnode = pnodeCatch->pnodeNext;
  3042. break;
  3043. }
  3044. case knopWith:
  3045. this->StartEmitWith(pnode);
  3046. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3047. this->EndEmitWith(pnode);
  3048. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3049. break;
  3050. default:
  3051. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3052. break;
  3053. }
  3054. }
  3055. }
  3056. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3057. {
  3058. if (pnodeFnc->pnodeName)
  3059. {
  3060. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3061. Symbol *sym = pnodeFnc->pnodeName->sym;
  3062. // If this function is shadowing the arguments symbol in body then skip it.
  3063. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3064. if (sym && !sym->IsArguments())
  3065. {
  3066. sym->EnsureScopeSlot(this, funcInfo);
  3067. }
  3068. }
  3069. }
  3070. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3071. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3072. {
  3073. if (pnodeFnc->pnodeName)
  3074. {
  3075. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3076. Symbol *sym = pnodeFnc->pnodeName->sym;
  3077. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3078. {
  3079. sym->EnsureScopeSlot(this, funcInfo);
  3080. }
  3081. }
  3082. }
  3083. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3084. {
  3085. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3086. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3087. Scope * const bodyScope = funcInfo->GetBodyScope();
  3088. Scope * const paramScope = funcInfo->GetParamScope();
  3089. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3090. {
  3091. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3092. {
  3093. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3094. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3095. }
  3096. if (funcInfo->GetCallsEval())
  3097. {
  3098. funcInfo->byteCodeFunction->SetDontInline(true);
  3099. }
  3100. Scope * const funcExprScope = funcInfo->funcExprScope;
  3101. if (funcExprScope)
  3102. {
  3103. if (funcInfo->GetCallsEval())
  3104. {
  3105. Assert(funcExprScope->GetIsObject());
  3106. }
  3107. if (funcExprScope->GetIsObject())
  3108. {
  3109. funcExprScope->SetCapturesAll(true);
  3110. funcExprScope->SetMustInstantiate(true);
  3111. PushScope(funcExprScope);
  3112. }
  3113. else
  3114. {
  3115. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3116. if (funcInfo->IsBodyAndParamScopeMerged())
  3117. {
  3118. funcInfo->bodyScope->AddSymbol(sym);
  3119. }
  3120. else
  3121. {
  3122. funcInfo->paramScope->AddSymbol(sym);
  3123. }
  3124. sym->EnsureScopeSlot(this, funcInfo);
  3125. if (sym->GetHasNonLocalReference())
  3126. {
  3127. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3128. }
  3129. }
  3130. }
  3131. if (pnodeFnc->nop != knopProg)
  3132. {
  3133. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3134. {
  3135. Assert(bodyScope->GetIsObject());
  3136. }
  3137. if (bodyScope->GetIsObject())
  3138. {
  3139. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3140. }
  3141. else
  3142. {
  3143. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3144. }
  3145. if (!funcInfo->IsBodyAndParamScopeMerged())
  3146. {
  3147. if (paramScope->GetIsObject())
  3148. {
  3149. paramScope->SetLocation(funcInfo->frameObjRegister);
  3150. }
  3151. else
  3152. {
  3153. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3154. }
  3155. }
  3156. if (bodyScope->GetIsObject())
  3157. {
  3158. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3159. funcInfo->SetHasCachedScope(
  3160. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3161. !funcInfo->Escapes() &&
  3162. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3163. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3164. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3165. !pnodeFnc->HasDefaultArguments() &&
  3166. !pnodeFnc->HasDestructuredParams() &&
  3167. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3168. #if ENABLE_TTD
  3169. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3170. #endif
  3171. );
  3172. if (funcInfo->GetHasCachedScope())
  3173. {
  3174. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3175. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3176. if (funcSym && funcSym->GetIsFuncExpr())
  3177. {
  3178. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3179. {
  3180. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3181. }
  3182. else
  3183. {
  3184. funcInfo->funcObjRegister = funcSym->GetLocation();
  3185. }
  3186. }
  3187. else
  3188. {
  3189. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3190. }
  3191. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3192. }
  3193. ParseNode *pnode;
  3194. Symbol *sym;
  3195. if (funcInfo->GetHasArguments())
  3196. {
  3197. // Process function's formal parameters
  3198. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3199. {
  3200. if (pnode->IsVarLetOrConst())
  3201. {
  3202. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3203. }
  3204. });
  3205. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3206. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3207. // doesn't require scope slot for "arguments" because inner functions can't access
  3208. // outer function's arguments directly.
  3209. sym = funcInfo->GetArgumentsSymbol();
  3210. Assert(sym);
  3211. if (sym->NeedsSlotAlloc(this, funcInfo))
  3212. {
  3213. sym->EnsureScopeSlot(this, funcInfo);
  3214. }
  3215. }
  3216. sym = funcInfo->root->GetFuncSymbol();
  3217. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3218. {
  3219. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3220. {
  3221. sym->SetScopeSlot(0);
  3222. }
  3223. else if (funcInfo->GetFuncExprNameReference())
  3224. {
  3225. sym->EnsureScopeSlot(this, funcInfo);
  3226. }
  3227. }
  3228. if (!funcInfo->GetHasArguments())
  3229. {
  3230. Symbol *formal;
  3231. Js::ArgSlot pos = 1;
  3232. auto moveArgToReg = [&](ParseNode *pnode)
  3233. {
  3234. if (pnode->IsVarLetOrConst())
  3235. {
  3236. formal = pnode->AsParseNodeVar()->sym;
  3237. // Get the param from its argument position into its assigned register.
  3238. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3239. if (formal->GetLocation() + 1 == pos)
  3240. {
  3241. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3242. }
  3243. }
  3244. pos++;
  3245. };
  3246. MapFormals(pnodeFnc, moveArgToReg);
  3247. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3248. }
  3249. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3250. {
  3251. sym = pnode->AsParseNodeVar()->sym;
  3252. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3253. {
  3254. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3255. {
  3256. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3257. }
  3258. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3259. {
  3260. sym->EnsureScopeSlot(this, funcInfo);
  3261. }
  3262. }
  3263. }
  3264. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3265. {
  3266. for (pnode = pnodeScope; pnode;)
  3267. {
  3268. switch (pnode->nop)
  3269. {
  3270. case knopFncDecl:
  3271. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3272. {
  3273. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3274. }
  3275. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3276. break;
  3277. case knopBlock:
  3278. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3279. break;
  3280. case knopCatch:
  3281. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3282. break;
  3283. case knopWith:
  3284. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3285. break;
  3286. }
  3287. }
  3288. };
  3289. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3290. if (pnodeFnc->pnodeBody)
  3291. {
  3292. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3293. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3294. }
  3295. }
  3296. else
  3297. {
  3298. ParseNode *pnode;
  3299. Symbol *sym;
  3300. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3301. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3302. {
  3303. sym = pnode->AsParseNodeVar()->sym;
  3304. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3305. {
  3306. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3307. {
  3308. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3309. }
  3310. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3311. {
  3312. sym->EnsureScopeSlot(this, funcInfo);
  3313. }
  3314. }
  3315. }
  3316. auto ensureScopeSlot = [&](ParseNode *pnode)
  3317. {
  3318. if (pnode->IsVarLetOrConst())
  3319. {
  3320. sym = pnode->AsParseNodeVar()->sym;
  3321. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3322. {
  3323. sym->EnsureScopeSlot(this, funcInfo);
  3324. }
  3325. }
  3326. };
  3327. // Process function's formal parameters
  3328. MapFormals(pnodeFnc, ensureScopeSlot);
  3329. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3330. if (funcInfo->GetHasArguments())
  3331. {
  3332. sym = funcInfo->GetArgumentsSymbol();
  3333. Assert(sym);
  3334. // There is no eval so the arguments may be captured in a lambda.
  3335. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3336. sym->EnsureScopeSlot(this, funcInfo);
  3337. }
  3338. if (pnodeFnc->pnodeBody)
  3339. {
  3340. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3341. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3342. }
  3343. }
  3344. // When we have split scope and body scope does not have any scope slots allocated, we don't have to mark the body scope as mustinstantiate.
  3345. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3346. {
  3347. bodyScope->SetMustInstantiate(true);
  3348. }
  3349. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3350. {
  3351. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3352. }
  3353. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3354. {
  3355. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3356. {
  3357. paramScope->SetMustInstantiate(true);
  3358. }
  3359. else
  3360. {
  3361. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3362. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3363. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3364. }
  3365. }
  3366. }
  3367. else
  3368. {
  3369. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3370. if (newScopeForEval)
  3371. {
  3372. Assert(bodyScope->GetIsObject());
  3373. }
  3374. }
  3375. }
  3376. if (!funcInfo->IsBodyAndParamScopeMerged())
  3377. {
  3378. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3379. Assert(paramBlock->blockType == Parameter);
  3380. PushScope(paramScope);
  3381. // While emitting the functions we have to stop when we see the body scope block.
  3382. // Otherwise functions defined in the body scope will not be able to get the right references.
  3383. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3384. Assert(this->GetCurrentScope() == paramScope);
  3385. }
  3386. PushScope(bodyScope);
  3387. }
  3388. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3389. {
  3390. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3391. {
  3392. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3393. }
  3394. else
  3395. {
  3396. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3397. if (opcode == Js::OpCode::LdModuleSlot)
  3398. {
  3399. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3400. }
  3401. }
  3402. }
  3403. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3404. {
  3405. Assert(sym->GetIsModuleExportStorage());
  3406. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3407. {
  3408. return true;
  3409. }
  3410. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3411. library->EnsureModuleRecordList();
  3412. uint moduleIndex = this->GetModuleID();
  3413. uint moduleSlotIndex;
  3414. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3415. if (sym->GetIsModuleImport())
  3416. {
  3417. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3418. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3419. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3420. {
  3421. return false;
  3422. }
  3423. AnalysisAssert(moduleNameRecord != nullptr);
  3424. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3425. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3426. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3427. moduleIndex = resolvedModuleRecord->GetModuleId();
  3428. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3429. }
  3430. else
  3431. {
  3432. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3433. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3434. }
  3435. sym->SetModuleIndex(moduleIndex);
  3436. sym->SetScopeSlot(moduleSlotIndex);
  3437. return true;
  3438. }
  3439. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3440. {
  3441. // We are assigning pnode to the default export of the current module.
  3442. uint moduleIndex = this->GetModuleID();
  3443. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3444. library->EnsureModuleRecordList();
  3445. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3446. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3447. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3448. }
  3449. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3450. {
  3451. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3452. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3453. {
  3454. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3455. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3456. {
  3457. sym->EnsureScopeSlot(this, funcInfo);
  3458. this->ProcessCapturedSym(sym);
  3459. }
  3460. });
  3461. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3462. }
  3463. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3464. {
  3465. while (pnode)
  3466. {
  3467. switch (pnode->nop)
  3468. {
  3469. case knopFncDecl:
  3470. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3471. {
  3472. CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3473. }
  3474. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3475. break;
  3476. case knopBlock:
  3477. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3478. break;
  3479. case knopCatch:
  3480. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3481. break;
  3482. case knopWith:
  3483. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3484. break;
  3485. }
  3486. }
  3487. }
  3488. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3489. {
  3490. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3491. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3492. PopScope(); // function body
  3493. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3494. Scope* paramScope = funcInfo->paramScope;
  3495. if (!funcInfo->IsBodyAndParamScopeMerged())
  3496. {
  3497. Assert(this->GetCurrentScope() == paramScope);
  3498. PopScope(); // Pop the param scope
  3499. }
  3500. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3501. {
  3502. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3503. // TODO: Refactor Start and EndEmitFunction for clarity.
  3504. Scope *scope = funcInfo->funcExprScope;
  3505. if (scope && scope->GetMustInstantiate())
  3506. {
  3507. Assert(currentScope == scope);
  3508. PopScope();
  3509. }
  3510. }
  3511. Assert(funcInfo == this->TopFuncInfo());
  3512. PopFuncInfo(_u("EndEmitFunction"));
  3513. }
  3514. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3515. {
  3516. Assert(pnodeCatch->nop == knopCatch);
  3517. Scope *scope = pnodeCatch->scope;
  3518. FuncInfo *funcInfo = scope->GetFunc();
  3519. // Catch scope is a dynamic object if it can be passed to a scoped lookup helper (i.e., eval is present or we're in an event handler).
  3520. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3521. {
  3522. scope->SetIsObject();
  3523. }
  3524. ParseNode * pnodeParam = pnodeCatch->GetParam();
  3525. if (pnodeParam->nop == knopParamPattern)
  3526. {
  3527. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3528. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3529. Parser::MapBindIdentifier(pnodeParam->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  3530. {
  3531. Symbol *sym = item->AsParseNodeVar()->sym;
  3532. if (funcInfo->IsGlobalFunction())
  3533. {
  3534. sym->SetIsGlobalCatch(true);
  3535. }
  3536. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3537. if (sym->NeedsSlotAlloc(this, funcInfo))
  3538. {
  3539. sym->EnsureScopeSlot(this, funcInfo);
  3540. }
  3541. });
  3542. // In the case of pattern we will always going to push the scope.
  3543. PushScope(scope);
  3544. }
  3545. else
  3546. {
  3547. Symbol *sym = pnodeParam->AsParseNodeName()->sym;
  3548. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3549. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3550. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3551. if (funcInfo->IsGlobalFunction())
  3552. {
  3553. sym->SetIsGlobalCatch(true);
  3554. }
  3555. if (scope->GetMustInstantiate())
  3556. {
  3557. if (sym->IsInSlot(this, funcInfo))
  3558. {
  3559. // Since there is only one symbol we are pushing to slot.
  3560. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3561. this->ProcessCapturedSym(sym);
  3562. sym->EnsureScopeSlot(this, funcInfo);
  3563. }
  3564. }
  3565. PushScope(scope);
  3566. }
  3567. }
  3568. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3569. {
  3570. Assert(pnodeCatch->nop == knopCatch);
  3571. Assert(currentScope == pnodeCatch->scope);
  3572. PopScope();
  3573. }
  3574. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3575. {
  3576. if (!BlockHasOwnScope(pnodeBlock, this))
  3577. {
  3578. return;
  3579. }
  3580. Assert(pnodeBlock->nop == knopBlock);
  3581. PushBlock(pnodeBlock);
  3582. Scope *scope = pnodeBlock->scope;
  3583. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3584. {
  3585. Assert(scope->GetIsObject());
  3586. }
  3587. // TODO: Consider nested deferred parsing.
  3588. if (scope->GetMustInstantiate())
  3589. {
  3590. FuncInfo *funcInfo = scope->GetFunc();
  3591. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3592. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3593. PushScope(scope);
  3594. }
  3595. }
  3596. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3597. {
  3598. if (!BlockHasOwnScope(pnodeBlock, this))
  3599. {
  3600. return;
  3601. }
  3602. Assert(pnodeBlock->nop == knopBlock);
  3603. Scope *scope = pnodeBlock->scope;
  3604. if (scope && scope->GetMustInstantiate())
  3605. {
  3606. Assert(currentScope == pnodeBlock->scope);
  3607. PopScope();
  3608. }
  3609. PopBlock();
  3610. }
  3611. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3612. {
  3613. Assert(pnodeWith->nop == knopWith);
  3614. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3615. AssertOrFailFast(scope->GetIsObject());
  3616. PushScope(scope);
  3617. }
  3618. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3619. {
  3620. Assert(pnodeWith->nop == knopWith);
  3621. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3622. PopScope();
  3623. }
  3624. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3625. {
  3626. Scope *currScope = this->currentScope;
  3627. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3628. if (currScope == funcScope)
  3629. {
  3630. return evalEnv;
  3631. }
  3632. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3633. if (acquireTempLoc)
  3634. {
  3635. tempLoc = funcInfo->AcquireTmpRegister();
  3636. }
  3637. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3638. // but the list must first be reversed so that innermost scopes appear first in the list.
  3639. while (currScope != funcScope)
  3640. {
  3641. Scope *innerScope;
  3642. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3643. ;
  3644. if (innerScope->GetMustInstantiate())
  3645. {
  3646. if (!innerScope->HasInnerScopeIndex())
  3647. {
  3648. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3649. {
  3650. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3651. }
  3652. else
  3653. {
  3654. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3655. }
  3656. }
  3657. else
  3658. {
  3659. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3660. {
  3661. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3662. }
  3663. else
  3664. {
  3665. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3666. }
  3667. }
  3668. evalEnv = tempLoc;
  3669. }
  3670. funcScope = innerScope;
  3671. }
  3672. if (acquireTempLoc)
  3673. {
  3674. funcInfo->ReleaseTmpRegister(tempLoc);
  3675. }
  3676. return evalEnv;
  3677. }
  3678. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3679. {
  3680. Js::ByteCodeLabel doneLabel = 0;
  3681. bool fLabelDefined = false;
  3682. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3683. Js::RegSlot thisLocation = *pThisLocation;
  3684. Js::RegSlot instLocation = *pInstLocation;
  3685. Js::PropertyId envIndex = -1;
  3686. Scope *scope = nullptr;
  3687. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3688. Assert(symScope);
  3689. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3690. {
  3691. *pInstLocation = Js::Constants::NoRegister;
  3692. return;
  3693. }
  3694. for (;;)
  3695. {
  3696. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3697. if (scope == this->globalScope)
  3698. {
  3699. break;
  3700. }
  3701. if (scope != symScope)
  3702. {
  3703. // We're not sure where the function is (eval/with/etc).
  3704. // So we're going to need registers to hold the instance where we (dynamically) find
  3705. // the function, and possibly to hold the "this" pointer we will pass to it.
  3706. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3707. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3708. if (instLocation == Js::Constants::NoRegister)
  3709. {
  3710. instLocation = funcInfo->AcquireTmpRegister();
  3711. // The "this" pointer will not be the same as the instance, so give it its own register.
  3712. thisLocation = funcInfo->AcquireTmpRegister();
  3713. }
  3714. }
  3715. if (envIndex == -1)
  3716. {
  3717. Assert(funcInfo == scope->GetFunc());
  3718. scopeLocation = scope->GetLocation();
  3719. }
  3720. if (scope == symScope)
  3721. {
  3722. break;
  3723. }
  3724. // Found a scope to which the property may have been added.
  3725. Assert(scope && scope->GetIsDynamic());
  3726. if (!fLabelDefined)
  3727. {
  3728. fLabelDefined = true;
  3729. doneLabel = this->m_writer.DefineLabel();
  3730. }
  3731. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3732. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3733. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3734. if (envIndex != -1)
  3735. {
  3736. this->m_writer.BrEnvProperty(
  3737. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3738. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3739. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3740. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3741. AssertOrFailFast(scope->GetIsObject());
  3742. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3743. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3744. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3745. this->m_writer.Reg2(op, instLocation, tmpReg);
  3746. if (thisLocation != Js::Constants::NoRegister)
  3747. {
  3748. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3749. }
  3750. funcInfo->ReleaseTmpRegister(tmpReg);
  3751. }
  3752. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3753. {
  3754. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3755. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3756. Assert(!unwrapWithObj);
  3757. AssertOrFailFast(scope->GetIsObject());
  3758. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3759. if (thisLocation != Js::Constants::NoRegister)
  3760. {
  3761. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3762. }
  3763. }
  3764. else
  3765. {
  3766. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3767. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3768. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3769. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3770. if (thisLocation != Js::Constants::NoRegister)
  3771. {
  3772. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3773. }
  3774. }
  3775. this->m_writer.Br(doneLabel);
  3776. this->m_writer.MarkLabel(nextLabel);
  3777. }
  3778. if (sym == nullptr || sym->GetIsGlobal())
  3779. {
  3780. if (this->flags & (fscrEval | fscrImplicitThis))
  3781. {
  3782. // Load of a symbol with unknown scope from within eval.
  3783. // Get it from the closure environment.
  3784. if (instLocation == Js::Constants::NoRegister)
  3785. {
  3786. instLocation = funcInfo->AcquireTmpRegister();
  3787. }
  3788. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3789. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3790. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3791. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3792. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3793. if (thisLocation == Js::Constants::NoRegister)
  3794. {
  3795. thisLocation = funcInfo->AcquireTmpRegister();
  3796. }
  3797. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3798. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3799. }
  3800. else
  3801. {
  3802. if (instLocation == Js::Constants::NoRegister)
  3803. {
  3804. instLocation = ByteCodeGenerator::RootObjectRegister;
  3805. }
  3806. else
  3807. {
  3808. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3809. }
  3810. if (thisLocation == Js::Constants::NoRegister)
  3811. {
  3812. thisLocation = funcInfo->undefinedConstantRegister;
  3813. }
  3814. else
  3815. {
  3816. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3817. }
  3818. }
  3819. }
  3820. else if (instLocation != Js::Constants::NoRegister)
  3821. {
  3822. if (envIndex != -1)
  3823. {
  3824. AssertOrFailFast(scope->GetIsObject());
  3825. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3826. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3827. }
  3828. else if (scope->HasInnerScopeIndex())
  3829. {
  3830. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3831. }
  3832. else if (symScope == funcInfo->GetParamScope())
  3833. {
  3834. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3835. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3836. }
  3837. else if (symScope != funcInfo->GetBodyScope())
  3838. {
  3839. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3840. }
  3841. else
  3842. {
  3843. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3844. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3845. }
  3846. if (thisLocation != Js::Constants::NoRegister)
  3847. {
  3848. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3849. }
  3850. else
  3851. {
  3852. thisLocation = funcInfo->undefinedConstantRegister;
  3853. }
  3854. }
  3855. *pThisLocation = thisLocation;
  3856. *pInstLocation = instLocation;
  3857. if (fLabelDefined)
  3858. {
  3859. this->m_writer.MarkLabel(doneLabel);
  3860. }
  3861. }
  3862. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3863. {
  3864. // Note: declared variables and assignments in the global function go to the root object directly.
  3865. if (this->flags & fscrEval)
  3866. {
  3867. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3868. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3869. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3870. // into one operation). See WOOB 1121763 and 1120973.
  3871. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3872. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3873. }
  3874. else
  3875. {
  3876. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3877. }
  3878. }
  3879. void
  3880. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3881. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3882. {
  3883. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3884. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3885. }
  3886. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3887. {
  3888. Scope *scope = sym->GetScope();
  3889. // Check consistency of sym->IsInSlot.
  3890. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3891. // Arrived at the scope in which the property was defined.
  3892. if (sym->NeedsSlotAlloc(this, funcInfo))
  3893. {
  3894. // The property is in memory rather than register. We'll have to load it from the slots.
  3895. if (scope->GetIsObject())
  3896. {
  3897. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3898. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3899. Js::RegSlot objReg;
  3900. if (scope->HasInnerScopeIndex())
  3901. {
  3902. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3903. }
  3904. else
  3905. {
  3906. objReg = scope->GetLocation();
  3907. }
  3908. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3909. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3910. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3911. {
  3912. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3913. }
  3914. else if (scope->HasInnerScopeIndex())
  3915. {
  3916. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3917. }
  3918. else
  3919. {
  3920. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3921. }
  3922. }
  3923. else
  3924. {
  3925. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3926. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3927. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3928. // Now store the property to its slot.
  3929. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3930. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3931. {
  3932. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3933. }
  3934. else
  3935. {
  3936. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3937. }
  3938. }
  3939. }
  3940. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3941. {
  3942. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3943. }
  3944. }
  3945. Js::OpCode
  3946. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  3947. {
  3948. Js::OpCode op;
  3949. if (envIndex != -1)
  3950. {
  3951. if (scope->GetIsObject())
  3952. {
  3953. op = Js::OpCode::StEnvObjSlot;
  3954. }
  3955. else
  3956. {
  3957. op = Js::OpCode::StEnvSlot;
  3958. }
  3959. }
  3960. else if (scopeLocation != Js::Constants::NoRegister &&
  3961. scopeLocation == funcInfo->frameSlotsRegister)
  3962. {
  3963. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3964. {
  3965. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3966. // We should use the param scope's bytecode now.
  3967. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3968. op = Js::OpCode::StParamSlot;
  3969. }
  3970. else
  3971. {
  3972. op = Js::OpCode::StLocalSlot;
  3973. }
  3974. }
  3975. else if (scopeLocation != Js::Constants::NoRegister &&
  3976. scopeLocation == funcInfo->frameObjRegister)
  3977. {
  3978. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3979. {
  3980. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3981. // We should use the param scope's bytecode now.
  3982. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3983. op = Js::OpCode::StParamObjSlot;
  3984. }
  3985. else
  3986. {
  3987. op = Js::OpCode::StLocalObjSlot;
  3988. }
  3989. }
  3990. else
  3991. {
  3992. Assert(scope->HasInnerScopeIndex());
  3993. if (scope->GetIsObject())
  3994. {
  3995. op = Js::OpCode::StInnerObjSlot;
  3996. }
  3997. else
  3998. {
  3999. op = Js::OpCode::StInnerSlot;
  4000. }
  4001. }
  4002. if (chkBlockVar)
  4003. {
  4004. op = this->ToChkUndeclOp(op);
  4005. }
  4006. return op;
  4007. }
  4008. Js::OpCode
  4009. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4010. {
  4011. Js::OpCode op;
  4012. if (scopeLocation != Js::Constants::NoRegister &&
  4013. scopeLocation == funcInfo->frameObjRegister)
  4014. {
  4015. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4016. }
  4017. else if (scope->HasInnerScopeIndex())
  4018. {
  4019. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4020. }
  4021. else
  4022. {
  4023. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4024. }
  4025. return op;
  4026. }
  4027. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4028. {
  4029. Js::ByteCodeLabel doneLabel = 0;
  4030. bool fLabelDefined = false;
  4031. Js::PropertyId envIndex = -1;
  4032. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4033. Assert(symScope);
  4034. // isFncDeclVar denotes that the symbol being stored to here is the var
  4035. // binding of a function declaration and we know we want to store directly
  4036. // to it, skipping over any dynamic scopes that may lie in between.
  4037. Scope *scope = nullptr;
  4038. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4039. bool scopeAcquired = false;
  4040. Js::OpCode op;
  4041. if (sym && sym->GetIsModuleExportStorage())
  4042. {
  4043. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4044. {
  4045. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4046. }
  4047. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4048. return;
  4049. }
  4050. if (isFncDeclVar)
  4051. {
  4052. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4053. // of the parent function, so we need to calculate envIndex in lieu of the while
  4054. // loop below.
  4055. do
  4056. {
  4057. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4058. } while (scope != symScope);
  4059. Assert(scope == symScope);
  4060. scopeLocation = scope->GetLocation();
  4061. }
  4062. while (!isFncDeclVar)
  4063. {
  4064. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4065. if (scope == this->globalScope)
  4066. {
  4067. break;
  4068. }
  4069. if (envIndex == -1)
  4070. {
  4071. Assert(funcInfo == scope->GetFunc());
  4072. scopeLocation = scope->GetLocation();
  4073. }
  4074. if (scope == symScope)
  4075. {
  4076. break;
  4077. }
  4078. // Found a scope to which the property may have been added.
  4079. Assert(scope && scope->GetIsDynamic());
  4080. if (!fLabelDefined)
  4081. {
  4082. fLabelDefined = true;
  4083. doneLabel = this->m_writer.DefineLabel();
  4084. }
  4085. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4086. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4087. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4088. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4089. if (envIndex != -1)
  4090. {
  4091. this->m_writer.BrEnvProperty(
  4092. Js::OpCode::BrOnNoEnvProperty,
  4093. nextLabel,
  4094. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4095. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4096. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4097. AssertOrFailFast(scope->GetIsObject());
  4098. this->m_writer.SlotI1(
  4099. Js::OpCode::LdEnvObj,
  4100. instLocation,
  4101. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4102. if (unwrapWithObj)
  4103. {
  4104. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4105. }
  4106. this->m_writer.PatchableProperty(
  4107. Js::OpCode::StFld,
  4108. rhsLocation,
  4109. instLocation,
  4110. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4111. funcInfo->ReleaseTmpRegister(instLocation);
  4112. }
  4113. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4114. {
  4115. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4116. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4117. Assert(!unwrapWithObj);
  4118. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4119. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4120. }
  4121. else
  4122. {
  4123. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4124. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4125. if (unwrapWithObj)
  4126. {
  4127. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4128. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4129. scopeLocation = unwrappedScopeLocation;
  4130. }
  4131. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4132. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4133. if (unwrapWithObj)
  4134. {
  4135. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4136. }
  4137. }
  4138. this->m_writer.Br(doneLabel);
  4139. this->m_writer.MarkLabel(nextLabel);
  4140. }
  4141. // Arrived at the scope in which the property was defined.
  4142. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4143. {
  4144. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4145. // Intentionally continue on to do normal EmitPropStore behavior so
  4146. // that the bytecode ends up well-formed for the backend. This is
  4147. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4148. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4149. // of their load and then they skip emitting their own bytecode.
  4150. // Potayto potahto.
  4151. }
  4152. if (sym == nullptr || sym->GetIsGlobal())
  4153. {
  4154. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4155. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4156. if (this->flags & fscrEval)
  4157. {
  4158. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4159. {
  4160. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4161. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4162. }
  4163. else
  4164. {
  4165. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4166. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4167. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4168. }
  4169. }
  4170. else if (this->flags & fscrImplicitThis)
  4171. {
  4172. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4173. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4174. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4175. }
  4176. else
  4177. {
  4178. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false, forceStrictModeForClassComputedPropertyName), rhsLocation, propertyId, false, true, funcInfo);
  4179. }
  4180. }
  4181. else if (sym->GetIsFuncExpr())
  4182. {
  4183. // Store to function expr variable.
  4184. // strict mode: we need to throw type error
  4185. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4186. {
  4187. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4188. // It doesn't matter which register we use, as long as it's valid for this function.
  4189. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4190. }
  4191. }
  4192. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4193. {
  4194. if (!isConstDecl && sym->GetIsConst())
  4195. {
  4196. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4197. // we have to catch it at runtime.
  4198. this->m_writer.W1(
  4199. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4200. }
  4201. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4202. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4203. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4204. // The property is in memory rather than register. We'll have to load it from the slots.
  4205. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4206. if (envIndex != -1)
  4207. {
  4208. this->m_writer.SlotI2(op, rhsLocation,
  4209. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4210. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4211. }
  4212. else if (scopeLocation != Js::Constants::NoRegister &&
  4213. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4214. {
  4215. this->m_writer.SlotI1(op, rhsLocation,
  4216. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4217. }
  4218. else
  4219. {
  4220. Assert(scope->HasInnerScopeIndex());
  4221. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4222. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4223. }
  4224. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4225. {
  4226. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4227. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4228. }
  4229. }
  4230. else if (isConstDecl)
  4231. {
  4232. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4233. if (this->ShouldTrackDebuggerMetadata())
  4234. {
  4235. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4236. }
  4237. }
  4238. else
  4239. {
  4240. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4241. {
  4242. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4243. // we have to catch it at runtime.
  4244. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4245. }
  4246. if (rhsLocation != sym->GetLocation())
  4247. {
  4248. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4249. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4250. {
  4251. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4252. }
  4253. }
  4254. }
  4255. if (fLabelDefined)
  4256. {
  4257. this->m_writer.MarkLabel(doneLabel);
  4258. }
  4259. if (scopeAcquired)
  4260. {
  4261. funcInfo->ReleaseTmpRegister(scopeLocation);
  4262. }
  4263. }
  4264. Js::OpCode
  4265. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4266. {
  4267. Js::OpCode op;
  4268. if (envIndex != -1)
  4269. {
  4270. if (scope->GetIsObject())
  4271. {
  4272. op = Js::OpCode::LdEnvObjSlot;
  4273. }
  4274. else
  4275. {
  4276. op = Js::OpCode::LdEnvSlot;
  4277. }
  4278. }
  4279. else if (scopeLocation != Js::Constants::NoRegister &&
  4280. scopeLocation == funcInfo->frameSlotsRegister)
  4281. {
  4282. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4283. {
  4284. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4285. // We should use the param scope's bytecode now.
  4286. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4287. op = Js::OpCode::LdParamSlot;
  4288. }
  4289. else
  4290. {
  4291. op = Js::OpCode::LdLocalSlot;
  4292. }
  4293. }
  4294. else if (scopeLocation != Js::Constants::NoRegister &&
  4295. scopeLocation == funcInfo->frameObjRegister)
  4296. {
  4297. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4298. {
  4299. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4300. // We should use the param scope's bytecode now.
  4301. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4302. op = Js::OpCode::LdParamObjSlot;
  4303. }
  4304. else
  4305. {
  4306. op = Js::OpCode::LdLocalObjSlot;
  4307. }
  4308. }
  4309. else if (scope->HasInnerScopeIndex())
  4310. {
  4311. if (scope->GetIsObject())
  4312. {
  4313. op = Js::OpCode::LdInnerObjSlot;
  4314. }
  4315. else
  4316. {
  4317. op = Js::OpCode::LdInnerSlot;
  4318. }
  4319. }
  4320. else
  4321. {
  4322. AssertOrFailFast(scope->GetIsObject());
  4323. op = Js::OpCode::LdObjSlot;
  4324. }
  4325. return op;
  4326. }
  4327. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4328. {
  4329. #if DBG
  4330. // We should load a const 'this' binding if the following holds
  4331. // - The function has a 'this' name node
  4332. // - We are in a global or global lambda function
  4333. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4334. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4335. {
  4336. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4337. && !funcInfo->GetThisSymbol()
  4338. && !(this->flags & fscrEval));
  4339. }
  4340. #endif
  4341. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4342. }
  4343. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4344. {
  4345. Symbol* sym = pnodeSpecialName->sym;
  4346. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4347. {
  4348. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4349. }
  4350. else
  4351. {
  4352. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4353. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4354. {
  4355. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4356. }
  4357. }
  4358. }
  4359. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4360. {
  4361. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4362. {
  4363. if (init)
  4364. {
  4365. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4366. }
  4367. else
  4368. {
  4369. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4370. }
  4371. }
  4372. }
  4373. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4374. {
  4375. // If sym belongs to a parent frame, get it from the closure environment.
  4376. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4377. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4378. // Otherwise, just copy the value to the lhsLocation.
  4379. Js::ByteCodeLabel doneLabel = 0;
  4380. bool fLabelDefined = false;
  4381. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4382. Js::PropertyId envIndex = -1;
  4383. Scope *scope = nullptr;
  4384. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4385. Assert(symScope);
  4386. if (sym && sym->GetIsModuleExportStorage())
  4387. {
  4388. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4389. return;
  4390. }
  4391. for (;;)
  4392. {
  4393. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4394. if (scope == this->globalScope)
  4395. {
  4396. break;
  4397. }
  4398. scopeLocation = scope->GetLocation();
  4399. if (scope == symScope)
  4400. {
  4401. break;
  4402. }
  4403. // Found a scope to which the property may have been added.
  4404. Assert(scope && scope->GetIsDynamic());
  4405. if (!fLabelDefined)
  4406. {
  4407. fLabelDefined = true;
  4408. doneLabel = this->m_writer.DefineLabel();
  4409. }
  4410. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4411. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4412. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4413. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4414. if (envIndex != -1)
  4415. {
  4416. this->m_writer.BrEnvProperty(
  4417. Js::OpCode::BrOnNoEnvProperty,
  4418. nextLabel,
  4419. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4420. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4421. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4422. AssertOrFailFast(scope->GetIsObject());
  4423. this->m_writer.SlotI1(
  4424. Js::OpCode::LdEnvObj,
  4425. instLocation,
  4426. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4427. if (unwrapWithObj)
  4428. {
  4429. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4430. }
  4431. this->m_writer.PatchableProperty(
  4432. Js::OpCode::LdFld,
  4433. lhsLocation,
  4434. instLocation,
  4435. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4436. funcInfo->ReleaseTmpRegister(instLocation);
  4437. }
  4438. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4439. {
  4440. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4441. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4442. Assert(!unwrapWithObj);
  4443. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4444. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4445. }
  4446. else
  4447. {
  4448. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4449. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4450. if (unwrapWithObj)
  4451. {
  4452. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4453. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4454. scopeLocation = unwrappedScopeLocation;
  4455. }
  4456. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4457. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4458. if (unwrapWithObj)
  4459. {
  4460. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4461. }
  4462. }
  4463. this->m_writer.Br(doneLabel);
  4464. this->m_writer.MarkLabel(nextLabel);
  4465. }
  4466. // Arrived at the scope in which the property was defined.
  4467. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4468. {
  4469. // Ensure this symbol has a slot if it needs one.
  4470. if (sym->IsInSlot(this, funcInfo))
  4471. {
  4472. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4473. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4474. }
  4475. if (skipUseBeforeDeclarationCheck)
  4476. {
  4477. if (lhsLocation != Js::Constants::NoRegister)
  4478. {
  4479. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4480. }
  4481. }
  4482. else
  4483. {
  4484. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4485. }
  4486. }
  4487. else if (sym == nullptr || sym->GetIsGlobal())
  4488. {
  4489. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4490. if (this->flags & fscrEval)
  4491. {
  4492. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4493. {
  4494. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4495. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4496. }
  4497. else
  4498. {
  4499. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4500. // Load of a symbol with unknown scope from within eval
  4501. // Get it from the closure environment.
  4502. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4503. }
  4504. }
  4505. else if (this->flags & fscrImplicitThis)
  4506. {
  4507. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4508. // Load of a symbol with unknown scope from within event handler.
  4509. // Get it from the closure environment.
  4510. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4511. }
  4512. else
  4513. {
  4514. // Special case non-writable built-ins
  4515. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4516. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4517. // next time we run. May want to catch that in the JIT.
  4518. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4519. // These properties are non-writable
  4520. switch (propertyId)
  4521. {
  4522. case Js::PropertyIds::NaN:
  4523. opcode = Js::OpCode::LdNaN;
  4524. break;
  4525. case Js::PropertyIds::Infinity:
  4526. opcode = Js::OpCode::LdInfinity;
  4527. break;
  4528. case Js::PropertyIds::undefined:
  4529. opcode = Js::OpCode::LdUndef;
  4530. break;
  4531. case Js::PropertyIds::__chakraLibrary:
  4532. if (CONFIG_FLAG(LdChakraLib) || CONFIG_FLAG(TestChakraLib))
  4533. {
  4534. opcode = Js::OpCode::LdChakraLib;
  4535. }
  4536. break;
  4537. }
  4538. if (opcode == Js::OpCode::LdRootFld)
  4539. {
  4540. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4541. }
  4542. else
  4543. {
  4544. this->Writer()->Reg1(opcode, lhsLocation);
  4545. }
  4546. }
  4547. }
  4548. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4549. {
  4550. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4551. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4552. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4553. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4554. Js::OpCode op;
  4555. // Now get the property from its slot.
  4556. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4557. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4558. if (envIndex != -1)
  4559. {
  4560. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4561. }
  4562. else if (scopeLocation != Js::Constants::NoRegister &&
  4563. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4564. {
  4565. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4566. }
  4567. else if (scope->HasInnerScopeIndex())
  4568. {
  4569. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4570. }
  4571. else
  4572. {
  4573. AssertOrFailFast(scope->GetIsObject());
  4574. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4575. }
  4576. if (chkBlockVar)
  4577. {
  4578. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4579. }
  4580. }
  4581. else
  4582. {
  4583. if (lhsLocation != sym->GetLocation())
  4584. {
  4585. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4586. }
  4587. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4588. {
  4589. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4590. }
  4591. }
  4592. if (fLabelDefined)
  4593. {
  4594. this->m_writer.MarkLabel(doneLabel);
  4595. }
  4596. }
  4597. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4598. {
  4599. bool tdz = sym->GetIsBlockVar()
  4600. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4601. return tdz || sym->GetIsNonSimpleParameter();
  4602. }
  4603. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4604. {
  4605. // If sym belongs to a parent frame, delete it from the closure environment.
  4606. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4607. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4608. // Otherwise, just return false.
  4609. Js::ByteCodeLabel doneLabel = 0;
  4610. bool fLabelDefined = false;
  4611. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4612. Js::PropertyId envIndex = -1;
  4613. Scope *scope = nullptr;
  4614. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4615. Assert(symScope);
  4616. for (;;)
  4617. {
  4618. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4619. if (scope == this->globalScope)
  4620. {
  4621. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4622. }
  4623. else if (envIndex == -1)
  4624. {
  4625. Assert(funcInfo == scope->GetFunc());
  4626. scopeLocation = scope->GetLocation();
  4627. }
  4628. if (scope == symScope)
  4629. {
  4630. break;
  4631. }
  4632. // Found a scope to which the property may have been added.
  4633. Assert(scope && scope->GetIsDynamic());
  4634. if (!fLabelDefined)
  4635. {
  4636. fLabelDefined = true;
  4637. doneLabel = this->m_writer.DefineLabel();
  4638. }
  4639. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4640. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4641. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4642. if (envIndex != -1)
  4643. {
  4644. this->m_writer.BrEnvProperty(
  4645. Js::OpCode::BrOnNoEnvProperty,
  4646. nextLabel,
  4647. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4648. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4649. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4650. AssertOrFailFast(scope->GetIsObject());
  4651. this->m_writer.SlotI1(
  4652. Js::OpCode::LdEnvObj,
  4653. instLocation,
  4654. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4655. if (unwrapWithObj)
  4656. {
  4657. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4658. }
  4659. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4660. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4661. funcInfo->ReleaseTmpRegister(instLocation);
  4662. }
  4663. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4664. {
  4665. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4666. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4667. Assert(!unwrapWithObj);
  4668. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4669. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4670. }
  4671. else
  4672. {
  4673. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4674. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4675. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4676. if (unwrapWithObj)
  4677. {
  4678. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4679. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4680. scopeLocation = unwrappedScopeLocation;
  4681. }
  4682. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4683. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4684. if (unwrapWithObj)
  4685. {
  4686. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4687. }
  4688. }
  4689. this->m_writer.Br(doneLabel);
  4690. this->m_writer.MarkLabel(nextLabel);
  4691. }
  4692. // Arrived at the scope in which the property was defined.
  4693. if (sym == nullptr || sym->GetIsGlobal())
  4694. {
  4695. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4696. if (this->flags & (fscrEval | fscrImplicitThis))
  4697. {
  4698. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4699. funcInfo->FindOrAddReferencedPropertyId(propertyId), forceStrictModeForClassComputedPropertyName);
  4700. }
  4701. else
  4702. {
  4703. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4704. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4705. }
  4706. }
  4707. else
  4708. {
  4709. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4710. sym->EnsureScopeSlot(this, funcInfo);
  4711. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4712. }
  4713. if (fLabelDefined)
  4714. {
  4715. this->m_writer.MarkLabel(doneLabel);
  4716. }
  4717. }
  4718. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4719. {
  4720. uint cacheId;
  4721. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4722. switch (ldFldOp)
  4723. {
  4724. case Js::OpCode::LdRootFldForTypeOf:
  4725. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4726. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4727. break;
  4728. case Js::OpCode::LdLocalFld:
  4729. case Js::OpCode::ScopedLdFldForTypeOf:
  4730. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4731. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4732. break;
  4733. default:
  4734. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4735. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4736. break;
  4737. }
  4738. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4739. funcInfo->ReleaseTmpRegister(tmpReg);
  4740. }
  4741. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4742. {
  4743. // If sym belongs to a parent frame, delete it from the closure environment.
  4744. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4745. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4746. // Otherwise, just return false
  4747. Js::ByteCodeLabel doneLabel = 0;
  4748. bool fLabelDefined = false;
  4749. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4750. Js::PropertyId envIndex = -1;
  4751. Scope *scope = nullptr;
  4752. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4753. Assert(symScope);
  4754. if (sym && sym->GetIsModuleExportStorage())
  4755. {
  4756. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4757. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4758. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4759. funcInfo->ReleaseTmpRegister(tmpLocation);
  4760. return;
  4761. }
  4762. for (;;)
  4763. {
  4764. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4765. if (scope == this->globalScope)
  4766. {
  4767. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4768. }
  4769. else if (envIndex == -1)
  4770. {
  4771. Assert(funcInfo == scope->GetFunc());
  4772. scopeLocation = scope->GetLocation();
  4773. }
  4774. if (scope == symScope)
  4775. {
  4776. break;
  4777. }
  4778. // Found a scope to which the property may have been added.
  4779. Assert(scope && scope->GetIsDynamic());
  4780. if (!fLabelDefined)
  4781. {
  4782. fLabelDefined = true;
  4783. doneLabel = this->m_writer.DefineLabel();
  4784. }
  4785. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4786. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4787. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4788. if (envIndex != -1)
  4789. {
  4790. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4791. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4792. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4793. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4794. AssertOrFailFast(scope->GetIsObject());
  4795. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4796. instLocation,
  4797. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4798. if (unwrapWithObj)
  4799. {
  4800. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4801. }
  4802. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4803. funcInfo->ReleaseTmpRegister(instLocation);
  4804. }
  4805. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4806. {
  4807. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4808. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4809. Assert(!unwrapWithObj);
  4810. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4811. }
  4812. else
  4813. {
  4814. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4815. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4816. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4817. if (unwrapWithObj)
  4818. {
  4819. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4820. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4821. scopeLocation = unwrappedScopeLocation;
  4822. }
  4823. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4824. if (unwrapWithObj)
  4825. {
  4826. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4827. }
  4828. }
  4829. this->m_writer.Br(doneLabel);
  4830. this->m_writer.MarkLabel(nextLabel);
  4831. }
  4832. // Arrived at the scope in which the property was defined.
  4833. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4834. {
  4835. // Ensure this symbol has a slot if it needs one.
  4836. if (sym->IsInSlot(this, funcInfo))
  4837. {
  4838. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4839. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4840. }
  4841. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4842. }
  4843. else if (sym == nullptr || sym->GetIsGlobal())
  4844. {
  4845. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4846. if (this->flags & fscrEval)
  4847. {
  4848. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4849. {
  4850. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4851. }
  4852. else
  4853. {
  4854. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4855. }
  4856. }
  4857. else if (this->flags & fscrImplicitThis)
  4858. {
  4859. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4860. }
  4861. else
  4862. {
  4863. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4864. }
  4865. }
  4866. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4867. {
  4868. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4869. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4870. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4871. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4872. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4873. Js::OpCode op;
  4874. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4875. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4876. if (envIndex != -1)
  4877. {
  4878. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4879. }
  4880. else if (scopeLocation != Js::Constants::NoRegister &&
  4881. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4882. {
  4883. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4884. }
  4885. else if (scope->HasInnerScopeIndex())
  4886. {
  4887. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4888. }
  4889. else
  4890. {
  4891. AssertOrFailFast(scope->GetIsObject());
  4892. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4893. }
  4894. if (chkBlockVar)
  4895. {
  4896. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4897. }
  4898. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4899. funcInfo->ReleaseTmpRegister(tmpLocation);
  4900. }
  4901. else
  4902. {
  4903. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4904. }
  4905. if (fLabelDefined)
  4906. {
  4907. this->m_writer.MarkLabel(doneLabel);
  4908. }
  4909. }
  4910. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  4911. {
  4912. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4913. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4914. // remain local to the eval code.
  4915. Assert(pnodeBlock->nop == knopBlock);
  4916. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4917. if (!(this->flags & fscrEvalCode))
  4918. {
  4919. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4920. {
  4921. FuncInfo *funcInfo = this->TopFuncInfo();
  4922. Symbol *sym = pnode->AsParseNodeVar()->sym;
  4923. Assert(sym->GetIsGlobal());
  4924. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4925. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4926. });
  4927. }
  4928. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo, bool isFncDecl = false)
  4929. {
  4930. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4931. // Global function declarations must pass #sec-candeclareglobalfunction
  4932. // which is enforced by EnsureCanDeclGloFunc
  4933. if (isFncDecl)
  4934. {
  4935. this->m_writer.ElementRootU(Js::OpCode::EnsureCanDeclGloFunc, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4936. }
  4937. if (this->flags & fscrEval)
  4938. {
  4939. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4940. {
  4941. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4942. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4943. }
  4944. }
  4945. else
  4946. {
  4947. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4948. }
  4949. };
  4950. // scan for function declarations
  4951. // these behave like "var" declarations
  4952. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  4953. {
  4954. switch (pnode->nop) {
  4955. case knopFncDecl:
  4956. if (pnode->AsParseNodeFnc()->IsDeclaration())
  4957. {
  4958. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo, true);
  4959. }
  4960. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  4961. break;
  4962. case knopBlock:
  4963. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  4964. break;
  4965. case knopCatch:
  4966. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  4967. break;
  4968. case knopWith:
  4969. pnode = pnode->AsParseNodeWith()->pnodeNext;
  4970. break;
  4971. default:
  4972. Assert(UNREACHED);
  4973. }
  4974. }
  4975. // scan for var declarations
  4976. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  4977. {
  4978. Symbol* sym = pnode->AsParseNodeVar()->sym;
  4979. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  4980. continue;
  4981. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4982. {
  4983. // The init node was bound to the catch object, because it's inside a catch and has the
  4984. // same name as the catch object. But we want to define a user var at function scope,
  4985. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4986. // This also applies to a var declaration in the same scope as a let declaration.
  4987. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4988. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  4989. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4990. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4991. }
  4992. Assert(sym->GetIsGlobal());
  4993. if (sym->GetSymbolType() == STVariable)
  4994. {
  4995. emitRedeclCheck(sym, funcInfo);
  4996. }
  4997. }
  4998. }
  4999. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  5000. {
  5001. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5002. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5003. {
  5004. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5005. });
  5006. }
  5007. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5008. {
  5009. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5010. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5011. {
  5012. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  5013. });
  5014. }
  5015. void ByteCodeGenerator::RecordAllBigIntConstants(FuncInfo * funcInfo)
  5016. {
  5017. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5018. funcInfo->bigintToRegister.Map([byteCodeFunction](ParseNode* pnode, Js::RegSlot location)
  5019. {
  5020. IdentPtr pid = pnode->AsParseNodeBigInt()->pid;
  5021. byteCodeFunction->RecordBigIntConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pnode->AsParseNodeBigInt()->isNegative);
  5022. });
  5023. }
  5024. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5025. {
  5026. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5027. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5028. {
  5029. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5030. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5031. rawArray->Freeze();
  5032. Js::RecyclableObject* callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5033. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5034. callsiteObject->Freeze();
  5035. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5036. });
  5037. }
  5038. bool IsApplyArgs(ParseNodeCall* callNode)
  5039. {
  5040. ParseNode* target = callNode->pnodeTarget;
  5041. ParseNode* args = callNode->pnodeArgs;
  5042. if ((target != nullptr) && (target->nop == knopDot))
  5043. {
  5044. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5045. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5046. {
  5047. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5048. if (nameNode != nullptr)
  5049. {
  5050. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5051. if (nameIsApply && args != nullptr && args->nop == knopList)
  5052. {
  5053. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5054. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5055. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5056. {
  5057. return arg2->AsParseNodeName()->sym->IsArguments();
  5058. }
  5059. }
  5060. }
  5061. }
  5062. }
  5063. return false;
  5064. }
  5065. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5066. {
  5067. if ((pnode == nullptr) || (!applyCheck->matches))
  5068. {
  5069. return;
  5070. }
  5071. if (pnode->nop == knopCall)
  5072. {
  5073. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5074. {
  5075. if (!applyCheck->insideApplyCall)
  5076. {
  5077. applyCheck->matches = false;
  5078. }
  5079. applyCheck->insideApplyCall = false;
  5080. }
  5081. }
  5082. }
  5083. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5084. {
  5085. if ((pnode == nullptr) || (!applyCheck->matches))
  5086. {
  5087. return;
  5088. }
  5089. switch (pnode->nop)
  5090. {
  5091. case knopName:
  5092. {
  5093. Symbol* sym = pnode->AsParseNodeName()->sym;
  5094. if (sym != nullptr)
  5095. {
  5096. if (sym->IsArguments())
  5097. {
  5098. if (!applyCheck->insideApplyCall)
  5099. {
  5100. applyCheck->matches = false;
  5101. }
  5102. }
  5103. }
  5104. break;
  5105. }
  5106. case knopCall:
  5107. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5108. {
  5109. // no nested apply calls
  5110. if (applyCheck->insideApplyCall)
  5111. {
  5112. applyCheck->matches = false;
  5113. }
  5114. else
  5115. {
  5116. applyCheck->insideApplyCall = true;
  5117. applyCheck->sawApply = true;
  5118. pnode->AsParseNodeCall()->isApplyCall = true;
  5119. }
  5120. }
  5121. break;
  5122. }
  5123. }
  5124. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5125. {
  5126. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5127. // side-effects in the argument list. We need to know this so that the call target
  5128. // operands can be preserved if necessary.
  5129. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5130. // but we can be more precise if we need to be.
  5131. if (pSideEffect)
  5132. {
  5133. *pSideEffect = FALSE;
  5134. }
  5135. unsigned int argCount = 1;
  5136. if (pnode != nullptr)
  5137. {
  5138. while (pnode->nop == knopList)
  5139. {
  5140. argCount++;
  5141. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5142. {
  5143. *pSideEffect = TRUE;
  5144. }
  5145. pnode = pnode->AsParseNodeBin()->pnode2;
  5146. }
  5147. argCount++;
  5148. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5149. {
  5150. *pSideEffect = TRUE;
  5151. }
  5152. }
  5153. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5154. return argCount;
  5155. }
  5156. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5157. {
  5158. // Save a local name to a register other than its home location.
  5159. // This guards against side-effects in cases like x.foo(x = bar()).
  5160. Symbol *sym = nullptr;
  5161. if (pnode->nop == knopName)
  5162. {
  5163. sym = pnode->AsParseNodeName()->sym;
  5164. }
  5165. else if (pnode->nop == knopComputedName)
  5166. {
  5167. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5168. if (pnode1->nop == knopName)
  5169. {
  5170. sym = pnode1->AsParseNodeName()->sym;
  5171. }
  5172. }
  5173. if (sym == nullptr)
  5174. {
  5175. return;
  5176. }
  5177. // If the target is a local being kept in its home location,
  5178. // protect the target's value in the event the home location is overwritten.
  5179. if (pnode->location != Js::Constants::NoRegister &&
  5180. sym->GetScope()->GetFunc() == funcInfo &&
  5181. pnode->location == sym->GetLocation())
  5182. {
  5183. pnode->location = funcInfo->AcquireTmpRegister();
  5184. }
  5185. }
  5186. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5187. {
  5188. Assert(TopFuncInfo() != nullptr);
  5189. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5190. }
  5191. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5192. {
  5193. m_writer.EndStatement(node);
  5194. }
  5195. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5196. {
  5197. Assert(TopFuncInfo() != nullptr);
  5198. m_writer.StartSubexpression(node);
  5199. }
  5200. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5201. {
  5202. m_writer.EndSubexpression(node);
  5203. }
  5204. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5205. {
  5206. // Generate code for the LHS of an assignment.
  5207. switch (pnode->nop)
  5208. {
  5209. case knopDot:
  5210. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5211. break;
  5212. case knopIndex:
  5213. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5214. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5215. break;
  5216. case knopName:
  5217. break;
  5218. case knopArrayPattern:
  5219. case knopObjectPattern:
  5220. break;
  5221. case knopCall:
  5222. case knopNew:
  5223. // Emit the operands of a call that will be used as a LHS.
  5224. // These have to be emitted before the RHS, but they have to persist until
  5225. // the end of the expression.
  5226. // Emit the call target operands first.
  5227. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5228. {
  5229. case knopDot:
  5230. case knopIndex:
  5231. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5232. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5233. break;
  5234. case knopName:
  5235. {
  5236. Symbol *sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5237. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5238. {
  5239. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5240. }
  5241. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5242. {
  5243. // Can't get the value from the assigned register, so load it here.
  5244. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5245. }
  5246. else
  5247. {
  5248. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5249. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5250. // must manually check here.
  5251. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5252. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5253. }
  5254. break;
  5255. }
  5256. default:
  5257. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5258. break;
  5259. }
  5260. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5261. if (pnode->AsParseNodeCall()->pnodeArgs)
  5262. {
  5263. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5264. while (pnodeArg->nop == knopList)
  5265. {
  5266. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5267. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5268. }
  5269. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5270. }
  5271. if (pnode->AsParseNodeCall()->isSuperCall)
  5272. {
  5273. Emit(pnode->AsParseNodeSuperCall()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5274. Emit(pnode->AsParseNodeSuperCall()->pnodeNewTarget, byteCodeGenerator, funcInfo, false);
  5275. }
  5276. break;
  5277. default:
  5278. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5279. break;
  5280. }
  5281. }
  5282. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5283. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5284. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5285. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5286. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5287. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5288. {
  5289. switch (elem->nop)
  5290. {
  5291. case knopVarDecl:
  5292. case knopLetDecl:
  5293. case knopConstDecl:
  5294. // We manually need to set NeedDeclaration since the node won't be visited.
  5295. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5296. break;
  5297. default:
  5298. EmitReference(elem, byteCodeGenerator, funcInfo);
  5299. }
  5300. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5301. funcInfo->ReleaseReference(elem);
  5302. }
  5303. void EmitDestructuredRestArray(ParseNode *elem,
  5304. Js::RegSlot iteratorLocation,
  5305. Js::RegSlot shouldCallReturnFunctionLocation,
  5306. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5307. ByteCodeGenerator *byteCodeGenerator,
  5308. FuncInfo *funcInfo)
  5309. {
  5310. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5311. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5312. if (isAssignmentTarget)
  5313. {
  5314. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5315. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5316. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5317. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5318. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5319. }
  5320. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5321. Js::OpCode::NewScArray,
  5322. restArrayLocation,
  5323. ByteCodeGenerator::DefaultArraySize);
  5324. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5325. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5326. // convey this is live on the back edge.
  5327. // As a workaround, we have a persistent var reg that is used for the loop counter
  5328. Js::RegSlot counterLocation = elem->location;
  5329. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5330. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5331. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5332. // loopTop:
  5333. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5334. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5335. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5336. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5337. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5338. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5339. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5340. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5341. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5342. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5343. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5344. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5345. byteCodeGenerator->Writer()->Element(
  5346. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5347. valueLocation, restArrayLocation, counterLocation);
  5348. funcInfo->ReleaseTmpRegister(valueLocation);
  5349. funcInfo->ReleaseTmpRegister(doneLocation);
  5350. funcInfo->ReleaseTmpRegister(itemLocation);
  5351. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5352. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5353. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5354. byteCodeGenerator->Writer()->Br(loopTop);
  5355. // iteratorDone:
  5356. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5357. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5358. if (isAssignmentTarget)
  5359. {
  5360. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5361. funcInfo->ReleaseReference(restElem);
  5362. }
  5363. else
  5364. {
  5365. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5366. }
  5367. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5368. }
  5369. void EmitDestructuredArray(
  5370. ParseNode *lhs,
  5371. Js::RegSlot rhsLocation,
  5372. ByteCodeGenerator *byteCodeGenerator,
  5373. FuncInfo *funcInfo);
  5374. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5375. {
  5376. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5377. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5378. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5379. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5380. }
  5381. /*
  5382. EmitDestructuredArray(lhsArray, rhs):
  5383. iterator = rhs[@@iterator]
  5384. if lhsArray empty
  5385. return
  5386. for each element in lhsArray except rest
  5387. value = iterator.next()
  5388. if element is a nested destructured array
  5389. EmitDestructuredArray(element, value)
  5390. else
  5391. if value is undefined and there is an initializer
  5392. evaluate initializer
  5393. evaluate element reference
  5394. element = initializer
  5395. else
  5396. element = value
  5397. if lhsArray has a rest element
  5398. rest = []
  5399. while iterator is not done
  5400. value = iterator.next()
  5401. rest.append(value)
  5402. */
  5403. void EmitDestructuredArrayCore(
  5404. ParseNode *list,
  5405. Js::RegSlot iteratorLocation,
  5406. Js::RegSlot shouldCallReturnFunctionLocation,
  5407. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5408. ByteCodeGenerator *byteCodeGenerator,
  5409. FuncInfo *funcInfo
  5410. )
  5411. {
  5412. Assert(list != nullptr);
  5413. ParseNode *elem = nullptr;
  5414. while (list != nullptr)
  5415. {
  5416. ParseNode *init = nullptr;
  5417. if (list->nop == knopList)
  5418. {
  5419. elem = list->AsParseNodeBin()->pnode1;
  5420. }
  5421. else
  5422. {
  5423. elem = list;
  5424. }
  5425. if (elem->nop == knopEllipsis)
  5426. {
  5427. break;
  5428. }
  5429. switch (elem->nop)
  5430. {
  5431. case knopAsg:
  5432. // An assignment node will always have an initializer
  5433. init = elem->AsParseNodeBin()->pnode2;
  5434. elem = elem->AsParseNodeBin()->pnode1;
  5435. break;
  5436. case knopVarDecl:
  5437. case knopLetDecl:
  5438. case knopConstDecl:
  5439. init = elem->AsParseNodeVar()->pnodeInit;
  5440. break;
  5441. default:
  5442. break;
  5443. }
  5444. byteCodeGenerator->StartStatement(elem);
  5445. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5446. if (isAssignmentTarget)
  5447. {
  5448. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5449. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5450. EmitReference(elem, byteCodeGenerator, funcInfo);
  5451. }
  5452. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5453. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5454. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5455. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5456. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5457. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5458. if (elem->nop == knopEmpty)
  5459. {
  5460. if (list->nop == knopList)
  5461. {
  5462. list = list->AsParseNodeBin()->pnode2;
  5463. funcInfo->ReleaseTmpRegister(doneLocation);
  5464. funcInfo->ReleaseTmpRegister(itemLocation);
  5465. continue;
  5466. }
  5467. else
  5468. {
  5469. Assert(list->nop == knopEmpty);
  5470. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5471. funcInfo->ReleaseTmpRegister(doneLocation);
  5472. funcInfo->ReleaseTmpRegister(itemLocation);
  5473. break;
  5474. }
  5475. }
  5476. // If the iterator hasn't completed, skip assigning undefined.
  5477. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5478. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5479. // We're not done with the iterator, so assign the .next() value.
  5480. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5481. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5482. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5483. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5484. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5485. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5486. // iteratorAlreadyDone:
  5487. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5488. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5489. // beforeDefaultAssign:
  5490. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5491. if (elem->IsPattern())
  5492. {
  5493. // If we get an undefined value and have an initializer, use it in place of undefined.
  5494. if (init != nullptr)
  5495. {
  5496. /*
  5497. the IR builder uses two symbols for a temp register in the if else path
  5498. R9 <- R3
  5499. if (...)
  5500. R9 <- R2
  5501. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5502. hence we have to create a new temp
  5503. TEMP REG USED TO FIX THIS PRODUCES THIS
  5504. R9 <- R3
  5505. if (BrEq_A R9, R3)
  5506. R10 <- R2 :
  5507. else
  5508. R10 <- R9 : skipdefault
  5509. ... = R10[@@iterator] : loadIter
  5510. */
  5511. // Temp Register
  5512. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5513. byteCodeGenerator->StartStatement(init);
  5514. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5515. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5516. // check value is undefined
  5517. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5518. // Evaluate the default expression and assign it.
  5519. Emit(init, byteCodeGenerator, funcInfo, false);
  5520. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5521. funcInfo->ReleaseLoc(init);
  5522. // jmp to loadIter
  5523. byteCodeGenerator->Writer()->Br(loadIter);
  5524. // skipDefault:
  5525. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5526. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5527. // loadIter:
  5528. // @@iterator
  5529. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5530. byteCodeGenerator->EndStatement(init);
  5531. if (elem->nop == knopObjectPattern)
  5532. {
  5533. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5534. }
  5535. else
  5536. {
  5537. // Recursively emit a destructured array using the current .next() as the RHS.
  5538. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5539. }
  5540. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5541. }
  5542. else
  5543. {
  5544. if (elem->nop == knopObjectPattern)
  5545. {
  5546. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5547. }
  5548. else
  5549. {
  5550. // Recursively emit a destructured array using the current .next() as the RHS.
  5551. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5552. }
  5553. }
  5554. }
  5555. else
  5556. {
  5557. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5558. }
  5559. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5560. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5561. if (list->nop != knopList)
  5562. {
  5563. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5564. }
  5565. funcInfo->ReleaseTmpRegister(valueLocation);
  5566. funcInfo->ReleaseTmpRegister(doneLocation);
  5567. funcInfo->ReleaseTmpRegister(itemLocation);
  5568. if (isAssignmentTarget)
  5569. {
  5570. funcInfo->ReleaseReference(elem);
  5571. }
  5572. byteCodeGenerator->EndStatement(elem);
  5573. if (list->nop == knopList)
  5574. {
  5575. list = list->AsParseNodeBin()->pnode2;
  5576. }
  5577. else
  5578. {
  5579. break;
  5580. }
  5581. }
  5582. // If we saw a rest element, emit the rest array.
  5583. if (elem != nullptr && elem->nop == knopEllipsis)
  5584. {
  5585. EmitDestructuredRestArray(elem,
  5586. iteratorLocation,
  5587. shouldCallReturnFunctionLocation,
  5588. shouldCallReturnFunctionLocationFinally,
  5589. byteCodeGenerator,
  5590. funcInfo);
  5591. }
  5592. }
  5593. // Generating
  5594. // try {
  5595. // CallIteratorClose
  5596. // } catch (e) {
  5597. // do nothing
  5598. // }
  5599. void EmitTryCatchAroundClose(
  5600. Js::RegSlot iteratorLocation,
  5601. Js::ByteCodeLabel endLabel,
  5602. ByteCodeGenerator *byteCodeGenerator,
  5603. FuncInfo *funcInfo)
  5604. {
  5605. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5606. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5607. //
  5608. // There is no need to add TryScopeRecord here as we are going to call 'return' function and there is not yield expression here.
  5609. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5610. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5611. byteCodeGenerator->Writer()->Br(endLabel);
  5612. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5613. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5614. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5615. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5616. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5617. }
  5618. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5619. {
  5620. Js::OpCode op;
  5621. Js::ByteCodeLabel label;
  5622. Js::RegSlot reg1;
  5623. Js::RegSlot reg2;
  5624. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5625. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5626. };
  5627. // Generating
  5628. // catch(e) {
  5629. // if (shouldCallReturn)
  5630. // CallReturnWhichWrappedByTryCatch
  5631. // throw e;
  5632. // }
  5633. void EmitTopLevelCatch(Js::ByteCodeLabel catchLabel,
  5634. Js::RegSlot iteratorLocation,
  5635. Js::RegSlot shouldCallReturnLocation,
  5636. Js::RegSlot shouldCallReturnLocationFinally,
  5637. ByteCodeGenerator *byteCodeGenerator,
  5638. FuncInfo *funcInfo)
  5639. {
  5640. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5641. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5642. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5643. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5644. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5645. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5646. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  5647. if (funcInfo->byteCodeFunction->IsCoroutine())
  5648. {
  5649. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  5650. }
  5651. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5652. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5653. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnLocationFinally);
  5654. EmitTryCatchAroundClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo);
  5655. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5656. // Rethrow the exception.
  5657. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5658. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5659. if (funcInfo->byteCodeFunction->IsCoroutine())
  5660. {
  5661. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5662. }
  5663. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5664. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5665. }
  5666. // Generating
  5667. // finally {
  5668. // if (shouldCallReturn)
  5669. // CallReturn
  5670. // }
  5671. void EmitTopLevelFinally(Js::ByteCodeLabel finallyLabel,
  5672. Js::RegSlot iteratorLocation,
  5673. Js::RegSlot shouldCallReturnLocation,
  5674. Js::RegSlot yieldExceptionLocation,
  5675. Js::RegSlot yieldOffsetLocation,
  5676. ByteCodeGenerator *byteCodeGenerator,
  5677. FuncInfo *funcInfo)
  5678. {
  5679. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5680. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5681. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5682. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5683. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5684. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5685. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5686. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5687. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, yieldExceptionLocation, yieldOffsetLocation);
  5688. if (isCoroutine)
  5689. {
  5690. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  5691. }
  5692. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5693. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5694. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5695. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5696. if (isCoroutine)
  5697. {
  5698. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5699. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5700. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5701. }
  5702. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5703. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5704. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5705. }
  5706. void EmitCatchAndFinallyBlocks(Js::ByteCodeLabel catchLabel,
  5707. Js::ByteCodeLabel finallyLabel,
  5708. Js::RegSlot iteratorLocation,
  5709. Js::RegSlot shouldCallReturnFunctionLocation,
  5710. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5711. Js::RegSlot yieldExceptionLocation,
  5712. Js::RegSlot yieldOffsetLocation,
  5713. ByteCodeGenerator *byteCodeGenerator,
  5714. FuncInfo *funcInfo
  5715. )
  5716. {
  5717. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5718. if (isCoroutine)
  5719. {
  5720. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5721. }
  5722. EmitTopLevelCatch(catchLabel,
  5723. iteratorLocation,
  5724. shouldCallReturnFunctionLocation,
  5725. shouldCallReturnFunctionLocationFinally,
  5726. byteCodeGenerator,
  5727. funcInfo);
  5728. if (isCoroutine)
  5729. {
  5730. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5731. }
  5732. EmitTopLevelFinally(finallyLabel,
  5733. iteratorLocation,
  5734. shouldCallReturnFunctionLocationFinally,
  5735. yieldExceptionLocation,
  5736. yieldOffsetLocation,
  5737. byteCodeGenerator,
  5738. funcInfo);
  5739. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  5740. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  5741. }
  5742. // Emit a wrapper try..finaly block around the destructuring elements
  5743. void EmitDestructuredArray(
  5744. ParseNode *lhs,
  5745. Js::RegSlot rhsLocation,
  5746. ByteCodeGenerator *byteCodeGenerator,
  5747. FuncInfo *funcInfo)
  5748. {
  5749. byteCodeGenerator->StartStatement(lhs);
  5750. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5751. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5752. Assert(lhs->nop == knopArrayPattern);
  5753. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  5754. if (list == nullptr)
  5755. { // Handline this case ([] = obj);
  5756. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5757. // No elements to bind or assign.
  5758. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5759. byteCodeGenerator->EndStatement(lhs);
  5760. return;
  5761. }
  5762. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  5763. // this variable will be set to true.
  5764. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  5765. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  5766. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5767. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5768. byteCodeGenerator->SetHasFinally(true);
  5769. byteCodeGenerator->SetHasTry(true);
  5770. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  5771. Js::RegSlot regException = Js::Constants::NoRegister;
  5772. Js::RegSlot regOffset = Js::Constants::NoRegister;
  5773. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5774. if (isCoroutine)
  5775. {
  5776. regException = funcInfo->AcquireTmpRegister();
  5777. regOffset = funcInfo->AcquireTmpRegister();
  5778. }
  5779. // Insert try node here
  5780. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  5781. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5782. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5783. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  5784. if (isCoroutine)
  5785. {
  5786. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  5787. tryRecForTryFinally.reg1 = regException;
  5788. tryRecForTryFinally.reg2 = regOffset;
  5789. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  5790. }
  5791. else
  5792. {
  5793. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  5794. }
  5795. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5796. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  5797. if (isCoroutine)
  5798. {
  5799. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  5800. }
  5801. EmitDestructuredArrayCore(list,
  5802. iteratorLocation,
  5803. shouldCallReturnFunctionLocation,
  5804. shouldCallReturnFunctionLocationFinally,
  5805. byteCodeGenerator,
  5806. funcInfo);
  5807. EmitCatchAndFinallyBlocks(catchLabel,
  5808. finallyLabel,
  5809. iteratorLocation,
  5810. shouldCallReturnFunctionLocation,
  5811. shouldCallReturnFunctionLocationFinally,
  5812. regException,
  5813. regOffset,
  5814. byteCodeGenerator,
  5815. funcInfo);
  5816. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5817. byteCodeGenerator->EndStatement(lhs);
  5818. }
  5819. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5820. Js::RegSlot objectLocation,
  5821. Js::RegSlot computedPropIdArrLocation,
  5822. uint32 *computedIndex,
  5823. bool hasRest,
  5824. ParseNodePtr nameNode,
  5825. ByteCodeGenerator* byteCodeGenerator,
  5826. FuncInfo* funcInfo)
  5827. {
  5828. Assert(nameNode != nullptr);
  5829. if (nameNode->nop == knopComputedName)
  5830. {
  5831. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  5832. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5833. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5834. if (hasRest)
  5835. {
  5836. byteCodeGenerator->Writer()->Slot(Js::OpCode::StPropIdArrFromVar, pnode1->location, computedPropIdArrLocation, *computedIndex);
  5837. (*computedIndex)++;
  5838. }
  5839. funcInfo->ReleaseLoc(pnode1);
  5840. }
  5841. else
  5842. {
  5843. Assert(nameNode->nop == knopStr);
  5844. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5845. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5846. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5847. }
  5848. }
  5849. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5850. Js::RegSlot rhsLocation,
  5851. ParseNodePtr initializer,
  5852. bool isNonPatternAssignmentTarget,
  5853. ByteCodeGenerator *byteCodeGenerator,
  5854. FuncInfo *funcInfo)
  5855. {
  5856. // If we have initializer we need to see if the destructured value is undefined or not - if it is undefined we need to assign initializer
  5857. Js::ByteCodeLabel useDefault = -1;
  5858. Js::ByteCodeLabel end = -1;
  5859. Js::RegSlot rhsLocationTmp = rhsLocation;
  5860. if (initializer != nullptr)
  5861. {
  5862. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5863. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5864. end = byteCodeGenerator->Writer()->DefineLabel();
  5865. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5866. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5867. byteCodeGenerator->Writer()->Br(end);
  5868. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5869. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5870. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5871. funcInfo->ReleaseLoc(initializer);
  5872. byteCodeGenerator->Writer()->MarkLabel(end);
  5873. }
  5874. if (lhsElementNode->nop == knopArrayPattern)
  5875. {
  5876. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5877. }
  5878. else if (lhsElementNode->nop == knopObjectPattern)
  5879. {
  5880. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5881. }
  5882. else if (isNonPatternAssignmentTarget)
  5883. {
  5884. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5885. }
  5886. else
  5887. {
  5888. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5889. }
  5890. if (initializer != nullptr)
  5891. {
  5892. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5893. }
  5894. }
  5895. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5896. Js::RegSlot rhsLocation,
  5897. Js::RegSlot propIdArrLocation,
  5898. Js::RegSlot computedPropIdArrLocation,
  5899. uint32 *computedIndex,
  5900. bool hasRest,
  5901. ByteCodeGenerator *byteCodeGenerator,
  5902. FuncInfo *funcInfo)
  5903. {
  5904. Assert(memberNode->nop == knopObjectPatternMember || memberNode->nop == knopEllipsis);
  5905. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5906. ParseNodePtr lhsElementNode = nullptr;
  5907. if (memberNode->nop == knopObjectPatternMember)
  5908. {
  5909. EmitNameInvoke(nameLocation, rhsLocation, computedPropIdArrLocation,
  5910. computedIndex, hasRest, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  5911. // Imagine we are transforming
  5912. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5913. lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  5914. }
  5915. else
  5916. {
  5917. // memberNode->nop == knopEllipsis, aka we are performing Rest operation
  5918. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, nameLocation);
  5919. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Restify, rhsLocation, nameLocation, propIdArrLocation, computedPropIdArrLocation);
  5920. lhsElementNode = memberNode->AsParseNodeUni()->pnode1;
  5921. }
  5922. ParseNodePtr init = nullptr;
  5923. if (lhsElementNode->IsVarLetOrConst())
  5924. {
  5925. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  5926. }
  5927. else if (lhsElementNode->nop == knopAsg)
  5928. {
  5929. init = lhsElementNode->AsParseNodeBin()->pnode2;
  5930. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  5931. }
  5932. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  5933. funcInfo->ReleaseTmpRegister(nameLocation);
  5934. }
  5935. void EmitObjectPropertyIdsToArray(ByteCodeGenerator *byteCodeGenerator,
  5936. Js::PropertyId *ids,
  5937. ParseNodePtr memberNodes,
  5938. uint32 staticCount,
  5939. bool *hasComputedProps)
  5940. {
  5941. uint32 index = 0;
  5942. Parser::ForEachItemInList(memberNodes, [&](ParseNodePtr current) {
  5943. if (current->nop != knopEllipsis)
  5944. {
  5945. ParseNodePtr nameNode = current->AsParseNodeBin()->pnode1;
  5946. Assert(nameNode != nullptr);
  5947. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  5948. if (nameNode->nop == knopStr)
  5949. {
  5950. if (index >= staticCount)
  5951. {
  5952. Js::Throw::InternalError();
  5953. return;
  5954. }
  5955. ids[index] = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5956. index++;
  5957. }
  5958. else
  5959. {
  5960. *hasComputedProps = true;
  5961. }
  5962. }
  5963. });
  5964. }
  5965. void EmitDestructuredObject(ParseNode *lhs,
  5966. Js::RegSlot rhsLocationOrig,
  5967. ByteCodeGenerator *byteCodeGenerator,
  5968. FuncInfo *funcInfo)
  5969. {
  5970. Assert(lhs->nop == knopObjectPattern);
  5971. ParseNodeObjLit *pnodeObjLit = lhs->AsParseNodeObjLit();
  5972. ParseNodePtr pnode1 = pnodeObjLit->pnode1;
  5973. uint32 staticCount = pnodeObjLit->staticCount;
  5974. uint32 computedCount = pnodeObjLit->computedCount;
  5975. bool hasRest = pnodeObjLit->hasRest;
  5976. bool hasComputedProps = false;
  5977. byteCodeGenerator->StartStatement(lhs);
  5978. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5979. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  5980. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  5981. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  5982. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  5983. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5984. if (pnode1 != nullptr)
  5985. {
  5986. Js::RegSlot propIdArrLocation = Js::Constants::NoRegister;
  5987. Js::RegSlot computedPropIdArrLocation = Js::Constants::NoRegister;
  5988. if (hasRest)
  5989. {
  5990. uint extraAlloc = UInt32Math::Mul(staticCount, sizeof(Js::PropertyId));
  5991. uint auxSize = UInt32Math::Add(sizeof(Js::PropertyIdArray), extraAlloc);
  5992. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::PropertyIdArray, staticCount, 0);
  5993. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember || pnode1->nop == knopEllipsis);
  5994. EmitObjectPropertyIdsToArray(byteCodeGenerator, propIds->elements, pnode1, staticCount, &hasComputedProps);
  5995. // Load static PropertyIdArray here
  5996. propIdArrLocation = funcInfo->AcquireTmpRegister();
  5997. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::LdPropIds, propIdArrLocation, propIds, auxSize, staticCount);
  5998. if (hasComputedProps)
  5999. {
  6000. computedPropIdArrLocation = funcInfo->AcquireTmpRegister();
  6001. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewPropIdArrForCompProps, computedPropIdArrLocation, computedCount);
  6002. }
  6003. else
  6004. {
  6005. computedPropIdArrLocation = propIdArrLocation;
  6006. }
  6007. }
  6008. uint32 index = 0;
  6009. Parser::ForEachItemInList(pnode1, [&](ParseNodePtr memberNode) {
  6010. EmitDestructuredObjectMember(memberNode, rhsLocation, propIdArrLocation, computedPropIdArrLocation,
  6011. &index, hasRest, byteCodeGenerator, funcInfo);
  6012. });
  6013. if (hasRest)
  6014. {
  6015. if (hasComputedProps)
  6016. {
  6017. funcInfo->ReleaseTmpRegister(computedPropIdArrLocation);
  6018. }
  6019. funcInfo->ReleaseTmpRegister(propIdArrLocation);
  6020. }
  6021. }
  6022. funcInfo->ReleaseTmpRegister(rhsLocation);
  6023. byteCodeGenerator->EndStatement(lhs);
  6024. }
  6025. void EmitAssignment(
  6026. ParseNode *asgnNode,
  6027. ParseNode *lhs,
  6028. Js::RegSlot rhsLocation,
  6029. ByteCodeGenerator *byteCodeGenerator,
  6030. FuncInfo *funcInfo)
  6031. {
  6032. switch (lhs->nop)
  6033. {
  6034. // assignment to a local or global variable
  6035. case knopVarDecl:
  6036. case knopLetDecl:
  6037. case knopConstDecl:
  6038. {
  6039. Symbol *sym = lhs->AsParseNodeVar()->sym;
  6040. Assert(sym != nullptr);
  6041. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  6042. break;
  6043. }
  6044. case knopName:
  6045. {
  6046. // Special names like 'this' or 'new.target' cannot be assigned to
  6047. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  6048. if (pnodeNameLhs->IsSpecialName())
  6049. {
  6050. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6051. }
  6052. else
  6053. {
  6054. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  6055. }
  6056. break;
  6057. }
  6058. // x.y =
  6059. case knopDot:
  6060. {
  6061. // PutValue(x, "y", rhs)
  6062. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6063. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6064. {
  6065. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6066. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  6067. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6068. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  6069. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  6070. }
  6071. else
  6072. {
  6073. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  6074. byteCodeGenerator->Writer()->PatchableProperty(
  6075. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false, byteCodeGenerator->forceStrictModeForClassComputedPropertyName), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6076. }
  6077. break;
  6078. }
  6079. case knopIndex:
  6080. {
  6081. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  6082. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6083. {
  6084. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  6085. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  6086. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  6087. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6088. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6089. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  6090. }
  6091. byteCodeGenerator->Writer()->Element(
  6092. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  6093. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  6094. break;
  6095. }
  6096. case knopObjectPattern:
  6097. {
  6098. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6099. // Copy the rhs value to be the result of the assignment if needed.
  6100. if (asgnNode != nullptr)
  6101. {
  6102. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6103. }
  6104. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6105. }
  6106. case knopArrayPattern:
  6107. {
  6108. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6109. // Copy the rhs value to be the result of the assignment if needed.
  6110. if (asgnNode != nullptr)
  6111. {
  6112. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6113. }
  6114. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6115. }
  6116. case knopArray:
  6117. case knopObject:
  6118. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6119. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6120. // down early vs. runtime errors for destructuring.
  6121. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6122. break;
  6123. default:
  6124. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6125. break;
  6126. }
  6127. if (asgnNode != nullptr)
  6128. {
  6129. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6130. if (asgnNode->location != rhsLocation)
  6131. {
  6132. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6133. }
  6134. }
  6135. }
  6136. void EmitLoad(
  6137. ParseNode *lhs,
  6138. ByteCodeGenerator *byteCodeGenerator,
  6139. FuncInfo *funcInfo)
  6140. {
  6141. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6142. // in the process.
  6143. // We usually get here as part of an op-equiv expression: x.y += z;
  6144. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6145. switch (lhs->nop)
  6146. {
  6147. // load of a local or global variable
  6148. case knopName:
  6149. {
  6150. funcInfo->AcquireLoc(lhs);
  6151. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6152. break;
  6153. }
  6154. // = x.y
  6155. case knopDot:
  6156. {
  6157. // get field id for "y"
  6158. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6159. funcInfo->AcquireLoc(lhs);
  6160. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6161. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6162. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6163. break;
  6164. }
  6165. case knopIndex:
  6166. funcInfo->AcquireLoc(lhs);
  6167. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6168. byteCodeGenerator->Writer()->Element(
  6169. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6170. break;
  6171. // f(x) +=
  6172. case knopCall:
  6173. {
  6174. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6175. if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6176. {
  6177. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6178. Assert(CountArguments(args) == 2); // import() takes one argument
  6179. Emit(args, byteCodeGenerator, funcInfo, false);
  6180. funcInfo->ReleaseLoc(args);
  6181. funcInfo->AcquireLoc(pnodeCallLhs);
  6182. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6183. }
  6184. else
  6185. {
  6186. funcInfo->AcquireLoc(pnodeCallLhs);
  6187. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6188. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6189. }
  6190. break;
  6191. }
  6192. default:
  6193. funcInfo->AcquireLoc(lhs);
  6194. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6195. break;
  6196. }
  6197. }
  6198. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6199. {
  6200. if (pnode != nullptr)
  6201. {
  6202. while (pnode->nop == knopList)
  6203. {
  6204. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6205. pnode = pnode->AsParseNodeBin()->pnode2;
  6206. }
  6207. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6208. }
  6209. }
  6210. void EmitOneArg(
  6211. ParseNode *pnode,
  6212. BOOL fAssignRegs,
  6213. ByteCodeGenerator *byteCodeGenerator,
  6214. FuncInfo *funcInfo,
  6215. Js::ProfileId callSiteId,
  6216. Js::ArgSlot &argIndex,
  6217. Js::ArgSlot &spreadIndex,
  6218. Js::RegSlot argTempLocation,
  6219. bool emitProfiledArgout,
  6220. Js::AuxArray<uint32> *spreadIndices = nullptr
  6221. )
  6222. {
  6223. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6224. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6225. // We just need to emit the ArgOut instructions.
  6226. if (fAssignRegs)
  6227. {
  6228. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6229. }
  6230. if (pnode->nop == knopEllipsis)
  6231. {
  6232. Assert(spreadIndices != nullptr);
  6233. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6234. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6235. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6236. if (noArgOuts)
  6237. {
  6238. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6239. }
  6240. else
  6241. {
  6242. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6243. }
  6244. funcInfo->ReleaseTmpRegister(regVal);
  6245. }
  6246. else
  6247. {
  6248. if (noArgOuts)
  6249. {
  6250. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6251. }
  6252. else
  6253. {
  6254. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6255. }
  6256. }
  6257. argIndex++;
  6258. if (fAssignRegs)
  6259. {
  6260. funcInfo->ReleaseLoc(pnode);
  6261. }
  6262. }
  6263. size_t EmitArgsWithArgOutsAtEnd(
  6264. ParseNode *pnode,
  6265. BOOL fAssignRegs,
  6266. ByteCodeGenerator *byteCodeGenerator,
  6267. FuncInfo *funcInfo,
  6268. Js::ProfileId callSiteId,
  6269. Js::RegSlot thisLocation,
  6270. Js::ArgSlot argsCountForStartCall,
  6271. bool emitProfiledArgouts,
  6272. Js::AuxArray<uint32> *spreadIndices = nullptr
  6273. )
  6274. {
  6275. AssertOrFailFast(pnode != nullptr);
  6276. Js::ArgSlot argIndex = 0;
  6277. Js::ArgSlot spreadIndex = 0;
  6278. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6279. Js::RegSlot firstArgTempLocation = argTempLocation;
  6280. while (pnode->nop == knopList)
  6281. {
  6282. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6283. pnode = pnode->AsParseNodeBin()->pnode2;
  6284. argTempLocation = funcInfo->AcquireTmpRegister();
  6285. }
  6286. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6287. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6288. // Emit all argOuts now
  6289. if (thisLocation != Js::Constants::NoRegister)
  6290. {
  6291. // Emit the "this" object.
  6292. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6293. }
  6294. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6295. {
  6296. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6297. }
  6298. // Now release all those temps register
  6299. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6300. {
  6301. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6302. }
  6303. return argIndex;
  6304. }
  6305. size_t EmitArgs(
  6306. ParseNode *pnode,
  6307. BOOL fAssignRegs,
  6308. ByteCodeGenerator *byteCodeGenerator,
  6309. FuncInfo *funcInfo,
  6310. Js::ProfileId callSiteId,
  6311. bool emitProfiledArgouts,
  6312. Js::AuxArray<uint32> *spreadIndices = nullptr
  6313. )
  6314. {
  6315. Js::ArgSlot argIndex = 0;
  6316. Js::ArgSlot spreadIndex = 0;
  6317. if (pnode != nullptr)
  6318. {
  6319. while (pnode->nop == knopList)
  6320. {
  6321. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6322. pnode = pnode->AsParseNodeBin()->pnode2;
  6323. }
  6324. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6325. }
  6326. return argIndex;
  6327. }
  6328. void EmitArgListStart(
  6329. Js::RegSlot thisLocation,
  6330. ByteCodeGenerator *byteCodeGenerator,
  6331. FuncInfo *funcInfo,
  6332. Js::ProfileId callSiteId)
  6333. {
  6334. if (thisLocation != Js::Constants::NoRegister)
  6335. {
  6336. // Emit the "this" object.
  6337. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6338. }
  6339. }
  6340. Js::ArgSlot EmitArgListEnd(
  6341. ParseNode *pnode,
  6342. Js::RegSlot thisLocation,
  6343. Js::RegSlot evalLocation,
  6344. Js::RegSlot newTargetLocation,
  6345. ByteCodeGenerator *byteCodeGenerator,
  6346. FuncInfo *funcInfo,
  6347. size_t argIndex,
  6348. Js::ProfileId callSiteId)
  6349. {
  6350. BOOL fEvalInModule = false;
  6351. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6352. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6353. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6354. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6355. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6356. Js::ArgSlot evalIndex;
  6357. if (fIsEval && argSlotIndex > 0)
  6358. {
  6359. Assert(!fHasNewTarget);
  6360. // Pass the frame display as an extra argument to "eval".
  6361. // Do this only if eval is called with some args
  6362. Js::RegSlot evalEnv;
  6363. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6364. {
  6365. // Use current environment as the environment for the function being called when:
  6366. // - this is the root global function (not an eval's global function)
  6367. // - this is an eval's global function that is not in strict mode (see else block)
  6368. evalEnv = funcInfo->GetEnvRegister();
  6369. }
  6370. else
  6371. {
  6372. // Use the frame display as the environment for the function being called when:
  6373. // - this is not a global function and thus it will have its own scope
  6374. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6375. // has its own scope
  6376. evalEnv = funcInfo->frameDisplayRegister;
  6377. }
  6378. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6379. // Passing the FrameDisplay as an extra argument
  6380. evalIndex = argSlotIndex + 1;
  6381. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6382. {
  6383. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6384. }
  6385. else
  6386. {
  6387. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6388. }
  6389. }
  6390. if (fHasNewTarget)
  6391. {
  6392. Assert(!fIsEval);
  6393. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6394. }
  6395. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6396. // eval and no args passed, return 1 as argument count
  6397. if (fIsEval && pnode == nullptr)
  6398. {
  6399. return 1;
  6400. }
  6401. return argIntCount;
  6402. }
  6403. Js::ArgSlot EmitArgList(
  6404. ParseNode *pnode,
  6405. Js::RegSlot thisLocation,
  6406. Js::RegSlot newTargetLocation,
  6407. BOOL fIsEval,
  6408. BOOL fAssignRegs,
  6409. ByteCodeGenerator *byteCodeGenerator,
  6410. FuncInfo *funcInfo,
  6411. Js::ProfileId callSiteId,
  6412. Js::ArgSlot argsCountForStartCall,
  6413. bool emitArgOutsAtEnd,
  6414. bool emitProfiledArgouts,
  6415. uint16 spreadArgCount = 0,
  6416. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6417. {
  6418. // This function emits the arguments for a call.
  6419. // ArgOut's with uses immediately following defs.
  6420. if (!emitArgOutsAtEnd)
  6421. {
  6422. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6423. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6424. }
  6425. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6426. //
  6427. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6428. // This would be used while generating frameDisplay in EmitArgListEnd.
  6429. //
  6430. if (fIsEval)
  6431. {
  6432. evalLocation = funcInfo->AcquireTmpRegister();
  6433. }
  6434. if (spreadArgCount > 0)
  6435. {
  6436. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6437. Assert(spreadIndices != nullptr);
  6438. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6439. }
  6440. size_t argIndex = 0;
  6441. if (emitArgOutsAtEnd)
  6442. {
  6443. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6444. }
  6445. else
  6446. {
  6447. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6448. }
  6449. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6450. if (fIsEval)
  6451. {
  6452. funcInfo->ReleaseTmpRegister(evalLocation);
  6453. }
  6454. return argumentsCount;
  6455. }
  6456. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6457. {
  6458. uint index = 0;
  6459. while (args->nop == knopList && index < argCount)
  6460. {
  6461. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6462. {
  6463. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6464. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6465. }
  6466. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6467. {
  6468. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6469. #if ! FLOATVAR
  6470. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6471. #endif
  6472. vars[index++] = number;
  6473. }
  6474. else
  6475. {
  6476. AnalysisAssert(false);
  6477. }
  6478. args = args->AsParseNodeBin()->pnode2;
  6479. }
  6480. if (index == argCount)
  6481. {
  6482. Assert(false);
  6483. Js::Throw::InternalError();
  6484. return;
  6485. }
  6486. if (args->nop == knopInt)
  6487. {
  6488. int value = args->AsParseNodeInt()->lw;
  6489. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6490. }
  6491. else if (args->nop == knopFlt)
  6492. {
  6493. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6494. #if ! FLOATVAR
  6495. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6496. #endif
  6497. vars[index++] = number;
  6498. }
  6499. else
  6500. {
  6501. AnalysisAssert(false);
  6502. }
  6503. }
  6504. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6505. {
  6506. uint index = 0;
  6507. while (args->nop == knopList && index < argCount)
  6508. {
  6509. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6510. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6511. args = args->AsParseNodeBin()->pnode2;
  6512. }
  6513. if (index >= argCount)
  6514. {
  6515. Js::Throw::InternalError();
  6516. return;
  6517. }
  6518. Assert(args->nop == knopInt);
  6519. vars[index++] = args->AsParseNodeInt()->lw;
  6520. Assert(index == argCount);
  6521. }
  6522. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6523. {
  6524. uint index = 0;
  6525. while (args->nop == knopList && index < argCount)
  6526. {
  6527. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6528. if (nop == knopInt)
  6529. {
  6530. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6531. }
  6532. else
  6533. {
  6534. Assert(nop == knopFlt);
  6535. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6536. }
  6537. args = args->AsParseNodeBin()->pnode2;
  6538. }
  6539. if (index >= argCount)
  6540. {
  6541. Js::Throw::InternalError();
  6542. return;
  6543. }
  6544. if (args->nop == knopInt)
  6545. {
  6546. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6547. }
  6548. else
  6549. {
  6550. Assert(args->nop == knopFlt);
  6551. vars[index++] = args->AsParseNodeFloat()->dbl;
  6552. }
  6553. Assert(index == argCount);
  6554. }
  6555. //
  6556. // Called when we have new Ctr(constant, constant...)
  6557. //
  6558. Js::ArgSlot EmitNewObjectOfConstants(
  6559. ParseNode *pnode,
  6560. ByteCodeGenerator *byteCodeGenerator,
  6561. FuncInfo *funcInfo,
  6562. unsigned int argCount)
  6563. {
  6564. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6565. // Create the vars array
  6566. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6567. // Emit all constants to the vars array
  6568. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6569. // Finish the arg list
  6570. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6571. pnode->AsParseNodeCall()->pnodeArgs,
  6572. Js::Constants::NoRegister,
  6573. Js::Constants::NoRegister,
  6574. Js::Constants::NoRegister,
  6575. byteCodeGenerator,
  6576. funcInfo,
  6577. argCount - 1,
  6578. Js::Constants::NoProfileId);
  6579. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6580. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6581. // Generate the opcode with vars
  6582. byteCodeGenerator->Writer()->AuxiliaryContext(
  6583. Js::OpCode::NewScObject_A,
  6584. funcInfo->AcquireLoc(pnode),
  6585. vars,
  6586. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6587. pnode->AsParseNodeCall()->pnodeTarget->location);
  6588. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6589. return actualArgCount;
  6590. }
  6591. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6592. {
  6593. Js::OpCode opcode;
  6594. if (!isRoot)
  6595. {
  6596. if (callObjLocation == funcInfo->frameObjRegister)
  6597. {
  6598. opcode = Js::OpCode::LdLocalMethodFld;
  6599. }
  6600. else
  6601. {
  6602. opcode = Js::OpCode::LdMethodFld;
  6603. }
  6604. }
  6605. else if (isScoped)
  6606. {
  6607. opcode = Js::OpCode::ScopedLdMethodFld;
  6608. }
  6609. else
  6610. {
  6611. opcode = Js::OpCode::LdRootMethodFld;
  6612. }
  6613. if (isScoped || !isRoot)
  6614. {
  6615. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6616. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6617. if (callObjLocation == funcInfo->frameObjRegister)
  6618. {
  6619. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6620. }
  6621. else
  6622. {
  6623. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6624. }
  6625. }
  6626. else
  6627. {
  6628. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6629. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6630. }
  6631. }
  6632. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6633. {
  6634. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6635. // the global object, etc.)
  6636. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6637. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6638. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6639. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6640. }
  6641. // lhs.apply(this, arguments);
  6642. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6643. {
  6644. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6645. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6646. Assert(applyNode->nop == knopDot);
  6647. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6648. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6649. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6650. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6651. Assert(applyNode->nop == knopDot);
  6652. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6653. funcInfo->AcquireLoc(applyNode);
  6654. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6655. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6656. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6657. // call for apply, we won't remove the entry for "apply" cacheId from
  6658. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6659. // have removed an entry from a map upon seeing its corresponding call.
  6660. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6661. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6662. Assert(argSym && argSym->IsArguments());
  6663. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6664. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6665. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6666. // If apply is overridden, bail to slow path.
  6667. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6668. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6669. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6670. // may crash if we try to unbox it on the store.
  6671. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6672. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6673. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6674. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6675. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6676. funcInfo->ReleaseTmpRegister(argCountLocation);
  6677. funcInfo->ReleaseTmpRegister(stackArgReg);
  6678. funcInfo->ReleaseLoc(applyNode);
  6679. funcInfo->ReleaseLoc(funcNode);
  6680. // Clear these nodes as they are going to be used to re-generate the slow path.
  6681. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6682. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6683. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6684. // slow path
  6685. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6686. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6687. {
  6688. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6689. }
  6690. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6691. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6692. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6693. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6694. }
  6695. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6696. {
  6697. // Load a call target of the form x[y]().
  6698. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6699. }
  6700. void EmitCallTargetNoEvalComponents(
  6701. ParseNode *pnodeTarget,
  6702. BOOL fSideEffectArgs,
  6703. Js::RegSlot *thisLocation,
  6704. bool *releaseThisLocation,
  6705. Js::RegSlot *callObjLocation,
  6706. ByteCodeGenerator *byteCodeGenerator,
  6707. FuncInfo *funcInfo)
  6708. {
  6709. // We first get a reference to the call target, then evaluate the arguments, then
  6710. // evaluate the call target.
  6711. // - emit reference to target
  6712. // - copy instance to scratch reg if necessary.
  6713. // - assign this
  6714. // - assign instance for dynamic/global name
  6715. // - emit args
  6716. // - do call (CallFld/Elem/I)
  6717. *releaseThisLocation = true;
  6718. switch (pnodeTarget->nop)
  6719. {
  6720. case knopDot:
  6721. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6722. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6723. break;
  6724. case knopIndex:
  6725. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6726. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6727. break;
  6728. case knopName:
  6729. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6730. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  6731. if (*thisLocation == Js::Constants::NoRegister)
  6732. {
  6733. *thisLocation = funcInfo->undefinedConstantRegister;
  6734. }
  6735. break;
  6736. default:
  6737. *thisLocation = funcInfo->undefinedConstantRegister;
  6738. break;
  6739. }
  6740. }
  6741. void EmitCallTarget(
  6742. ParseNode *pnodeTarget,
  6743. BOOL fSideEffectArgs,
  6744. Js::RegSlot *thisLocation,
  6745. bool *releaseThisLocation,
  6746. Js::RegSlot *callObjLocation,
  6747. ByteCodeGenerator *byteCodeGenerator,
  6748. FuncInfo *funcInfo)
  6749. {
  6750. // - emit target
  6751. // - assign this
  6752. // - emit args
  6753. // - do call
  6754. // The call target is fully evaluated before the argument list. Note that we're not handling
  6755. // put-call cases here currently, as such cases only apply to host objects
  6756. // and are very unlikely to behave differently depending on the order of evaluation.
  6757. *releaseThisLocation = true;
  6758. switch (pnodeTarget->nop)
  6759. {
  6760. case knopDot:
  6761. {
  6762. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  6763. funcInfo->AcquireLoc(pnodeBinTarget);
  6764. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6765. // them from side-effects.
  6766. if (fSideEffectArgs)
  6767. {
  6768. // Though we're done with target evaluation after this point, still protect opnd1 from
  6769. // arg side-effects as it's the "this" pointer.
  6770. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  6771. }
  6772. Assert(pnodeBinTarget->pnode2->nop == knopName);
  6773. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  6774. {
  6775. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  6776. }
  6777. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  6778. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6779. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  6780. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  6781. {
  6782. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6783. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6784. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  6785. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  6786. // Function calls on the 'super' object should maintain current 'this' pointer.
  6787. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6788. *releaseThisLocation = false;
  6789. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  6790. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld,
  6791. pnodeTarget->location, protoLocation, *thisLocation, cacheId, false);
  6792. }
  6793. else
  6794. {
  6795. *thisLocation = pnodeBinTarget->pnode1->location;
  6796. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6797. }
  6798. break;
  6799. }
  6800. case knopIndex:
  6801. {
  6802. funcInfo->AcquireLoc(pnodeTarget);
  6803. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6804. // them from side-effects.
  6805. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  6806. {
  6807. // Though we're done with target evaluation after this point, still protect opnd1 from
  6808. // arg or opnd2 side-effects as it's the "this" pointer.
  6809. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  6810. }
  6811. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  6812. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  6813. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  6814. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6815. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6816. {
  6817. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6818. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6819. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  6820. // Function calls on the 'super' object should maintain current 'this' pointer
  6821. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6822. *releaseThisLocation = false;
  6823. }
  6824. else
  6825. {
  6826. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6827. }
  6828. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6829. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  6830. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6831. {
  6832. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  6833. }
  6834. break;
  6835. }
  6836. case knopName:
  6837. {
  6838. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  6839. if (!pnodeNameTarget->IsSpecialName())
  6840. {
  6841. funcInfo->AcquireLoc(pnodeNameTarget);
  6842. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6843. // them from side-effects.
  6844. if (fSideEffectArgs)
  6845. {
  6846. SaveOpndValue(pnodeNameTarget, funcInfo);
  6847. }
  6848. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  6849. if (*callObjLocation != Js::Constants::NoRegister)
  6850. {
  6851. // Load the call target as a property of the instance.
  6852. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  6853. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6854. break;
  6855. }
  6856. }
  6857. // FALL THROUGH to evaluate call target.
  6858. }
  6859. default:
  6860. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6861. // them from side-effects.
  6862. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6863. *thisLocation = funcInfo->undefinedConstantRegister;
  6864. break;
  6865. }
  6866. // "This" pointer should have been assigned by the above.
  6867. Assert(*thisLocation != Js::Constants::NoRegister);
  6868. }
  6869. void EmitCallI(
  6870. ParseNodeCall *pnodeCall,
  6871. BOOL fEvaluateComponents,
  6872. BOOL fIsEval,
  6873. BOOL fHasNewTarget,
  6874. uint32 actualArgCount,
  6875. ByteCodeGenerator *byteCodeGenerator,
  6876. FuncInfo *funcInfo,
  6877. Js::ProfileId callSiteId,
  6878. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6879. {
  6880. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6881. // already evaluated.
  6882. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6883. Js::OpCode op;
  6884. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6885. uint spreadExtraAlloc = 0;
  6886. bool isSuperCall = pnodeCall->isSuperCall;
  6887. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6888. // check for integer overflow
  6889. if ((size_t)actualArgSlotCount != actualArgCount)
  6890. {
  6891. Js::Throw::OutOfMemory();
  6892. }
  6893. if (fEvaluateComponents && !isSuperCall)
  6894. {
  6895. // Release the call target operands we assigned above. If we didn't assign them here,
  6896. // we'll need them later, so we can't re-use them for the result of the call.
  6897. funcInfo->ReleaseLoc(pnodeTarget);
  6898. }
  6899. // Grab a register for the call result.
  6900. if (pnodeCall->isUsed)
  6901. {
  6902. funcInfo->AcquireLoc(pnodeCall);
  6903. }
  6904. if (fIsEval)
  6905. {
  6906. op = Js::OpCode::CallIExtendedFlags;
  6907. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6908. }
  6909. else
  6910. {
  6911. if (isSuperCall)
  6912. {
  6913. callFlags = Js::CallFlags_New;
  6914. }
  6915. if (fHasNewTarget)
  6916. {
  6917. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6918. }
  6919. if (pnodeCall->spreadArgCount > 0)
  6920. {
  6921. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6922. }
  6923. else
  6924. {
  6925. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6926. }
  6927. }
  6928. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6929. {
  6930. if (isSuperCall)
  6931. {
  6932. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6933. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  6934. }
  6935. else
  6936. {
  6937. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6938. }
  6939. }
  6940. else
  6941. {
  6942. uint spreadIndicesSize = 0;
  6943. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6944. if (pnodeCall->spreadArgCount > 0)
  6945. {
  6946. Assert(spreadIndices != nullptr);
  6947. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  6948. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  6949. options = Js::CallIExtended_SpreadArgs;
  6950. }
  6951. if (isSuperCall)
  6952. {
  6953. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6954. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6955. }
  6956. else
  6957. {
  6958. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6959. }
  6960. }
  6961. if (pnodeCall->spreadArgCount > 0)
  6962. {
  6963. Assert(spreadExtraAlloc != 0);
  6964. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6965. }
  6966. }
  6967. void EmitCallInstrNoEvalComponents(
  6968. ParseNodeCall *pnodeCall,
  6969. BOOL fIsEval,
  6970. Js::RegSlot thisLocation,
  6971. Js::RegSlot callObjLocation,
  6972. uint32 actualArgCount,
  6973. ByteCodeGenerator *byteCodeGenerator,
  6974. FuncInfo *funcInfo,
  6975. Js::ProfileId callSiteId,
  6976. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6977. {
  6978. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6979. // it as part of doing the actual call.
  6980. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6981. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6982. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6983. switch (pnodeTarget->nop)
  6984. {
  6985. case knopDot:
  6986. {
  6987. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  6988. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6989. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6990. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6991. }
  6992. break;
  6993. case knopIndex:
  6994. {
  6995. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  6996. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6997. }
  6998. break;
  6999. case knopName:
  7000. {
  7001. if (callObjLocation != Js::Constants::NoRegister)
  7002. {
  7003. // We still have to get the property from its instance, so emit CallFld.
  7004. if (thisLocation != callObjLocation)
  7005. {
  7006. funcInfo->ReleaseTmpRegister(thisLocation);
  7007. }
  7008. funcInfo->ReleaseTmpRegister(callObjLocation);
  7009. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  7010. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7011. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7012. break;
  7013. }
  7014. }
  7015. // FALL THROUGH
  7016. default:
  7017. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7018. break;
  7019. }
  7020. }
  7021. void EmitCallInstr(
  7022. ParseNodeCall *pnodeCall,
  7023. BOOL fIsEval,
  7024. BOOL fHasNewTarget,
  7025. Js::RegSlot thisLocation,
  7026. Js::RegSlot callObjLocation,
  7027. uint32 actualArgCount,
  7028. ByteCodeGenerator *byteCodeGenerator,
  7029. FuncInfo *funcInfo,
  7030. Js::ProfileId callSiteId,
  7031. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7032. {
  7033. // Emit a call instruction. The call target has been fully evaluated already, so we always
  7034. // emit a CallI through the register that holds the target value.
  7035. // Note that we don't handle !fEvaluateComponents cases at this point.
  7036. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  7037. if (thisLocation != Js::Constants::NoRegister)
  7038. {
  7039. funcInfo->ReleaseTmpRegister(thisLocation);
  7040. }
  7041. if (callObjLocation != Js::Constants::NoRegister &&
  7042. callObjLocation != thisLocation)
  7043. {
  7044. funcInfo->ReleaseTmpRegister(callObjLocation);
  7045. }
  7046. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7047. }
  7048. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7049. {
  7050. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  7051. argCount++; // include "this"
  7052. BOOL fSideEffectArgs = FALSE;
  7053. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  7054. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  7055. byteCodeGenerator->StartStatement(pnode);
  7056. // Start call, allocate out param space
  7057. funcInfo->StartRecordingOutArgs(argCount);
  7058. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7059. // them from side-effects.
  7060. if (fSideEffectArgs)
  7061. {
  7062. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  7063. }
  7064. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  7065. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  7066. {
  7067. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7068. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  7069. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  7070. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  7071. Assert(argCount == 1);
  7072. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7073. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7074. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  7075. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  7076. }
  7077. else
  7078. {
  7079. uint32 actualArgCount = 0;
  7080. if (IsCallOfConstants(pnode))
  7081. {
  7082. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7083. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7084. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  7085. }
  7086. else
  7087. {
  7088. Js::OpCode op;
  7089. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  7090. {
  7091. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  7092. }
  7093. else
  7094. {
  7095. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  7096. }
  7097. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7098. // Only emit profiled argouts if we're going to profile this call.
  7099. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7100. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7101. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7102. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, pnode->AsParseNodeCall()->hasDestructuring, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  7103. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7104. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  7105. {
  7106. Assert(spreadIndices != nullptr);
  7107. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7108. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7109. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7110. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7111. spreadIndices, spreadIndicesSize, callSiteId);
  7112. }
  7113. else
  7114. {
  7115. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7116. (uint16)actualArgCount, callSiteId);
  7117. }
  7118. }
  7119. Assert(argCount == actualArgCount);
  7120. }
  7121. // End call, pop param space
  7122. funcInfo->EndRecordingOutArgs(argCount);
  7123. return;
  7124. }
  7125. void EmitCall(
  7126. ParseNodeCall * pnodeCall,
  7127. ByteCodeGenerator* byteCodeGenerator,
  7128. FuncInfo* funcInfo,
  7129. BOOL fReturnValue,
  7130. BOOL fEvaluateComponents,
  7131. Js::RegSlot overrideThisLocation,
  7132. Js::RegSlot newTargetLocation)
  7133. {
  7134. // If the call returns a float, we'll note this in the byte code.
  7135. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7136. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7137. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7138. BOOL fSideEffectArgs = FALSE;
  7139. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7140. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7141. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7142. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7143. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7144. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7145. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7146. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7147. // "new" path, since then our native array handling can kick in.
  7148. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7149. return;*/
  7150. }
  7151. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7152. BOOL fIsEval = pnodeCall->isEvalCall;
  7153. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7154. if (fIsEval)
  7155. {
  7156. Assert(!fHasNewTarget);
  7157. //
  7158. // "eval" takes the closure environment as an extra argument
  7159. // Pass the closure env only if some argument is passed
  7160. // For just eval(), don't pass the closure environment
  7161. //
  7162. if (argCount > 1)
  7163. {
  7164. argCount++;
  7165. }
  7166. }
  7167. else if (fHasNewTarget)
  7168. {
  7169. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7170. // This is similar to how eval passes an extra argument for the frame display and is
  7171. // used to support cases where we need to pass both 'this' and new.target as part of
  7172. // a function call.
  7173. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7174. argCount++;
  7175. }
  7176. // argCount indicates the total arguments count including the extra arguments.
  7177. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7178. if (argCount < (unsigned int)argSlotCount)
  7179. {
  7180. Js::Throw::OutOfMemory();
  7181. }
  7182. if (fReturnValue)
  7183. {
  7184. pnodeCall->isUsed = true;
  7185. }
  7186. //
  7187. // Set up the call.
  7188. //
  7189. bool releaseThisLocation = true;
  7190. // We already emit the call target for super calls in EmitSuperCall
  7191. if (!fIsSuperCall)
  7192. {
  7193. if (!fEvaluateComponents)
  7194. {
  7195. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7196. }
  7197. else
  7198. {
  7199. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7200. }
  7201. }
  7202. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7203. if (overrideThisLocation != Js::Constants::NoRegister)
  7204. {
  7205. thisLocation = overrideThisLocation;
  7206. releaseThisLocation = false;
  7207. }
  7208. // Evaluate the arguments (nothing mode-specific here).
  7209. // Start call, allocate out param space
  7210. // We have to use the arguments count including the extra args to Start Call as we use it to allocated space for all the args
  7211. funcInfo->StartRecordingOutArgs(argCount);
  7212. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7213. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7214. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7215. Js::AuxArray<uint32> *spreadIndices;
  7216. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, pnodeCall->hasDestructuring, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7217. if (!fEvaluateComponents)
  7218. {
  7219. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7220. }
  7221. else
  7222. {
  7223. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7224. }
  7225. // End call, pop param space
  7226. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7227. }
  7228. void EmitInvoke(
  7229. Js::RegSlot location,
  7230. Js::RegSlot callObjLocation,
  7231. Js::PropertyId propertyId,
  7232. ByteCodeGenerator* byteCodeGenerator,
  7233. FuncInfo* funcInfo)
  7234. {
  7235. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7236. funcInfo->StartRecordingOutArgs(1);
  7237. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7238. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7239. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7240. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7241. }
  7242. void EmitInvoke(
  7243. Js::RegSlot location,
  7244. Js::RegSlot callObjLocation,
  7245. Js::PropertyId propertyId,
  7246. ByteCodeGenerator* byteCodeGenerator,
  7247. FuncInfo* funcInfo,
  7248. Js::RegSlot arg1Location)
  7249. {
  7250. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7251. funcInfo->StartRecordingOutArgs(2);
  7252. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7253. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7254. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7255. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7256. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7257. }
  7258. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNodeFnc *exprNode, ByteCodeGenerator *byteCodeGenerator)
  7259. {
  7260. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  7261. Assert(exprNode->HasComputedName());
  7262. if (nameNode == nullptr)
  7263. {
  7264. return;
  7265. }
  7266. if (exprNode->pnodeName == nullptr)
  7267. {
  7268. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  7269. }
  7270. }
  7271. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7272. {
  7273. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7274. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7275. bool isFncDecl = exprNode->nop == knopFncDecl;
  7276. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7277. if (isFncDecl)
  7278. {
  7279. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7280. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7281. }
  7282. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7283. // which makes this bytecode too late to influence the function.name.
  7284. if (nameNode->nop == knopComputedName)
  7285. {
  7286. // Computed property name
  7287. // Transparently pass the name expr
  7288. // The Emit will replace this with a temp register if necessary to preserve the value.
  7289. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7290. // Save the previous value of the flag to be restored later.
  7291. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7292. // Strict mode must be enforced on the evaluation of computed property names inside
  7293. // classes, thus enable the flag if the computed property name is a class member.
  7294. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7295. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  7296. // Restore the flag's previous value.
  7297. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7298. if (isFncDecl && !exprNode->AsParseNodeFnc()->IsClassConstructor())
  7299. {
  7300. EmitComputedFunctionNameVar(nameNode, exprNode->AsParseNodeFnc(), byteCodeGenerator);
  7301. }
  7302. }
  7303. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  7304. // but if we don't have any members then we don't need to load the prototype.
  7305. Assert(isClassMember == (isObjectEmpty != nullptr));
  7306. if (isClassMember && *isObjectEmpty)
  7307. {
  7308. *isObjectEmpty = false;
  7309. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  7310. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  7311. }
  7312. if (nameNode->nop == knopComputedName)
  7313. {
  7314. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7315. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7316. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7317. memberNode->nop == knopSetMember ?
  7318. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7319. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7320. // Save the previous value of the flag to be restored later.
  7321. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7322. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7323. // Strict mode must be enforced on the evaluation of computed property names inside
  7324. // classes, thus enable the flag if the computed property name is a class member.
  7325. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true,
  7326. byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  7327. // Restore the flag's previous value.
  7328. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7329. funcInfo->ReleaseLoc(exprNode);
  7330. funcInfo->ReleaseLoc(nameNode);
  7331. return;
  7332. }
  7333. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7334. if (useStore)
  7335. {
  7336. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7337. }
  7338. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7339. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7340. if (Js::PropertyIds::name == propertyId
  7341. && exprNode->nop == knopFncDecl
  7342. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7343. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7344. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7345. {
  7346. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7347. nameFunc->SetIsStaticNameFunction(true);
  7348. }
  7349. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7350. {
  7351. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7352. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7353. {
  7354. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7355. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7356. }
  7357. else
  7358. {
  7359. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7360. Js::OpCode patchablePropertyOpCode;
  7361. if (useStore)
  7362. {
  7363. patchablePropertyOpCode = stFldOpCode;
  7364. }
  7365. else if (isClassMember)
  7366. {
  7367. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7368. }
  7369. else
  7370. {
  7371. patchablePropertyOpCode = Js::OpCode::InitFld;
  7372. }
  7373. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7374. }
  7375. }
  7376. else
  7377. {
  7378. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7379. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7380. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7381. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7382. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7383. }
  7384. funcInfo->ReleaseLoc(exprNode);
  7385. if (propertyId == Js::PropertyIds::valueOf)
  7386. {
  7387. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7388. }
  7389. else if (propertyId == Js::PropertyIds::toString)
  7390. {
  7391. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7392. }
  7393. }
  7394. void EmitObjectSpreadNode(ParseNode *spreadNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7395. {
  7396. Js::RegSlot fromObjectLocation;
  7397. ParseNode *exprNode = spreadNode->AsParseNodeUni()->pnode1;
  7398. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7399. fromObjectLocation = exprNode->location;
  7400. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SpreadObjectLiteral, fromObjectLocation, objectLocation);
  7401. funcInfo->ReleaseLoc(exprNode);
  7402. }
  7403. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7404. {
  7405. if (memberList != nullptr)
  7406. {
  7407. while (memberList->nop == knopList)
  7408. {
  7409. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7410. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7411. memberList = memberList->AsParseNodeBin()->pnode2;
  7412. }
  7413. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7414. }
  7415. }
  7416. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7417. {
  7418. ParseNode *pmemberList = memberList;
  7419. unsigned int argCount = 0;
  7420. uint32 value;
  7421. Js::PropertyId propertyId;
  7422. //
  7423. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7424. // 2. Get the count of propertyIds
  7425. // 3. Create a propertyId array of size count
  7426. // 4. Put the propIds in the auxiliary area
  7427. // 5. Get the objectLiteralCacheId
  7428. // 6. Generate propId inits with values
  7429. //
  7430. // Handle propertyId collision
  7431. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7432. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7433. bool hasComputedNameOrSpread = false;
  7434. if (memberList != nullptr)
  7435. {
  7436. while (memberList->nop == knopList)
  7437. {
  7438. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7439. {
  7440. hasComputedNameOrSpread = true;
  7441. break;
  7442. }
  7443. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7444. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7445. {
  7446. propertyIds->Item(propertyId);
  7447. }
  7448. memberList = memberList->AsParseNodeBin()->pnode2;
  7449. }
  7450. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7451. {
  7452. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7453. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7454. {
  7455. propertyIds->Item(propertyId);
  7456. }
  7457. }
  7458. }
  7459. argCount = propertyIds->Count();
  7460. memberList = pmemberList;
  7461. if ((memberList == nullptr) || (argCount == 0))
  7462. {
  7463. // Empty literal or numeric property only object literal
  7464. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7465. }
  7466. else
  7467. {
  7468. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7469. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7470. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7471. {
  7472. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7473. // or not, in case the bytecode is later run with __proto__ enabled.
  7474. propIds->has__proto__ = true;
  7475. }
  7476. unsigned int argIndex = 0;
  7477. while (memberList->nop == knopList)
  7478. {
  7479. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7480. {
  7481. break;
  7482. }
  7483. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7484. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7485. {
  7486. propIds->elements[argIndex] = propertyId;
  7487. argIndex++;
  7488. }
  7489. memberList = memberList->AsParseNodeBin()->pnode2;
  7490. }
  7491. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7492. {
  7493. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7494. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7495. {
  7496. propIds->elements[argIndex] = propertyId;
  7497. argIndex++;
  7498. }
  7499. }
  7500. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7501. // Generate the opcode with propIds and cacheId
  7502. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7503. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7504. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7505. }
  7506. memberList = pmemberList;
  7507. bool useStore = false;
  7508. // Generate the actual assignment to those properties
  7509. if (memberList != nullptr)
  7510. {
  7511. while (memberList->nop == knopList)
  7512. {
  7513. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7514. if (memberNode->nop == knopEllipsis)
  7515. {
  7516. byteCodeGenerator->StartSubexpression(memberNode);
  7517. EmitObjectSpreadNode(memberNode, objectLocation, byteCodeGenerator, funcInfo);
  7518. byteCodeGenerator->EndSubexpression(memberNode);
  7519. }
  7520. else
  7521. {
  7522. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7523. {
  7524. useStore = true;
  7525. }
  7526. byteCodeGenerator->StartSubexpression(memberNode);
  7527. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7528. byteCodeGenerator->EndSubexpression(memberNode);
  7529. }
  7530. memberList = memberList->AsParseNodeBin()->pnode2;
  7531. }
  7532. byteCodeGenerator->StartSubexpression(memberList);
  7533. if (memberList->nop == knopEllipsis)
  7534. {
  7535. EmitObjectSpreadNode(memberList, objectLocation, byteCodeGenerator, funcInfo);
  7536. }
  7537. else
  7538. {
  7539. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7540. }
  7541. byteCodeGenerator->EndSubexpression(memberList);
  7542. }
  7543. }
  7544. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7545. {
  7546. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7547. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7548. // We only need to emit code for non-tagged string templates here.
  7549. if (!pnodeStrTemplate->isTaggedTemplate)
  7550. {
  7551. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7552. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7553. {
  7554. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7555. funcInfo->AcquireLoc(pnodeStrTemplate);
  7556. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7557. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7558. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7559. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7560. }
  7561. else
  7562. {
  7563. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7564. funcInfo->AcquireLoc(pnodeStrTemplate);
  7565. // First string must be a list node since we have substitutions.
  7566. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7567. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7568. // Emit the first string and load that into the pnode location.
  7569. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7570. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7571. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7572. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7573. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7574. ParseNode* stringNode;
  7575. ParseNode* expressionNode;
  7576. // Now append the substitution expressions and remaining string constants via normal add operator
  7577. // We will always have one more string constant than substitution expression
  7578. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7579. //
  7580. // strcon1 --- step 1 (above)
  7581. // expr1 \__ step 2
  7582. // strcon2 /
  7583. // expr2 \__ step 3
  7584. // strcon3 /
  7585. while (stringNodeList->nop == knopList)
  7586. {
  7587. // If the current head of the expression list is a list, fetch the node and walk the list.
  7588. if (expressionNodeList->nop == knopList)
  7589. {
  7590. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7591. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7592. }
  7593. else
  7594. {
  7595. // This is the last element of the expression list.
  7596. expressionNode = expressionNodeList;
  7597. }
  7598. // Emit the expression and append it to the string we're building.
  7599. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7600. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7601. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7602. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7603. funcInfo->ReleaseTmpRegister(toStringLocation);
  7604. funcInfo->ReleaseLoc(expressionNode);
  7605. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7606. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7607. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7608. if (stringNodeList->nop == knopList)
  7609. {
  7610. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7611. }
  7612. else
  7613. {
  7614. // This is the last element of the string literal list.
  7615. stringNode = stringNodeList;
  7616. }
  7617. // Emit the string node following the previous expression and append it to the string.
  7618. // This is either just some string in the list or it is the last string.
  7619. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7620. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7621. funcInfo->ReleaseLoc(stringNode);
  7622. }
  7623. }
  7624. }
  7625. }
  7626. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7627. {
  7628. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7629. uint argCount = pnode->AsParseNodeArrLit()->count;
  7630. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7631. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7632. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7633. if (arrayIntOpt)
  7634. {
  7635. int extraAlloc = 0, auxSize = 0;
  7636. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7637. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7638. {
  7639. ::Math::DefaultOverflowPolicy();
  7640. }
  7641. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7642. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7643. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7644. byteCodeGenerator->Writer()->Auxiliary(
  7645. Js::OpCode::NewScIntArray,
  7646. pnode->location,
  7647. ints,
  7648. auxSize,
  7649. argCount);
  7650. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7651. return;
  7652. }
  7653. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7654. if (arrayNumOpt)
  7655. {
  7656. int extraAlloc = 0, auxSize = 0;
  7657. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7658. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7659. {
  7660. ::Math::DefaultOverflowPolicy();
  7661. }
  7662. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7663. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7664. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7665. byteCodeGenerator->Writer()->Auxiliary(
  7666. Js::OpCode::NewScFltArray,
  7667. pnode->location,
  7668. doubles,
  7669. auxSize,
  7670. argCount);
  7671. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7672. return;
  7673. }
  7674. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7675. Assert(!arrayLitOpt || !nativeArrays);
  7676. Js::RegSlot spreadArrLoc = arrayLocation;
  7677. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7678. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7679. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7680. {
  7681. arrayLocation = funcInfo->AcquireTmpRegister();
  7682. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7683. }
  7684. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7685. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7686. arrayLocation,
  7687. argCount);
  7688. if (args != nullptr)
  7689. {
  7690. Js::OpCode opcode;
  7691. Js::RegSlot arrLoc;
  7692. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7693. {
  7694. opcode = Js::OpCode::StArrItemC_CI4;
  7695. arrLoc = arrayLocation;
  7696. }
  7697. else if (arrayLitOpt)
  7698. {
  7699. opcode = Js::OpCode::StArrSegItem_A;
  7700. arrLoc = funcInfo->AcquireTmpRegister();
  7701. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7702. }
  7703. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7704. {
  7705. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7706. // should be done relative to the array header to keep it alive (instead of the array segment).
  7707. opcode = Js::OpCode::StArrInlineItem_CI4;
  7708. arrLoc = arrayLocation;
  7709. }
  7710. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7711. {
  7712. opcode = Js::OpCode::StArrSegItem_CI4;
  7713. arrLoc = funcInfo->AcquireTmpRegister();
  7714. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7715. }
  7716. else
  7717. {
  7718. opcode = Js::OpCode::StArrItemI_CI4;
  7719. arrLoc = arrayLocation;
  7720. }
  7721. if (arrayLitOpt)
  7722. {
  7723. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  7724. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  7725. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7726. // Generate the opcode with vars
  7727. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  7728. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  7729. }
  7730. else
  7731. {
  7732. uint i = 0;
  7733. unsigned spreadIndex = 0;
  7734. Js::RegSlot rhsLocation;
  7735. while (args->nop == knopList)
  7736. {
  7737. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  7738. {
  7739. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7740. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  7741. Js::RegSlot regVal = rhsLocation;
  7742. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7743. {
  7744. AnalysisAssert(spreadIndices);
  7745. regVal = funcInfo->AcquireTmpRegister();
  7746. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7747. spreadIndices->elements[spreadIndex++] = i;
  7748. }
  7749. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7750. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7751. {
  7752. funcInfo->ReleaseTmpRegister(regVal);
  7753. }
  7754. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  7755. }
  7756. args = args->AsParseNodeBin()->pnode2;
  7757. i++;
  7758. }
  7759. if (args->nop != knopEmpty)
  7760. {
  7761. Emit(args, byteCodeGenerator, funcInfo, false);
  7762. rhsLocation = args->location;
  7763. Js::RegSlot regVal = rhsLocation;
  7764. if (args->nop == knopEllipsis)
  7765. {
  7766. regVal = funcInfo->AcquireTmpRegister();
  7767. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7768. AnalysisAssert(spreadIndices);
  7769. spreadIndices->elements[spreadIndex] = i;
  7770. }
  7771. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7772. if (args->nop == knopEllipsis)
  7773. {
  7774. funcInfo->ReleaseTmpRegister(regVal);
  7775. }
  7776. funcInfo->ReleaseLoc(args);
  7777. i++;
  7778. }
  7779. Assert(i <= argCount);
  7780. }
  7781. if (arrLoc != arrayLocation)
  7782. {
  7783. funcInfo->ReleaseTmpRegister(arrLoc);
  7784. }
  7785. }
  7786. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7787. {
  7788. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  7789. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7790. funcInfo->ReleaseTmpRegister(arrayLocation);
  7791. }
  7792. }
  7793. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7794. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7795. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7796. // with special case for single-branch style.
  7797. void EmitBooleanExpression(
  7798. _In_ ParseNode* expr,
  7799. Js::ByteCodeLabel trueLabel,
  7800. Js::ByteCodeLabel falseLabel,
  7801. _In_ ByteCodeGenerator* byteCodeGenerator,
  7802. _In_ FuncInfo* funcInfo,
  7803. bool trueFallthrough,
  7804. bool falseFallthrough)
  7805. {
  7806. Assert(!trueFallthrough || !falseFallthrough);
  7807. byteCodeGenerator->StartStatement(expr);
  7808. switch (expr->nop)
  7809. {
  7810. case knopLogOr:
  7811. {
  7812. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7813. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  7814. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7815. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7816. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7817. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7818. break;
  7819. }
  7820. case knopLogAnd:
  7821. {
  7822. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7823. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  7824. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7825. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7826. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7827. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7828. break;
  7829. }
  7830. case knopLogNot:
  7831. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  7832. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7833. break;
  7834. case knopEq:
  7835. case knopEqv:
  7836. case knopNEqv:
  7837. case knopNe:
  7838. case knopLt:
  7839. case knopLe:
  7840. case knopGe:
  7841. case knopGt:
  7842. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7843. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7844. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7845. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  7846. expr->AsParseNodeBin()->pnode2->location);
  7847. if (!falseFallthrough)
  7848. {
  7849. byteCodeGenerator->Writer()->Br(falseLabel);
  7850. }
  7851. break;
  7852. case knopTrue:
  7853. if (!trueFallthrough)
  7854. {
  7855. byteCodeGenerator->Writer()->Br(trueLabel);
  7856. }
  7857. break;
  7858. case knopFalse:
  7859. if (!falseFallthrough)
  7860. {
  7861. byteCodeGenerator->Writer()->Br(falseLabel);
  7862. }
  7863. break;
  7864. default:
  7865. // Note: we usually release the temp assigned to a node after we Emit it.
  7866. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7867. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7868. Emit(expr, byteCodeGenerator, funcInfo, false);
  7869. if (trueFallthrough)
  7870. {
  7871. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7872. }
  7873. else
  7874. {
  7875. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7876. if (!falseFallthrough)
  7877. {
  7878. byteCodeGenerator->Writer()->Br(falseLabel);
  7879. }
  7880. }
  7881. break;
  7882. }
  7883. byteCodeGenerator->EndStatement(expr);
  7884. }
  7885. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  7886. ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7887. {
  7888. switch (expr->nop)
  7889. {
  7890. case knopLogOr:
  7891. {
  7892. byteCodeGenerator->StartStatement(expr);
  7893. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7894. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, byteCodeGenerator, funcInfo);
  7895. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7896. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7897. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7898. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7899. byteCodeGenerator->EndStatement(expr);
  7900. break;
  7901. }
  7902. case knopLogAnd:
  7903. {
  7904. byteCodeGenerator->StartStatement(expr);
  7905. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7906. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, byteCodeGenerator, funcInfo);
  7907. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7908. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7909. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7910. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7911. byteCodeGenerator->EndStatement(expr);
  7912. break;
  7913. }
  7914. case knopLogNot:
  7915. {
  7916. byteCodeGenerator->StartStatement(expr);
  7917. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  7918. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  7919. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  7920. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  7921. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  7922. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7923. byteCodeGenerator->Writer()->Br(trueLabel);
  7924. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  7925. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7926. if (!falsefallthrough)
  7927. {
  7928. byteCodeGenerator->Writer()->Br(falseLabel);
  7929. }
  7930. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7931. byteCodeGenerator->EndStatement(expr);
  7932. break;
  7933. }
  7934. case knopEq:
  7935. case knopEqv:
  7936. case knopNEqv:
  7937. case knopNe:
  7938. case knopLt:
  7939. case knopLe:
  7940. case knopGe:
  7941. case knopGt:
  7942. byteCodeGenerator->StartStatement(expr);
  7943. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7944. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7945. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7946. funcInfo->AcquireLoc(expr);
  7947. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  7948. expr->AsParseNodeBin()->pnode2->location);
  7949. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7950. // The inliner likes small bytecode
  7951. if (!(truefallthrough || falsefallthrough))
  7952. {
  7953. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7954. byteCodeGenerator->Writer()->Br(falseLabel);
  7955. }
  7956. else if (truefallthrough && !falsefallthrough) {
  7957. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7958. }
  7959. else if (falsefallthrough && !truefallthrough) {
  7960. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7961. }
  7962. byteCodeGenerator->EndStatement(expr);
  7963. break;
  7964. case knopTrue:
  7965. byteCodeGenerator->StartStatement(expr);
  7966. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7967. if (!truefallthrough)
  7968. {
  7969. byteCodeGenerator->Writer()->Br(trueLabel);
  7970. }
  7971. byteCodeGenerator->EndStatement(expr);
  7972. break;
  7973. case knopFalse:
  7974. byteCodeGenerator->StartStatement(expr);
  7975. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7976. if (!falsefallthrough)
  7977. {
  7978. byteCodeGenerator->Writer()->Br(falseLabel);
  7979. }
  7980. byteCodeGenerator->EndStatement(expr);
  7981. break;
  7982. default:
  7983. // Note: we usually release the temp assigned to a node after we Emit it.
  7984. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7985. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7986. // For diagnostics purposes, register the name and dot to the statement list.
  7987. if (expr->nop == knopName || expr->nop == knopDot)
  7988. {
  7989. byteCodeGenerator->StartStatement(expr);
  7990. Emit(expr, byteCodeGenerator, funcInfo, false);
  7991. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7992. // The inliner likes small bytecode
  7993. if (!(truefallthrough || falsefallthrough))
  7994. {
  7995. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7996. byteCodeGenerator->Writer()->Br(falseLabel);
  7997. }
  7998. else if (truefallthrough && !falsefallthrough) {
  7999. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8000. }
  8001. else if (falsefallthrough && !truefallthrough) {
  8002. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8003. }
  8004. byteCodeGenerator->EndStatement(expr);
  8005. }
  8006. else
  8007. {
  8008. Emit(expr, byteCodeGenerator, funcInfo, false);
  8009. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  8010. // The inliner likes small bytecode
  8011. if (!(truefallthrough || falsefallthrough))
  8012. {
  8013. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8014. byteCodeGenerator->Writer()->Br(falseLabel);
  8015. }
  8016. else if (truefallthrough && !falsefallthrough) {
  8017. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8018. }
  8019. else if (falsefallthrough && !truefallthrough) {
  8020. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8021. }
  8022. }
  8023. break;
  8024. }
  8025. }
  8026. // used by while and for loops
  8027. void EmitLoop(
  8028. ParseNodeLoop *loopNode,
  8029. ParseNode *cond,
  8030. ParseNode *body,
  8031. ParseNode *incr,
  8032. ByteCodeGenerator *byteCodeGenerator,
  8033. FuncInfo *funcInfo,
  8034. BOOL fReturnValue,
  8035. BOOL doWhile = FALSE,
  8036. ParseNodeBlock *forLoopBlock = nullptr)
  8037. {
  8038. // Need to increment loop count whether we are going to profile or not for HasLoop()
  8039. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8040. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8041. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8042. loopNode->loopId = loopId;
  8043. if (doWhile)
  8044. {
  8045. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8046. funcInfo->ReleaseLoc(body);
  8047. if (loopNode->emitLabels)
  8048. {
  8049. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8050. }
  8051. if (!ByteCodeGenerator::IsFalse(cond) ||
  8052. byteCodeGenerator->IsInDebugMode())
  8053. {
  8054. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  8055. }
  8056. funcInfo->ReleaseLoc(cond);
  8057. }
  8058. else
  8059. {
  8060. if (cond)
  8061. {
  8062. if (!(cond->nop == knopInt &&
  8063. cond->AsParseNodeInt()->lw != 0))
  8064. {
  8065. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8066. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  8067. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8068. }
  8069. funcInfo->ReleaseLoc(cond);
  8070. }
  8071. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8072. funcInfo->ReleaseLoc(body);
  8073. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8074. forLoopBlock != nullptr)
  8075. {
  8076. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  8077. }
  8078. if (loopNode->emitLabels)
  8079. {
  8080. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8081. }
  8082. if (incr != nullptr)
  8083. {
  8084. Emit(incr, byteCodeGenerator, funcInfo, false);
  8085. funcInfo->ReleaseLoc(incr);
  8086. }
  8087. byteCodeGenerator->Writer()->Br(loopEntrance);
  8088. }
  8089. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8090. if (loopNode->emitLabels)
  8091. {
  8092. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8093. }
  8094. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8095. }
  8096. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeLoop* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  8097. {
  8098. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  8099. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  8100. // emit branch around original
  8101. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  8102. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  8103. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  8104. // emit original
  8105. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  8106. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  8107. // clear temporary registers since inverted loop may share nodes with
  8108. // emitted original loop
  8109. VisitClearTmpRegs(outerLoop, this, funcInfo);
  8110. // emit branch around inverted
  8111. this->m_writer.Br(afterInvertedLoop);
  8112. this->m_writer.MarkLabel(invertedLoopLabel);
  8113. // Emit a zero trip test for the original outer-loop if the outer-loop
  8114. // has a condition
  8115. if (outerLoop->AsParseNodeFor()->pnodeCond)
  8116. {
  8117. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  8118. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  8119. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  8120. this->m_writer.MarkLabel(zeroTrip);
  8121. funcInfo->ReleaseLoc(testNode);
  8122. }
  8123. // emit inverted
  8124. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  8125. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  8126. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  8127. invertedLoop->pnodeIncr, this, funcInfo, false);
  8128. this->m_writer.MarkLabel(afterInvertedLoop);
  8129. }
  8130. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8131. {
  8132. // get iterator object from the iterable
  8133. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  8134. // throw TypeError if the result is not an object
  8135. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8136. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  8137. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8138. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8139. }
  8140. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8141. {
  8142. // invoke next() on the iterator
  8143. if (nextInputLocation == Js::Constants::NoRegister)
  8144. {
  8145. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  8146. }
  8147. else
  8148. {
  8149. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  8150. }
  8151. // throw TypeError if the result is not an object
  8152. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8153. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  8154. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8155. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8156. }
  8157. // Generating
  8158. // if (hasReturnFunction) {
  8159. // value = Call Retrun;
  8160. // if (value != Object)
  8161. // throw TypeError;
  8162. // }
  8163. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8164. {
  8165. Js::RegSlot returnLocation = funcInfo->AcquireTmpRegister();
  8166. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8167. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8168. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorLocation, Js::PropertyIds::return_, false, false);
  8169. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, returnLocation, iteratorLocation, cacheId);
  8170. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, noReturn, returnLocation, funcInfo->undefinedConstantRegister);
  8171. EmitInvoke(returnLocation, iteratorLocation, Js::PropertyIds::return_, byteCodeGenerator, funcInfo);
  8172. // throw TypeError if the result is not an Object
  8173. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, returnLocation);
  8174. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8175. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8176. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8177. funcInfo->ReleaseTmpRegister(returnLocation);
  8178. }
  8179. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8180. {
  8181. // get the iterator result's "done" property
  8182. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  8183. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  8184. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  8185. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  8186. }
  8187. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8188. {
  8189. // get the iterator result's "value" property
  8190. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  8191. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  8192. }
  8193. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8194. Js::ByteCodeLabel loopEntrance,
  8195. Js::ByteCodeLabel continuePastLoop,
  8196. ByteCodeGenerator *byteCodeGenerator,
  8197. FuncInfo *funcInfo,
  8198. BOOL fReturnValue)
  8199. {
  8200. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8201. loopNode->pnodeLval->nop != knopLetDecl &&
  8202. loopNode->pnodeLval->nop != knopConstDecl)
  8203. {
  8204. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8205. }
  8206. else
  8207. {
  8208. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8209. sym->SetNeedDeclaration(false);
  8210. }
  8211. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8212. {
  8213. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8214. }
  8215. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8216. // The StartStatement is already done in the caller of this function.
  8217. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8218. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8219. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8220. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8221. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8222. {
  8223. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8224. }
  8225. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8226. if (loopNode->emitLabels)
  8227. {
  8228. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8229. }
  8230. byteCodeGenerator->Writer()->Br(loopEntrance);
  8231. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8232. if (loopNode->emitLabels)
  8233. {
  8234. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8235. }
  8236. }
  8237. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8238. Js::ByteCodeLabel loopEntrance,
  8239. Js::ByteCodeLabel continuePastLoop,
  8240. ByteCodeGenerator *byteCodeGenerator,
  8241. FuncInfo *funcInfo,
  8242. BOOL fReturnValue)
  8243. {
  8244. Assert(loopNode->nop == knopForIn);
  8245. Assert(loopNode->location == Js::Constants::NoRegister);
  8246. // Grab registers for the enumerator and for the current enumerated item.
  8247. // The enumerator register will be released after this call returns.
  8248. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8249. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8250. // get enumerator from the collection
  8251. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8252. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8253. byteCodeGenerator->EndStatement(loopNode);
  8254. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8255. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8256. loopNode->loopId = loopId;
  8257. // The EndStatement will happen in the EmitForInOfLoopBody function
  8258. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8259. // branch past loop when MoveAndGetNext returns nullptr
  8260. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8261. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8262. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8263. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8264. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8265. {
  8266. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8267. }
  8268. }
  8269. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8270. {
  8271. bool isForIn = (loopNode->nop == knopForIn);
  8272. Assert(isForIn || loopNode->nop == knopForOf);
  8273. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8274. byteCodeGenerator->StartStatement(loopNode);
  8275. if (!isForIn)
  8276. {
  8277. funcInfo->AcquireLoc(loopNode);
  8278. }
  8279. // Record the branch bytecode offset.
  8280. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8281. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8282. // otherwise use offset of next stmt.
  8283. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8284. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8285. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8286. // See WinBlue 231880 for details.
  8287. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8288. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8289. loopNode->pnodeBlock->HasBlockScopedContent())
  8290. {
  8291. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8292. }
  8293. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8294. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8295. if (loopNode->pnodeLval->nop == knopVarDecl)
  8296. {
  8297. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8298. }
  8299. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8300. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8301. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8302. {
  8303. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8304. if (loopNode->pnodeBlock->scope != nullptr)
  8305. {
  8306. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8307. sym->SetIsTrackedForDebugger(false);
  8308. });
  8309. }
  8310. }
  8311. if (isForIn)
  8312. {
  8313. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8314. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8315. {
  8316. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8317. }
  8318. return;
  8319. }
  8320. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8321. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8322. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8323. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8324. Js::RegSlot regException = Js::Constants::NoRegister;
  8325. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8326. // These two temp variables store the information of return function to be called or not.
  8327. // one variable is used for catch block and one is used for finally block. These variable will be set to true when we think that return function
  8328. // to be called on abrupt loop break.
  8329. // Why two variables? since these are temps and JIT does like not flow if single variable is used in multiple blocks.
  8330. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  8331. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  8332. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8333. if (isCoroutine)
  8334. {
  8335. regException = funcInfo->AcquireTmpRegister();
  8336. regOffset = funcInfo->AcquireTmpRegister();
  8337. }
  8338. // Grab registers for the enumerator and for the current enumerated item.
  8339. // The enumerator register will be released after this call returns.
  8340. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8341. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8342. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8343. // to the profiler and JIT.
  8344. byteCodeGenerator->SetHasFinally(true);
  8345. byteCodeGenerator->SetHasTry(true);
  8346. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8347. // do a ToObject on the collection
  8348. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8349. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8350. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8351. funcInfo->ReleaseTmpRegister(tmpObj);
  8352. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8353. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8354. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8355. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8356. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8357. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8358. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  8359. if (isCoroutine)
  8360. {
  8361. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8362. tryRecForTryFinally.reg1 = regException;
  8363. tryRecForTryFinally.reg2 = regOffset;
  8364. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  8365. }
  8366. else
  8367. {
  8368. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8369. }
  8370. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8371. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  8372. if (isCoroutine)
  8373. {
  8374. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  8375. }
  8376. byteCodeGenerator->EndStatement(loopNode);
  8377. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8378. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8379. loopNode->loopId = loopId;
  8380. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8381. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8382. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8383. EmitIteratorNext(loopNode->itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  8384. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8385. EmitIteratorComplete(doneLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8386. // branch past loop if the result's done property is truthy
  8387. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8388. funcInfo->ReleaseTmpRegister(doneLocation);
  8389. // otherwise put result's value property in itemLocation
  8390. EmitIteratorValue(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8391. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8392. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8393. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8394. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8395. EmitCatchAndFinallyBlocks(catchLabel,
  8396. finallyLabel,
  8397. loopNode->location,
  8398. shouldCallReturnFunctionLocation,
  8399. shouldCallReturnFunctionLocationFinally,
  8400. regException,
  8401. regOffset,
  8402. byteCodeGenerator,
  8403. funcInfo);
  8404. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8405. {
  8406. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8407. }
  8408. }
  8409. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8410. {
  8411. funcInfo->AcquireLoc(pnode);
  8412. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8413. if (args == nullptr)
  8414. {
  8415. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8416. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8417. pnode->location,
  8418. ByteCodeGenerator::DefaultArraySize);
  8419. }
  8420. else
  8421. {
  8422. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8423. }
  8424. }
  8425. void EmitJumpCleanup(ParseNodeStmt *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  8426. {
  8427. for (; pnode != pnodeTarget; pnode = pnode->pnodeOuter)
  8428. {
  8429. switch (pnode->nop)
  8430. {
  8431. case knopTry:
  8432. case knopCatch:
  8433. case knopFinally:
  8434. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8435. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  8436. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  8437. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8438. break;
  8439. case knopForOf:
  8440. #if ENABLE_PROFILE_INFO
  8441. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8442. {
  8443. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8444. }
  8445. #endif
  8446. // The ForOf loop code is wrapped around try..catch..finally - Forcing couple Leave bytecode over here
  8447. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8448. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8449. break;
  8450. #if ENABLE_PROFILE_INFO
  8451. case knopWhile:
  8452. case knopDoWhile:
  8453. case knopFor:
  8454. case knopForIn:
  8455. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8456. {
  8457. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8458. }
  8459. break;
  8460. #endif
  8461. }
  8462. }
  8463. }
  8464. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8465. {
  8466. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8467. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8468. {
  8469. SaveOpndValue(pnode1, funcInfo);
  8470. }
  8471. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8472. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  8473. (pnode2->AsParseNodeClass()->pnodeConstructor == nullptr || pnode2->AsParseNodeClass()->pnodeConstructor->nop != knopVarDecl))
  8474. {
  8475. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  8476. }
  8477. else
  8478. {
  8479. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8480. }
  8481. }
  8482. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8483. {
  8484. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8485. switch (pnode1->nop)
  8486. {
  8487. case knopName:
  8488. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8489. {
  8490. // Given x op y, y may kill x, so stash x.
  8491. // Note that this only matters if we're loading x prior to the op.
  8492. SaveOpndValue(pnode1, funcInfo);
  8493. }
  8494. break;
  8495. case knopDot:
  8496. if (fLoadLhs)
  8497. {
  8498. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8499. funcInfo->AcquireLoc(pnode1);
  8500. }
  8501. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator))
  8502. {
  8503. // Given x.y op z, z may kill x, so stash x away.
  8504. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8505. }
  8506. break;
  8507. case knopIndex:
  8508. if (fLoadLhs)
  8509. {
  8510. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8511. funcInfo->AcquireLoc(pnode1);
  8512. }
  8513. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator) ||
  8514. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2, byteCodeGenerator))
  8515. {
  8516. // Given x[y] op z, y or z may kill x, so stash x away.
  8517. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8518. }
  8519. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2, byteCodeGenerator))
  8520. {
  8521. // Given x[y] op z, z may kill y, so stash y away.
  8522. // But make sure that x gets a register before y.
  8523. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8524. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8525. }
  8526. break;
  8527. }
  8528. if (fLoadLhs)
  8529. {
  8530. // Emit code to load the value of the LHS.
  8531. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8532. }
  8533. else
  8534. {
  8535. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8536. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8537. }
  8538. // Evaluate the RHS.
  8539. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8540. }
  8541. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8542. {
  8543. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8544. if (location != Js::Constants::NoRegister)
  8545. {
  8546. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8547. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8548. }
  8549. }
  8550. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8551. {
  8552. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8553. // if necessary.
  8554. if (sym != nullptr &&
  8555. !sym->GetIsModuleExportStorage() &&
  8556. sym->GetNeedDeclaration() &&
  8557. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8558. sym->GetScope()->GetFunc() == funcInfo)
  8559. {
  8560. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8561. }
  8562. }
  8563. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8564. {
  8565. byteCodeGenerator->StartStatement(pnode);
  8566. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8567. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8568. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8569. funcInfo->AcquireLoc(pnode);
  8570. byteCodeGenerator->Writer()->Reg3(opcode,
  8571. pnode->location,
  8572. pnode->AsParseNodeBin()->pnode1->location,
  8573. pnode->AsParseNodeBin()->pnode2->location);
  8574. byteCodeGenerator->EndStatement(pnode);
  8575. }
  8576. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  8577. {
  8578. Assert(pnodeAdd->nop == knopAdd);
  8579. Assert(pnodeAdd->CanFlattenConcatExpr());
  8580. bool doConcatString = false;
  8581. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8582. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8583. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8584. while (true)
  8585. {
  8586. if (!pnode->CanFlattenConcatExpr())
  8587. {
  8588. concatOpnds.Append(pnode);
  8589. }
  8590. else if (pnode->nop == knopStr)
  8591. {
  8592. concatOpnds.Append(pnode);
  8593. // Detect if there are any string larger then the append size limit.
  8594. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8595. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8596. }
  8597. else
  8598. {
  8599. Assert(pnode->nop == knopAdd);
  8600. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8601. pnode = pnode->AsParseNodeBin()->pnode1;
  8602. continue;
  8603. }
  8604. if (pnodeStack.Empty())
  8605. {
  8606. break;
  8607. }
  8608. pnode = pnodeStack.Head();
  8609. pnodeStack.RemoveHead();
  8610. }
  8611. return doConcatString;
  8612. }
  8613. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8614. {
  8615. byteCodeGenerator->StartStatement(pnode);
  8616. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator) || MayHaveSideEffectOnNode(pnode1, pnode3, byteCodeGenerator))
  8617. {
  8618. SaveOpndValue(pnode1, funcInfo);
  8619. }
  8620. if (MayHaveSideEffectOnNode(pnode2, pnode3, byteCodeGenerator))
  8621. {
  8622. SaveOpndValue(pnode2, funcInfo);
  8623. }
  8624. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8625. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8626. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8627. funcInfo->ReleaseLoc(pnode3);
  8628. funcInfo->ReleaseLoc(pnode2);
  8629. funcInfo->ReleaseLoc(pnode1);
  8630. funcInfo->AcquireLoc(pnode);
  8631. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8632. pnode->location,
  8633. pnode1->location,
  8634. pnode2->location,
  8635. pnode3->location);
  8636. byteCodeGenerator->EndStatement(pnode);
  8637. }
  8638. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8639. {
  8640. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8641. funcInfo->ReleaseLoc(pnode2);
  8642. funcInfo->ReleaseLoc(pnode1);
  8643. funcInfo->AcquireLoc(pnode);
  8644. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8645. pnode->location,
  8646. pnode1->location,
  8647. pnode2->location,
  8648. count);
  8649. }
  8650. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8651. {
  8652. Assert(pnode->nop == knopAdd);
  8653. if (pnode->CanFlattenConcatExpr())
  8654. {
  8655. // We should only have a string concat if the feature is on.
  8656. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8657. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8658. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8659. if (doConcatString)
  8660. {
  8661. uint concatCount = concatOpnds.Count();
  8662. Assert(concatCount >= 2);
  8663. // Don't do concatN if the number is too high
  8664. // CONSIDER: although we could have done multiple ConcatNs
  8665. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8666. {
  8667. #if DBG
  8668. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  8669. #endif
  8670. ParseNode * pnode1 = concatOpnds.Head();
  8671. concatOpnds.RemoveHead();
  8672. ParseNode * pnode2 = concatOpnds.Head();
  8673. concatOpnds.RemoveHead();
  8674. if (concatCount == 3)
  8675. {
  8676. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  8677. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8678. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8679. byteCodeGenerator->Writer()->ByteCodeDataSize());
  8680. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  8681. return;
  8682. }
  8683. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  8684. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8685. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8686. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  8687. byteCodeGenerator->StartStatement(pnode);
  8688. funcInfo->AcquireLoc(pnode);
  8689. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  8690. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  8691. uint i = 2;
  8692. do
  8693. {
  8694. ParseNode * currNode = concatOpnds.Head();
  8695. concatOpnds.RemoveHead();
  8696. ParseNode * currNode2 = concatOpnds.Head();
  8697. concatOpnds.RemoveHead();
  8698. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8699. funcInfo->ReleaseLoc(currNode2);
  8700. funcInfo->ReleaseLoc(currNode);
  8701. byteCodeGenerator->Writer()->Reg3B1(
  8702. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  8703. i += 2;
  8704. } while (concatOpnds.Count() > 1);
  8705. if (!concatOpnds.Empty())
  8706. {
  8707. ParseNode * currNode = concatOpnds.Head();
  8708. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8709. funcInfo->ReleaseLoc(currNode);
  8710. byteCodeGenerator->Writer()->Reg2B1(
  8711. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  8712. i++;
  8713. }
  8714. Assert(concatCount == i);
  8715. byteCodeGenerator->EndStatement(pnode);
  8716. return;
  8717. }
  8718. }
  8719. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  8720. byteCodeGenerator->StartStatement(pnode);
  8721. ParseNode * currNode = concatOpnds.Head();
  8722. concatOpnds.RemoveHead();
  8723. ParseNode * currNode2 = concatOpnds.Head();
  8724. concatOpnds.RemoveHead();
  8725. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8726. funcInfo->ReleaseLoc(currNode2);
  8727. funcInfo->ReleaseLoc(currNode);
  8728. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  8729. byteCodeGenerator->Writer()->Reg3(
  8730. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  8731. while (!concatOpnds.Empty())
  8732. {
  8733. currNode = concatOpnds.Head();
  8734. concatOpnds.RemoveHead();
  8735. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8736. funcInfo->ReleaseLoc(currNode);
  8737. byteCodeGenerator->Writer()->Reg3(
  8738. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  8739. }
  8740. byteCodeGenerator->EndStatement(pnode);
  8741. }
  8742. else
  8743. {
  8744. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  8745. }
  8746. }
  8747. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  8748. {
  8749. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  8750. {
  8751. switch (node->op)
  8752. {
  8753. case Js::OpCode::TryFinallyWithYield:
  8754. this->Writer()->Empty(Js::OpCode::LeaveNull);
  8755. break;
  8756. case Js::OpCode::TryCatch:
  8757. case Js::OpCode::ResumeFinally:
  8758. case Js::OpCode::ResumeCatch:
  8759. this->Writer()->Empty(Js::OpCode::Leave);
  8760. break;
  8761. default:
  8762. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8763. break;
  8764. }
  8765. }
  8766. }
  8767. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8768. {
  8769. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8770. {
  8771. switch (node->op)
  8772. {
  8773. case Js::OpCode::TryCatch:
  8774. this->Writer()->Br(node->op, node->label);
  8775. break;
  8776. case Js::OpCode::TryFinallyWithYield:
  8777. case Js::OpCode::ResumeFinally:
  8778. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8779. break;
  8780. case Js::OpCode::ResumeCatch:
  8781. this->Writer()->Empty(node->op);
  8782. break;
  8783. default:
  8784. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8785. break;
  8786. }
  8787. }
  8788. }
  8789. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator)
  8790. {
  8791. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8792. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8793. if (yieldStarIterator == Js::Constants::NoRegister)
  8794. {
  8795. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8796. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8797. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8798. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8799. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8800. }
  8801. else
  8802. {
  8803. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8804. }
  8805. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8806. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8807. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8808. if (yieldStarIterator == Js::Constants::NoRegister)
  8809. {
  8810. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8811. }
  8812. else
  8813. {
  8814. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8815. }
  8816. }
  8817. void EmitYieldStar(ParseNodeUni* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8818. {
  8819. funcInfo->AcquireLoc(yieldStarNode);
  8820. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8821. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8822. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8823. // Evaluate operand
  8824. Emit(yieldStarNode->pnode1, byteCodeGenerator, funcInfo, false);
  8825. funcInfo->ReleaseLoc(yieldStarNode->pnode1);
  8826. EmitGetIterator(iteratorLocation, yieldStarNode->pnode1->location, byteCodeGenerator, funcInfo);
  8827. // Call the iterator's next()
  8828. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8829. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8830. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8831. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8832. // remember the loopId like the loop statements do.
  8833. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8834. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8835. // branch past the loop if the done property is truthy
  8836. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8837. funcInfo->ReleaseTmpRegister(doneLocation);
  8838. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8839. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8840. byteCodeGenerator->Writer()->Br(loopEntrance);
  8841. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8842. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8843. // Put the iterator result's value in yieldStarNode->location.
  8844. // It will be used as the result value of the yield* operator expression.
  8845. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8846. }
  8847. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8848. {
  8849. if (isSymGlobalAndSingleAssignment)
  8850. {
  8851. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8852. }
  8853. }
  8854. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8855. {
  8856. if (isSymGlobalAndSingleAssignment)
  8857. {
  8858. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8859. }
  8860. }
  8861. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8862. {
  8863. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8864. {
  8865. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8866. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8867. }
  8868. }
  8869. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8870. {
  8871. Assert(objNode->nop == knopObject);
  8872. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  8873. while (memberList != nullptr)
  8874. {
  8875. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  8876. if (memberNode->nop != knopEllipsis)
  8877. {
  8878. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  8879. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  8880. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8881. {
  8882. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  8883. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8884. }
  8885. }
  8886. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  8887. }
  8888. }
  8889. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8890. {
  8891. Assert(knopDotNode->nop == knopDot);
  8892. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  8893. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  8894. bool isSymGlobalAndSingleAssignment = false;
  8895. if (objectNode->nop == knopName)
  8896. {
  8897. if (ByteCodeGenerator::IsThis(objectNode))
  8898. {
  8899. // Assume 'this' always refer to GlobalObject
  8900. // Cases like "this.a = "
  8901. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  8902. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8903. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8904. }
  8905. else
  8906. {
  8907. Symbol * sym = objectNode->AsParseNodeName()->sym;
  8908. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  8909. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8910. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8911. }
  8912. }
  8913. }
  8914. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8915. {
  8916. // Track the Global Int Constant properties' assignments here.
  8917. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8918. if (nodeType & fnopAsg)
  8919. {
  8920. if (nodeType & fnopBin)
  8921. {
  8922. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  8923. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  8924. Assert(lhs && rhs);
  8925. // Don't track other than integers and objects with member nodes.
  8926. if (rhs->nop == knopObject)
  8927. {
  8928. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8929. }
  8930. else if (rhs->nop != knopInt &&
  8931. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  8932. {
  8933. return;
  8934. }
  8935. if (lhs->nop == knopName)
  8936. {
  8937. // Handle "a = <Integer>" cases here
  8938. Symbol * sym = lhs->AsParseNodeName()->sym;
  8939. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8940. }
  8941. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8942. {
  8943. // Cases like "obj.a = <Integer>"
  8944. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8945. }
  8946. }
  8947. else if (nodeType & fnopUni)
  8948. {
  8949. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  8950. if (lhs->nop == knopName)
  8951. {
  8952. // Cases like "a++"
  8953. Symbol * sym = lhs->AsParseNodeName()->sym;
  8954. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8955. }
  8956. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8957. {
  8958. // Cases like "obj.a++"
  8959. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8960. }
  8961. }
  8962. }
  8963. }
  8964. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode, bool isTopLevel)
  8965. {
  8966. if (pnode == nullptr)
  8967. {
  8968. return;
  8969. }
  8970. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8971. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8972. // printNop(pnode->nop);
  8973. switch (pnode->nop)
  8974. {
  8975. case knopList:
  8976. EmitList(pnode, byteCodeGenerator, funcInfo);
  8977. break;
  8978. case knopInt:
  8979. // currently, these are loaded at the top
  8980. break;
  8981. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8982. case knopFlt:
  8983. // currently, these are loaded at the top
  8984. break;
  8985. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8986. case knopStr:
  8987. // TODO: protocol for combining string constants
  8988. break;
  8989. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8990. case knopBigInt:
  8991. // PTNODE(knopBigInt , "bigint const" ,None ,Pid ,fnopLeaf|fnopConst)
  8992. break;
  8993. case knopRegExp:
  8994. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  8995. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  8996. break;
  8997. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8998. case knopNull:
  8999. // enregistered
  9000. break;
  9001. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  9002. case knopFalse:
  9003. // enregistered
  9004. break;
  9005. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  9006. case knopTrue:
  9007. // enregistered
  9008. break;
  9009. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  9010. case knopEmpty:
  9011. break;
  9012. // Unary operators.
  9013. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  9014. case knopNot:
  9015. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9016. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9017. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9018. byteCodeGenerator->Writer()->Reg2(
  9019. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9020. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9021. break;
  9022. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  9023. case knopNeg:
  9024. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9025. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9026. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9027. funcInfo->AcquireLoc(pnode);
  9028. byteCodeGenerator->Writer()->Reg2(
  9029. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9030. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9031. break;
  9032. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  9033. case knopPos:
  9034. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9035. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9036. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9037. byteCodeGenerator->Writer()->Reg2(
  9038. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9039. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9040. break;
  9041. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  9042. case knopLogNot:
  9043. {
  9044. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9045. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9046. // For boolean expressions that compute a result, we have to burn a register for the result
  9047. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9048. // full-on renaming in the back end.
  9049. funcInfo->AcquireLoc(pnode);
  9050. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  9051. {
  9052. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  9053. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  9054. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  9055. }
  9056. else
  9057. {
  9058. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9059. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  9060. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  9061. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9062. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9063. }
  9064. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9065. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9066. break;
  9067. }
  9068. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  9069. case knopEllipsis:
  9070. {
  9071. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9072. // Transparently pass the location of the object or array.
  9073. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9074. break;
  9075. }
  9076. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  9077. case knopIncPost:
  9078. case knopDecPost:
  9079. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  9080. if (pnode->isUsed || fReturnValue)
  9081. {
  9082. byteCodeGenerator->StartStatement(pnode);
  9083. const Js::OpCode op = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  9084. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9085. // Grab a register for the expression result.
  9086. funcInfo->AcquireLoc(pnode);
  9087. // Load the initial value, convert it (this is the expression result), and increment it.
  9088. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9089. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode1->location);
  9090. // Use temporary register if lhs cannot be assigned
  9091. Js::RegSlot incDecResult = pnode1->location;
  9092. if (funcInfo->RegIsConst(incDecResult) ||
  9093. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  9094. {
  9095. incDecResult = funcInfo->AcquireTmpRegister();
  9096. }
  9097. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  9098. Assert(oneReg != Js::Constants::NoRegister);
  9099. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  9100. // Store the incremented value.
  9101. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9102. // Release the incremented value and the l-value.
  9103. if (incDecResult != pnode1->location)
  9104. {
  9105. funcInfo->ReleaseTmpRegister(incDecResult);
  9106. }
  9107. funcInfo->ReleaseLoad(pnode1);
  9108. byteCodeGenerator->EndStatement(pnode);
  9109. break;
  9110. }
  9111. else
  9112. {
  9113. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  9114. }
  9115. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  9116. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  9117. case knopIncPre:
  9118. case knopDecPre:
  9119. {
  9120. byteCodeGenerator->StartStatement(pnode);
  9121. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  9122. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9123. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9124. // (i.e., is a constant).
  9125. const bool need_result_location =
  9126. pnode->isUsed
  9127. || fReturnValue
  9128. || funcInfo->RegIsConst(pnode1->location)
  9129. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  9130. if (need_result_location)
  9131. {
  9132. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9133. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9134. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  9135. // Store the incremented value and release the l-value.
  9136. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  9137. }
  9138. else
  9139. {
  9140. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9141. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  9142. // Store the incremented value and release the l-value.
  9143. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  9144. }
  9145. funcInfo->ReleaseLoad(pnode1);
  9146. byteCodeGenerator->EndStatement(pnode);
  9147. break;
  9148. }
  9149. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  9150. case knopTypeof:
  9151. {
  9152. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9153. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  9154. switch (pnodeOpnd->nop)
  9155. {
  9156. case knopDot:
  9157. {
  9158. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9159. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9160. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  9161. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9162. funcInfo->AcquireLoc(pnode);
  9163. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  9164. break;
  9165. }
  9166. case knopIndex:
  9167. {
  9168. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9169. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9170. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9171. funcInfo->AcquireLoc(pnode);
  9172. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9173. break;
  9174. }
  9175. case knopName:
  9176. {
  9177. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9178. if (pnodeNameOpnd->IsUserIdentifier())
  9179. {
  9180. funcInfo->AcquireLoc(pnode);
  9181. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9182. break;
  9183. }
  9184. // Special names should fallthrough to default case
  9185. }
  9186. default:
  9187. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9188. funcInfo->ReleaseLoc(pnodeOpnd);
  9189. byteCodeGenerator->Writer()->Reg2(
  9190. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9191. break;
  9192. }
  9193. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9194. break;
  9195. }
  9196. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9197. case knopVoid:
  9198. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9199. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9200. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9201. break;
  9202. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9203. case knopArray:
  9204. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9205. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9206. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9207. break;
  9208. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9209. case knopObject:
  9210. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9211. funcInfo->AcquireLoc(pnode);
  9212. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9213. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9214. break;
  9215. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9216. case knopComputedName:
  9217. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9218. if (pnode->location == Js::Constants::NoRegister)
  9219. {
  9220. // The name is some expression with no home location. We can just re-use the register.
  9221. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9222. }
  9223. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9224. {
  9225. // The name had to be protected from side-effects of the RHS.
  9226. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9227. }
  9228. break;
  9229. // Binary and Ternary Operators
  9230. case knopAdd:
  9231. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9232. break;
  9233. case knopSub:
  9234. case knopMul:
  9235. case knopExpo:
  9236. case knopDiv:
  9237. case knopMod:
  9238. case knopOr:
  9239. case knopXor:
  9240. case knopAnd:
  9241. case knopLsh:
  9242. case knopRsh:
  9243. case knopRs2:
  9244. case knopIn:
  9245. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9246. break;
  9247. case knopInstOf:
  9248. {
  9249. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9250. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9251. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9252. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9253. funcInfo->AcquireLoc(pnode);
  9254. uint cacheId = funcInfo->NewIsInstInlineCache();
  9255. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9256. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9257. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9258. }
  9259. break;
  9260. case knopEq:
  9261. case knopEqv:
  9262. case knopNEqv:
  9263. case knopNe:
  9264. case knopLt:
  9265. case knopLe:
  9266. case knopGe:
  9267. case knopGt:
  9268. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9269. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9270. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9271. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9272. funcInfo->AcquireLoc(pnode);
  9273. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9274. pnode->AsParseNodeBin()->pnode2->location);
  9275. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9276. break;
  9277. case knopNew:
  9278. {
  9279. EmitNew(pnode, byteCodeGenerator, funcInfo);
  9280. byteCodeGenerator->EndStatement(pnode);
  9281. break;
  9282. }
  9283. case knopDelete:
  9284. {
  9285. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  9286. byteCodeGenerator->StartStatement(pnode);
  9287. switch (pexpr->nop)
  9288. {
  9289. case knopName:
  9290. {
  9291. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  9292. if (pnodeName->IsSpecialName())
  9293. {
  9294. funcInfo->AcquireLoc(pnode);
  9295. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9296. }
  9297. else
  9298. {
  9299. funcInfo->AcquireLoc(pnode);
  9300. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  9301. }
  9302. break;
  9303. }
  9304. case knopDot:
  9305. {
  9306. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  9307. {
  9308. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  9309. funcInfo->AcquireLoc(pnode);
  9310. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  9311. }
  9312. else
  9313. {
  9314. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9315. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9316. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9317. funcInfo->AcquireLoc(pnode);
  9318. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  9319. funcInfo->FindOrAddReferencedPropertyId(propertyId), byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  9320. }
  9321. break;
  9322. }
  9323. case knopIndex:
  9324. {
  9325. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9326. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  9327. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9328. funcInfo->AcquireLoc(pnode);
  9329. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  9330. break;
  9331. }
  9332. default:
  9333. {
  9334. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  9335. funcInfo->ReleaseLoc(pexpr);
  9336. byteCodeGenerator->Writer()->Reg2(
  9337. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  9338. break;
  9339. }
  9340. }
  9341. byteCodeGenerator->EndStatement(pnode);
  9342. break;
  9343. }
  9344. case knopCall:
  9345. {
  9346. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  9347. byteCodeGenerator->StartStatement(pnodeCall);
  9348. if (pnodeCall->isSuperCall)
  9349. {
  9350. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue);
  9351. }
  9352. else if (pnodeCall->pnodeTarget->nop == knopImport)
  9353. {
  9354. ParseNodePtr args = pnodeCall->pnodeArgs;
  9355. Assert(CountArguments(args) == 2); // import() takes one argument
  9356. Emit(args, byteCodeGenerator, funcInfo, false);
  9357. funcInfo->ReleaseLoc(args);
  9358. funcInfo->AcquireLoc(pnodeCall);
  9359. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  9360. }
  9361. else
  9362. {
  9363. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  9364. {
  9365. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  9366. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  9367. }
  9368. else
  9369. {
  9370. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  9371. }
  9372. }
  9373. byteCodeGenerator->EndStatement(pnode);
  9374. break;
  9375. }
  9376. case knopIndex:
  9377. {
  9378. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9379. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9380. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9381. Js::RegSlot protoLocation = callObjLocation;
  9382. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9383. {
  9384. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9385. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9386. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9387. }
  9388. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9389. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9390. funcInfo->AcquireLoc(pnode);
  9391. byteCodeGenerator->Writer()->Element(
  9392. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  9393. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9394. break;
  9395. }
  9396. // this is MemberExpression as rvalue
  9397. case knopDot:
  9398. {
  9399. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9400. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9401. funcInfo->AcquireLoc(pnode);
  9402. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9403. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9404. Js::RegSlot protoLocation = callObjLocation;
  9405. if (propertyId == Js::PropertyIds::length)
  9406. {
  9407. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9408. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  9409. }
  9410. else if (pnode->IsCallApplyTargetLoad())
  9411. {
  9412. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9413. {
  9414. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9415. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9416. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9417. }
  9418. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9419. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  9420. }
  9421. else
  9422. {
  9423. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9424. {
  9425. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9426. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9427. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9428. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9429. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  9430. }
  9431. else
  9432. {
  9433. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  9434. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  9435. }
  9436. }
  9437. break;
  9438. }
  9439. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  9440. case knopAsg:
  9441. {
  9442. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9443. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9444. byteCodeGenerator->StartStatement(pnode);
  9445. if (pnode->isUsed || fReturnValue)
  9446. {
  9447. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  9448. // which will copy the assigned value there.
  9449. funcInfo->AcquireLoc(pnode);
  9450. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9451. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9452. }
  9453. else
  9454. {
  9455. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9456. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9457. }
  9458. funcInfo->ReleaseLoc(rhs);
  9459. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  9460. {
  9461. funcInfo->ReleaseReference(lhs);
  9462. }
  9463. byteCodeGenerator->EndStatement(pnode);
  9464. break;
  9465. }
  9466. case knopName:
  9467. funcInfo->AcquireLoc(pnode);
  9468. if (ByteCodeGenerator::IsThis(pnode))
  9469. {
  9470. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  9471. }
  9472. else
  9473. {
  9474. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  9475. }
  9476. break;
  9477. case knopComma:
  9478. {
  9479. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9480. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  9481. // Easier to correct this here than to check every binary op in the parser.
  9482. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  9483. pnode1->isUsed = false;
  9484. if (pnode1->nop == knopComma)
  9485. {
  9486. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  9487. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  9488. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  9489. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  9490. SList<ParseNode *> rhsStack(alloc);
  9491. do
  9492. {
  9493. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  9494. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  9495. pnode1->isUsed = false;
  9496. } while (pnode1->nop == knopComma);
  9497. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9498. if (funcInfo->IsTmpReg(pnode1->location))
  9499. {
  9500. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9501. }
  9502. while (!rhsStack.Empty())
  9503. {
  9504. ParseNode *pnodeRhs = rhsStack.Pop();
  9505. pnodeRhs->isUsed = false;
  9506. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  9507. if (funcInfo->IsTmpReg(pnodeRhs->location))
  9508. {
  9509. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  9510. }
  9511. funcInfo->ReleaseLoc(pnodeRhs);
  9512. }
  9513. }
  9514. else
  9515. {
  9516. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9517. if (funcInfo->IsTmpReg(pnode1->location))
  9518. {
  9519. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9520. }
  9521. }
  9522. funcInfo->ReleaseLoc(pnode1);
  9523. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  9524. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  9525. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9526. funcInfo->AcquireLoc(pnode);
  9527. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  9528. {
  9529. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  9530. }
  9531. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9532. }
  9533. break;
  9534. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  9535. // boolean value short-circuits the operation, and to the value of the right-hand expression
  9536. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  9537. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  9538. case knopLogOr:
  9539. {
  9540. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9541. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9542. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9543. // optimizing the previous version where we had a dest for each level
  9544. funcInfo->AcquireLoc(pnode);
  9545. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9546. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9547. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9548. break;
  9549. }
  9550. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  9551. case knopLogAnd:
  9552. {
  9553. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9554. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9555. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9556. // optimizing the previous version where we had a dest for each level
  9557. funcInfo->AcquireLoc(pnode);
  9558. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9559. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9560. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9561. break;
  9562. }
  9563. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  9564. case knopQmark:
  9565. {
  9566. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9567. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9568. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9569. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9570. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9571. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  9572. // For boolean expressions that compute a result, we have to burn a register for the result
  9573. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9574. // full-on renaming in the back end.
  9575. funcInfo->AcquireLoc(pnode);
  9576. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  9577. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  9578. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  9579. // Record the branch bytecode offset
  9580. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9581. byteCodeGenerator->Writer()->Br(skipLabel);
  9582. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9583. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  9584. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  9585. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  9586. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9587. break;
  9588. }
  9589. case knopAsgAdd:
  9590. case knopAsgSub:
  9591. case knopAsgMul:
  9592. case knopAsgDiv:
  9593. case knopAsgExpo:
  9594. case knopAsgMod:
  9595. case knopAsgAnd:
  9596. case knopAsgXor:
  9597. case knopAsgOr:
  9598. case knopAsgLsh:
  9599. case knopAsgRsh:
  9600. case knopAsgRs2:
  9601. {
  9602. byteCodeGenerator->StartStatement(pnode);
  9603. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9604. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9605. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9606. // (i.e., is a constant).
  9607. const bool need_result_location =
  9608. pnode->isUsed
  9609. || fReturnValue
  9610. || funcInfo->RegIsConst(lhs->location)
  9611. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  9612. if (need_result_location)
  9613. {
  9614. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9615. // Grab a register for the initial value and load it.
  9616. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9617. funcInfo->ReleaseLoc(rhs);
  9618. // Do the arithmetic, store the result, and release the l-value.
  9619. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  9620. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  9621. }
  9622. else
  9623. {
  9624. // Grab a register for the initial value and load it. Might modify lhs->location.
  9625. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9626. funcInfo->ReleaseLoc(rhs);
  9627. // Do the arithmetic, store the result, and release the l-value.
  9628. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  9629. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  9630. }
  9631. funcInfo->ReleaseLoad(lhs);
  9632. byteCodeGenerator->EndStatement(pnode);
  9633. break;
  9634. }
  9635. // General nodes.
  9636. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  9637. case knopTempRef:
  9638. // TODO: check whether mov is necessary
  9639. funcInfo->AcquireLoc(pnode);
  9640. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9641. break;
  9642. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  9643. case knopTemp:
  9644. // Emit initialization code
  9645. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  9646. {
  9647. byteCodeGenerator->StartStatement(pnode);
  9648. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  9649. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  9650. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  9651. byteCodeGenerator->EndStatement(pnode);
  9652. }
  9653. break;
  9654. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9655. case knopVarDecl:
  9656. case knopConstDecl:
  9657. case knopLetDecl:
  9658. {
  9659. // Emit initialization code
  9660. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  9661. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  9662. if (initNode != nullptr || pnode->nop == knopLetDecl)
  9663. {
  9664. Symbol *sym = pnode->AsParseNodeVar()->sym;
  9665. Js::RegSlot rhsLocation;
  9666. byteCodeGenerator->StartStatement(pnode);
  9667. if (initNode != nullptr)
  9668. {
  9669. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9670. rhsLocation = initNode->location;
  9671. if (initNode->nop == knopObject)
  9672. {
  9673. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  9674. }
  9675. else if (initNode->nop == knopInt)
  9676. {
  9677. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9678. }
  9679. }
  9680. else
  9681. {
  9682. Assert(pnode->nop == knopLetDecl);
  9683. rhsLocation = funcInfo->AcquireTmpRegister();
  9684. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9685. }
  9686. if (pnode->nop != knopVarDecl)
  9687. {
  9688. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  9689. sym->SetNeedDeclaration(false);
  9690. }
  9691. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  9692. funcInfo->ReleaseTmpRegister(rhsLocation);
  9693. byteCodeGenerator->EndStatement(pnode);
  9694. }
  9695. break;
  9696. }
  9697. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9698. case knopFncDecl:
  9699. // The "function declarations" were emitted in DefineFunctions()
  9700. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  9701. {
  9702. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  9703. }
  9704. break;
  9705. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9706. case knopClassDecl:
  9707. {
  9708. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  9709. funcInfo->AcquireLoc(pnodeClass);
  9710. Assert(pnodeClass->pnodeConstructor);
  9711. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9712. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9713. // Extends
  9714. if (pnodeClass->pnodeExtends)
  9715. {
  9716. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9717. // defer and nondefer parse modes.
  9718. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9719. }
  9720. // Constructor
  9721. Emit(pnodeClass->pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9722. EmitComputedFunctionNameVar(bindPnode, pnodeClass->pnodeConstructor, byteCodeGenerator);
  9723. if (pnodeClass->pnodeExtends)
  9724. {
  9725. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9726. byteCodeGenerator->Writer()->InitClass(pnodeClass->location, pnodeClass->pnodeExtends->location);
  9727. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9728. }
  9729. else
  9730. {
  9731. byteCodeGenerator->Writer()->InitClass(pnodeClass->location);
  9732. }
  9733. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9734. int cacheId = funcInfo->FindOrAddInlineCacheId(pnodeClass->location, Js::PropertyIds::prototype, false, false);
  9735. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnodeClass->location, cacheId);
  9736. // Static Methods
  9737. EmitClassInitializers(pnodeClass->pnodeStaticMembers, pnodeClass->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9738. // Instance Methods
  9739. EmitClassInitializers(pnodeClass->pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9740. funcInfo->ReleaseTmpRegister(protoLoc);
  9741. // Emit name binding.
  9742. if (pnodeClass->pnodeName)
  9743. {
  9744. Symbol * sym = pnodeClass->pnodeName->sym;
  9745. sym->SetNeedDeclaration(false);
  9746. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9747. }
  9748. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9749. if (pnodeClass->pnodeExtends)
  9750. {
  9751. funcInfo->ReleaseLoc(pnodeClass->pnodeExtends);
  9752. }
  9753. if (pnodeClass->pnodeDeclName)
  9754. {
  9755. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9756. sym->SetNeedDeclaration(false);
  9757. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9758. }
  9759. if (pnodeClass->IsDefaultModuleExport())
  9760. {
  9761. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9762. }
  9763. break;
  9764. }
  9765. case knopStrTemplate:
  9766. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9767. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  9768. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9769. break;
  9770. case knopEndCode:
  9771. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9772. // load undefined for the fallthrough case:
  9773. if (!funcInfo->IsGlobalFunction())
  9774. {
  9775. if (funcInfo->IsClassConstructor())
  9776. {
  9777. // For class constructors, we need to explicitly load 'this' into the return register.
  9778. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9779. }
  9780. else
  9781. {
  9782. // In the global function, implicit return values are copied to the return register, and if
  9783. // necessary the return register is initialized at the top. Don't clobber the value here.
  9784. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9785. }
  9786. }
  9787. // Label for non-fall-through return
  9788. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9789. if (funcInfo->GetHasCachedScope())
  9790. {
  9791. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  9792. }
  9793. byteCodeGenerator->StartStatement(pnode);
  9794. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9795. byteCodeGenerator->EndStatement(pnode);
  9796. break;
  9797. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9798. case knopDebugger:
  9799. byteCodeGenerator->StartStatement(pnode);
  9800. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9801. byteCodeGenerator->EndStatement(pnode);
  9802. break;
  9803. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9804. case knopFor:
  9805. {
  9806. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  9807. if (pnodeFor->pnodeInverted != nullptr)
  9808. {
  9809. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  9810. }
  9811. else
  9812. {
  9813. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9814. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  9815. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  9816. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9817. {
  9818. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9819. }
  9820. EmitLoop(pnodeFor,
  9821. pnodeFor->pnodeCond,
  9822. pnodeFor->pnodeBody,
  9823. pnodeFor->pnodeIncr,
  9824. byteCodeGenerator,
  9825. funcInfo,
  9826. fReturnValue,
  9827. FALSE,
  9828. pnodeFor->pnodeBlock);
  9829. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9830. }
  9831. break;
  9832. }
  9833. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9834. case knopIf:
  9835. {
  9836. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  9837. byteCodeGenerator->StartStatement(pnodeIf);
  9838. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9839. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9840. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9841. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  9842. byteCodeGenerator->EndStatement(pnodeIf);
  9843. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9844. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9845. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  9846. if (pnodeIf->pnodeFalse != nullptr)
  9847. {
  9848. // has else clause
  9849. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9850. // Record the branch bytecode offset
  9851. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9852. // then clause skips else clause
  9853. byteCodeGenerator->Writer()->Br(skipLabel);
  9854. // generate code for else clause
  9855. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9856. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9857. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  9858. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9859. }
  9860. else
  9861. {
  9862. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9863. }
  9864. if (pnodeIf->emitLabels)
  9865. {
  9866. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  9867. }
  9868. break;
  9869. }
  9870. case knopWhile:
  9871. {
  9872. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9873. EmitLoop(pnodeWhile,
  9874. pnodeWhile->pnodeCond,
  9875. pnodeWhile->pnodeBody,
  9876. nullptr,
  9877. byteCodeGenerator,
  9878. funcInfo,
  9879. fReturnValue);
  9880. break;
  9881. }
  9882. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9883. case knopDoWhile:
  9884. {
  9885. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9886. EmitLoop(pnodeWhile,
  9887. pnodeWhile->pnodeCond,
  9888. pnodeWhile->pnodeBody,
  9889. nullptr,
  9890. byteCodeGenerator,
  9891. funcInfo,
  9892. fReturnValue,
  9893. true);
  9894. break;
  9895. }
  9896. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9897. case knopForIn:
  9898. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9899. break;
  9900. case knopForOf:
  9901. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9902. break;
  9903. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9904. case knopReturn:
  9905. {
  9906. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  9907. byteCodeGenerator->StartStatement(pnodeReturn);
  9908. if (pnodeReturn->pnodeExpr != nullptr)
  9909. {
  9910. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  9911. {
  9912. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9913. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9914. }
  9915. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9916. if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9917. {
  9918. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  9919. }
  9920. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9921. }
  9922. else
  9923. {
  9924. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9925. }
  9926. if (funcInfo->IsClassConstructor())
  9927. {
  9928. // return expr; // becomes like below:
  9929. //
  9930. // if (IsObject(expr)) {
  9931. // return expr;
  9932. // } else if (IsBaseClassConstructor) {
  9933. // return this;
  9934. // } else if (!IsUndefined(expr)) {
  9935. // throw TypeError;
  9936. // }
  9937. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9938. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9939. if (funcInfo->IsBaseClassConstructor())
  9940. {
  9941. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  9942. }
  9943. else
  9944. {
  9945. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9946. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9947. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9948. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9949. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9950. }
  9951. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9952. }
  9953. if (pnodeReturn->grfnop & fnopCleanup)
  9954. {
  9955. EmitJumpCleanup(pnodeReturn, nullptr, byteCodeGenerator, funcInfo);
  9956. }
  9957. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9958. byteCodeGenerator->EndStatement(pnodeReturn);
  9959. break;
  9960. }
  9961. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9962. case knopBlock:
  9963. {
  9964. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  9965. if (pnodeBlock->pnodeStmt != nullptr)
  9966. {
  9967. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  9968. if (pnodeBlock->emitLabels)
  9969. {
  9970. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  9971. }
  9972. }
  9973. break;
  9974. }
  9975. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9976. case knopWith:
  9977. {
  9978. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  9979. Assert(pnodeWith->pnodeObj != nullptr);
  9980. byteCodeGenerator->StartStatement(pnodeWith);
  9981. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9982. // is overwritten in the body, the lookups are not affected.
  9983. funcInfo->AcquireLoc(pnodeWith);
  9984. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  9985. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnodeWith->location;
  9986. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  9987. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9988. {
  9989. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewWithObject, pnodeWith->location, regVal);
  9990. }
  9991. byteCodeGenerator->EndStatement(pnodeWith);
  9992. #ifdef PERF_HINT
  9993. if (PHASE_TRACE1(Js::PerfHintPhase))
  9994. {
  9995. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9996. }
  9997. #endif
  9998. if (pnodeWith->pnodeBody != nullptr)
  9999. {
  10000. Scope *scope = pnodeWith->scope;
  10001. scope->SetLocation(pnodeWith->location);
  10002. byteCodeGenerator->PushScope(scope);
  10003. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  10004. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  10005. {
  10006. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  10007. }
  10008. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10009. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  10010. byteCodeGenerator->PopScope();
  10011. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  10012. }
  10013. if (pnodeWith->emitLabels)
  10014. {
  10015. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  10016. }
  10017. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  10018. {
  10019. funcInfo->ReleaseTmpRegister(regVal);
  10020. }
  10021. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  10022. break;
  10023. }
  10024. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10025. case knopBreak:
  10026. {
  10027. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10028. Assert(pnodeJump->pnodeTarget->emitLabels);
  10029. byteCodeGenerator->StartStatement(pnodeJump);
  10030. if (pnodeJump->grfnop & fnopCleanup)
  10031. {
  10032. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  10033. }
  10034. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  10035. if (pnodeJump->emitLabels)
  10036. {
  10037. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  10038. }
  10039. byteCodeGenerator->EndStatement(pnodeJump);
  10040. break;
  10041. }
  10042. case knopContinue:
  10043. {
  10044. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10045. Assert(pnodeJump->pnodeTarget->emitLabels);
  10046. byteCodeGenerator->StartStatement(pnodeJump);
  10047. if (pnodeJump->grfnop & fnopCleanup)
  10048. {
  10049. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  10050. }
  10051. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  10052. byteCodeGenerator->EndStatement(pnodeJump);
  10053. break;
  10054. }
  10055. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10056. case knopSwitch:
  10057. {
  10058. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  10059. BOOL fHasDefault = false;
  10060. Assert(pnodeSwitch->pnodeVal != nullptr);
  10061. byteCodeGenerator->StartStatement(pnodeSwitch);
  10062. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  10063. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10064. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  10065. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10066. byteCodeGenerator->EndStatement(pnodeSwitch);
  10067. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  10068. // code so the BE can optimize it.
  10069. ParseNodeCase *pnodeCase;
  10070. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10071. {
  10072. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  10073. // expression take place regardless.
  10074. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  10075. if (pnodeCase == pnodeSwitch->pnodeDefault)
  10076. {
  10077. fHasDefault = true;
  10078. continue;
  10079. }
  10080. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10081. byteCodeGenerator->Writer()->BrReg2(
  10082. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  10083. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  10084. }
  10085. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  10086. if (fHasDefault)
  10087. {
  10088. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  10089. }
  10090. else
  10091. {
  10092. if (!pnodeSwitch->emitLabels)
  10093. {
  10094. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  10095. }
  10096. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  10097. }
  10098. // Now emit the case arms to which we jump on matching a case value.
  10099. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10100. {
  10101. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  10102. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10103. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  10104. }
  10105. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10106. funcInfo->ReleaseTmpRegister(regVal);
  10107. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  10108. if (!fHasDefault || pnodeSwitch->emitLabels)
  10109. {
  10110. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  10111. }
  10112. break;
  10113. }
  10114. case knopTryCatch:
  10115. {
  10116. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  10117. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  10118. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  10119. Assert(pnodeTry);
  10120. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  10121. Assert(pnodeCatch);
  10122. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  10123. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  10124. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  10125. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  10126. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  10127. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  10128. if (funcInfo->byteCodeFunction->IsCoroutine())
  10129. {
  10130. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10131. }
  10132. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10133. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10134. if (funcInfo->byteCodeFunction->IsCoroutine())
  10135. {
  10136. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10137. }
  10138. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  10139. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10140. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  10141. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  10142. ParseNode *pnodeObj = pnodeCatch->GetParam();
  10143. Assert(pnodeObj);
  10144. Js::RegSlot location;
  10145. bool acquiredTempLocation = false;
  10146. Js::DebuggerScope *debuggerScope = nullptr;
  10147. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  10148. bool isPattern = pnodeObj->nop == knopParamPattern;
  10149. if (isPattern)
  10150. {
  10151. location = pnodeObj->AsParseNodeParamPattern()->location;
  10152. }
  10153. else
  10154. {
  10155. location = pnodeObj->AsParseNodeName()->sym->GetLocation();
  10156. }
  10157. if (location == Js::Constants::NoRegister)
  10158. {
  10159. location = funcInfo->AcquireLoc(pnodeObj);
  10160. acquiredTempLocation = true;
  10161. }
  10162. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10163. Scope *scope = pnodeCatch->scope;
  10164. byteCodeGenerator->PushScope(scope);
  10165. if (scope->GetMustInstantiate())
  10166. {
  10167. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10168. if (scope->GetIsObject())
  10169. {
  10170. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10171. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10172. }
  10173. else
  10174. {
  10175. int index = Js::DebuggerScope::InvalidScopeIndex;
  10176. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10177. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10178. }
  10179. }
  10180. else
  10181. {
  10182. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10183. }
  10184. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10185. {
  10186. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10187. {
  10188. Assert(scope->GetMustInstantiate());
  10189. if (scope->GetIsObject())
  10190. {
  10191. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10192. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10193. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10194. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10195. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10196. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10197. }
  10198. else
  10199. {
  10200. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10201. if (initializeParam)
  10202. {
  10203. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10204. }
  10205. else
  10206. {
  10207. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10208. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10209. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10210. funcInfo->ReleaseTmpRegister(tmpReg);
  10211. }
  10212. }
  10213. }
  10214. else
  10215. {
  10216. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10217. if (initializeParam)
  10218. {
  10219. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10220. }
  10221. else
  10222. {
  10223. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10224. }
  10225. }
  10226. };
  10227. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10228. if (isPattern)
  10229. {
  10230. Parser::MapBindIdentifier(pnodeObj->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  10231. {
  10232. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10233. if (itemLocation == Js::Constants::NoRegister)
  10234. {
  10235. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10236. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10237. itemLocation = ByteCodeGenerator::ReturnRegister;
  10238. }
  10239. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10240. });
  10241. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10242. // Now emitting bytecode for destructuring pattern
  10243. byteCodeGenerator->StartStatement(pnodeCatch);
  10244. ParseNodePtr pnode1 = pnodeObj->AsParseNodeParamPattern()->pnode1;
  10245. Assert(pnode1->IsPattern());
  10246. if (funcInfo->byteCodeFunction->IsCoroutine())
  10247. {
  10248. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10249. }
  10250. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10251. byteCodeGenerator->EndStatement(pnodeCatch);
  10252. }
  10253. else
  10254. {
  10255. ParamTrackAndInitialization(pnodeObj->AsParseNodeName()->sym, true /*initializeParam*/, location);
  10256. if (scope->GetMustInstantiate())
  10257. {
  10258. pnodeObj->AsParseNodeName()->sym->SetIsGlobalCatch(true);
  10259. }
  10260. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10261. // Allow a debugger to stop on the 'catch (e)'
  10262. byteCodeGenerator->StartStatement(pnodeCatch);
  10263. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10264. byteCodeGenerator->EndStatement(pnodeCatch);
  10265. if (funcInfo->byteCodeFunction->IsCoroutine())
  10266. {
  10267. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10268. }
  10269. }
  10270. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10271. if (funcInfo->byteCodeFunction->IsCoroutine())
  10272. {
  10273. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10274. }
  10275. byteCodeGenerator->PopScope();
  10276. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10277. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10278. if (acquiredTempLocation)
  10279. {
  10280. funcInfo->ReleaseLoc(pnodeObj);
  10281. }
  10282. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10283. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10284. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10285. break;
  10286. }
  10287. case knopTryFinally:
  10288. {
  10289. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10290. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10291. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10292. Assert(pnodeTry);
  10293. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10294. Assert(pnodeFinally);
  10295. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10296. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10297. Js::RegSlot regException = Js::Constants::NoRegister;
  10298. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10299. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10300. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10301. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10302. // For now, if the function is generator we are using the TryFinallyWithYield.
  10303. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  10304. if (funcInfo->byteCodeFunction->IsCoroutine())
  10305. {
  10306. regException = funcInfo->AcquireTmpRegister();
  10307. regOffset = funcInfo->AcquireTmpRegister();
  10308. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10309. tryRecForTry.reg1 = regException;
  10310. tryRecForTry.reg2 = regOffset;
  10311. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10312. }
  10313. else
  10314. {
  10315. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10316. }
  10317. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10318. funcInfo->StartRecordingOutArgs(1);
  10319. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10320. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10321. if (funcInfo->byteCodeFunction->IsCoroutine())
  10322. {
  10323. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10324. }
  10325. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10326. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10327. // Note: although we don't use OpCode::Leave for finally block,
  10328. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10329. // This has to be on offset prior to offset of 1st statement of finally.
  10330. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10331. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10332. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10333. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10334. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  10335. if (funcInfo->byteCodeFunction->IsCoroutine())
  10336. {
  10337. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  10338. }
  10339. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10340. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  10341. if (funcInfo->byteCodeFunction->IsCoroutine())
  10342. {
  10343. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10344. funcInfo->ReleaseTmpRegister(regOffset);
  10345. funcInfo->ReleaseTmpRegister(regException);
  10346. }
  10347. funcInfo->EndRecordingOutArgs(1);
  10348. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10349. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  10350. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  10351. break;
  10352. }
  10353. case knopThrow:
  10354. byteCodeGenerator->StartStatement(pnode);
  10355. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10356. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  10357. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10358. byteCodeGenerator->EndStatement(pnode);
  10359. break;
  10360. case knopYieldLeaf:
  10361. byteCodeGenerator->StartStatement(pnode);
  10362. funcInfo->AcquireLoc(pnode);
  10363. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  10364. byteCodeGenerator->EndStatement(pnode);
  10365. break;
  10366. case knopAwait:
  10367. case knopYield:
  10368. byteCodeGenerator->StartStatement(pnode);
  10369. funcInfo->AcquireLoc(pnode);
  10370. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10371. EmitYield(pnode->AsParseNodeUni()->pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  10372. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10373. byteCodeGenerator->EndStatement(pnode);
  10374. break;
  10375. case knopYieldStar:
  10376. byteCodeGenerator->StartStatement(pnode);
  10377. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  10378. byteCodeGenerator->EndStatement(pnode);
  10379. break;
  10380. case knopExportDefault:
  10381. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10382. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  10383. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  10384. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  10385. break;
  10386. default:
  10387. AssertMsg(0, "emit unhandled pnode op");
  10388. break;
  10389. }
  10390. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  10391. {
  10392. // If this statement may produce the global function's return value, copy its result to the return register.
  10393. // fReturnValue implies global function, which implies that "return" is a parse error.
  10394. Assert(funcInfo->IsGlobalFunction());
  10395. Assert(pnode->nop != knopReturn);
  10396. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  10397. }
  10398. }