ByteCodeEmitter.cpp 462 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741
  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)
  32. {
  33. // Try to determine whether pnodeSE 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. uint fnop = ParseNode::Grfnop(pnodeSE->nop);
  44. if (fnop & fnopLeaf)
  45. {
  46. // pnodeSE is a leaf and can't kill anything.
  47. return false;
  48. }
  49. if (fnop & fnopAsg)
  50. {
  51. // pnodeSE is an assignment (=, ++, +=, etc.)
  52. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  53. // maybe because of code layout or some other subtle effect.
  54. return true;
  55. }
  56. if (fnop & fnopUni)
  57. {
  58. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  59. if (pnodeSE->nop == knopTempRef)
  60. {
  61. return false;
  62. }
  63. else
  64. {
  65. return pnodeSE->AsParseNodeUni()->pnode1 && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeUni()->pnode1);
  66. }
  67. }
  68. else if (fnop & fnopBin)
  69. {
  70. // pnodeSE is a binary (or ternary) op, so recurse to the sources (if present).
  71. return MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeBin()->pnode1) ||
  72. (pnodeSE->AsParseNodeBin()->pnode2 && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeBin()->pnode2));
  73. }
  74. else if (pnodeSE->nop == knopQmark)
  75. {
  76. ParseNodeTri * pnodeTriSE = pnodeSE->AsParseNodeTri();
  77. return MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode1) ||
  78. MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode2) ||
  79. MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode3);
  80. }
  81. else if (pnodeSE->nop == knopCall || pnodeSE->nop == knopNew)
  82. {
  83. return MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeCall()->pnodeTarget) ||
  84. (pnodeSE->AsParseNodeCall()->pnodeArgs && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeCall()->pnodeArgs));
  85. }
  86. else if (pnodeSE->nop == knopList)
  87. {
  88. return true;
  89. }
  90. return false;
  91. }
  92. bool IsCallOfConstants(ParseNode *pnode);
  93. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  94. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  95. bool IsArguments(ParseNode *pnode)
  96. {
  97. for (;;)
  98. {
  99. switch (pnode->nop)
  100. {
  101. case knopName:
  102. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  103. case knopCall:
  104. case knopNew:
  105. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  106. {
  107. return true;
  108. }
  109. if (pnode->AsParseNodeCall()->pnodeArgs)
  110. {
  111. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  112. while (pnodeArg->nop == knopList)
  113. {
  114. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  115. return true;
  116. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  117. }
  118. pnode = pnodeArg;
  119. break;
  120. }
  121. return false;
  122. case knopArray:
  123. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  124. {
  125. return false;
  126. }
  127. pnode = pnode->AsParseNodeUni()->pnode1;
  128. break;
  129. case knopQmark:
  130. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  131. {
  132. return true;
  133. }
  134. pnode = pnode->AsParseNodeTri()->pnode3;
  135. break;
  136. //
  137. // Cases where we don't check for "arguments" yet.
  138. // Assume that they might have it. Disable the optimization is such scenarios
  139. //
  140. case knopList:
  141. case knopObject:
  142. case knopVarDecl:
  143. case knopConstDecl:
  144. case knopLetDecl:
  145. case knopFncDecl:
  146. case knopClassDecl:
  147. case knopFor:
  148. case knopIf:
  149. case knopDoWhile:
  150. case knopWhile:
  151. case knopForIn:
  152. case knopForOf:
  153. case knopReturn:
  154. case knopBlock:
  155. case knopBreak:
  156. case knopContinue:
  157. case knopTypeof:
  158. case knopThrow:
  159. case knopWith:
  160. case knopFinally:
  161. case knopTry:
  162. case knopTryCatch:
  163. case knopTryFinally:
  164. case knopArrayPattern:
  165. case knopObjectPattern:
  166. case knopParamPattern:
  167. return true;
  168. default:
  169. {
  170. uint flags = ParseNode::Grfnop(pnode->nop);
  171. if (flags&fnopUni)
  172. {
  173. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  174. Assert(pnodeUni->pnode1);
  175. pnode = pnodeUni->pnode1;
  176. break;
  177. }
  178. else if (flags&fnopBin)
  179. {
  180. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  181. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  182. if (IsArguments(pnodeBin->pnode1))
  183. {
  184. return true;
  185. }
  186. pnode = pnodeBin->pnode2;
  187. break;
  188. }
  189. return false;
  190. }
  191. }
  192. }
  193. }
  194. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  195. void Emit(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, bool isConstructorCall = false, Js::RegSlot bindingNameLocation = Js::Constants::NoRegister, bool isTopLevel = false);
  196. void EmitBinaryOpnds(ParseNode* pnode1, ParseNode* pnode2, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot computedPropertyLocation = Js::Constants::NoRegister);
  197. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  198. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  199. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  200. static const Js::OpCode nopToOp[knopLim] =
  201. {
  202. #define OP(x) Br##x##_A
  203. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  204. #include "ptlist.h"
  205. };
  206. static const Js::OpCode nopToCMOp[knopLim] =
  207. {
  208. #define OP(x) Cm##x##_A
  209. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  210. #include "ptlist.h"
  211. };
  212. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  213. {
  214. switch (op)
  215. {
  216. case Js::OpCode::StLocalSlot:
  217. return Js::OpCode::StLocalSlotChkUndecl;
  218. case Js::OpCode::StParamSlot:
  219. return Js::OpCode::StParamSlotChkUndecl;
  220. case Js::OpCode::StInnerSlot:
  221. return Js::OpCode::StInnerSlotChkUndecl;
  222. case Js::OpCode::StEnvSlot:
  223. return Js::OpCode::StEnvSlotChkUndecl;
  224. case Js::OpCode::StObjSlot:
  225. return Js::OpCode::StObjSlotChkUndecl;
  226. case Js::OpCode::StLocalObjSlot:
  227. return Js::OpCode::StLocalObjSlotChkUndecl;
  228. case Js::OpCode::StParamObjSlot:
  229. return Js::OpCode::StParamObjSlotChkUndecl;
  230. case Js::OpCode::StInnerObjSlot:
  231. return Js::OpCode::StInnerObjSlotChkUndecl;
  232. case Js::OpCode::StEnvObjSlot:
  233. return Js::OpCode::StEnvObjSlotChkUndecl;
  234. default:
  235. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  236. return Js::OpCode::InvalidOpCode;
  237. }
  238. }
  239. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  240. // debuggerScope - The scope to add the variable to.
  241. // symbol - The symbol that represents the register property.
  242. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  243. // flags - The flags to assign to the property.
  244. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  245. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  246. Js::DebuggerScope *debuggerScope,
  247. Symbol *symbol,
  248. FuncInfo *funcInfo,
  249. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  250. bool isFunctionDeclaration /*= false*/)
  251. {
  252. Assert(debuggerScope);
  253. Assert(symbol);
  254. Assert(funcInfo);
  255. Js::RegSlot location = symbol->GetLocation();
  256. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  257. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  258. {
  259. // We have to get the appropriate scope and add property over there.
  260. // Make sure the scope is created whether we're in debug mode or not, because we
  261. // need the empty scopes present during reparsing for debug mode.
  262. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  263. }
  264. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  265. {
  266. // Only track the property if we're in debug mode since it's only needed by the debugger.
  267. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  268. this->Writer()->AddPropertyToDebuggerScope(
  269. correctDebuggerScope,
  270. location,
  271. propertyId,
  272. /*shouldConsumeRegister*/ true,
  273. flags,
  274. isFunctionDeclaration);
  275. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  276. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  277. symbol->SetIsTrackedForDebugger(true);
  278. }
  279. }
  280. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  281. Js::DebuggerScope *debuggerScope,
  282. Symbol *symbol,
  283. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  284. bool isFunctionDeclaration /*= false*/)
  285. {
  286. Assert(debuggerScope);
  287. Assert(symbol);
  288. // Only need to track activation object properties in debug mode.
  289. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  290. {
  291. Js::RegSlot location = symbol->GetLocation();
  292. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  293. this->Writer()->AddPropertyToDebuggerScope(
  294. debuggerScope,
  295. location,
  296. propertyId,
  297. /*shouldConsumeRegister*/ false,
  298. flags,
  299. isFunctionDeclaration);
  300. symbol->SetIsTrackedForDebugger(true);
  301. }
  302. }
  303. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  304. Js::DebuggerScope *debuggerScope,
  305. Symbol* symbol,
  306. Js::PropertyId propertyId,
  307. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  308. bool isFunctionDeclaration /*= false*/)
  309. {
  310. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  311. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  312. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  313. Assert(debuggerScope);
  314. Assert(symbol);
  315. if (!symbol->GetIsTrackedForDebugger())
  316. {
  317. Js::RegSlot location = symbol->GetScopeSlot();
  318. Assert(location != Js::Constants::NoRegister);
  319. Assert(propertyId != Js::Constants::NoProperty);
  320. this->Writer()->AddPropertyToDebuggerScope(
  321. debuggerScope,
  322. location,
  323. propertyId,
  324. /*shouldConsumeRegister*/ false,
  325. flags,
  326. isFunctionDeclaration);
  327. symbol->SetIsTrackedForDebugger(true);
  328. }
  329. }
  330. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  331. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  332. {
  333. Assert(functionDeclarationSymbol);
  334. Assert(funcInfoParent);
  335. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  336. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  337. // which is done in other Track* functions that we call.
  338. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  339. {
  340. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  341. {
  342. this->TrackActivationObjectPropertyForDebugger(
  343. this->Writer()->GetCurrentDebuggerScope(),
  344. functionDeclarationSymbol,
  345. Js::DebuggerScopePropertyFlags_None,
  346. true /*isFunctionDeclaration*/);
  347. }
  348. else
  349. {
  350. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  351. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  352. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  353. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  354. functionDeclarationSymbol->EnsurePosition(this);
  355. this->TrackSlotArrayPropertyForDebugger(
  356. this->Writer()->GetCurrentDebuggerScope(),
  357. functionDeclarationSymbol,
  358. functionDeclarationSymbol->GetPosition(),
  359. Js::DebuggerScopePropertyFlags_None,
  360. true /*isFunctionDeclaration*/);
  361. }
  362. }
  363. else
  364. {
  365. this->TrackRegisterPropertyForDebugger(
  366. this->Writer()->GetCurrentDebuggerScope(),
  367. functionDeclarationSymbol,
  368. funcInfoParent,
  369. Js::DebuggerScopePropertyFlags_None,
  370. true /*isFunctionDeclaration*/);
  371. }
  372. }
  373. // Updates the byte code offset of the property with the passed in location and ID.
  374. // Used to track let/const variables that are in the dead zone debugger side.
  375. // location - The activation object, scope slot index, or register location for the property.
  376. // propertyId - The ID of the property to update.
  377. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  378. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  379. {
  380. Assert(this->Writer());
  381. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  382. Assert(currentDebuggerScope);
  383. if (currentDebuggerScope != nullptr)
  384. {
  385. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  386. currentDebuggerScope,
  387. location,
  388. propertyId,
  389. shouldConsumeRegister);
  390. }
  391. }
  392. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  393. {
  394. if (funcInfo->GetHasCachedScope())
  395. {
  396. this->LoadCachedHeapArguments(funcInfo);
  397. }
  398. else
  399. {
  400. this->LoadUncachedHeapArguments(funcInfo);
  401. }
  402. }
  403. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  404. {
  405. Assert(funcInfo);
  406. Assert(propIds);
  407. Assert(byteCodeGenerator);
  408. bool hadDuplicates = false;
  409. Js::ArgSlot i = 0;
  410. auto processArg = [&](ParseNode *pnode)
  411. {
  412. if (pnode->IsVarLetOrConst())
  413. {
  414. Assert(i < propIds->count);
  415. Symbol *sym = pnode->AsParseNodeVar()->sym;
  416. Assert(sym);
  417. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  418. //
  419. // Check if the function has any same name parameters
  420. // For the same name param, only the last one will be passed the correct propertyid
  421. // For remaining dup param names, pass Constants::NoProperty
  422. //
  423. for (Js::ArgSlot j = 0; j < i; j++)
  424. {
  425. if (propIds->elements[j] == symPos)
  426. {
  427. // Found a dup parameter name
  428. propIds->elements[j] = Js::Constants::NoProperty;
  429. hadDuplicates = true;
  430. break;
  431. }
  432. }
  433. propIds->elements[i] = symPos;
  434. }
  435. else
  436. {
  437. propIds->elements[i] = Js::Constants::NoProperty;
  438. }
  439. ++i;
  440. };
  441. MapFormals(funcInfo->root, processArg);
  442. propIds->hadDuplicates = hadDuplicates;
  443. }
  444. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  445. {
  446. Assert(funcInfo->GetHasHeapArguments());
  447. Scope *scope = funcInfo->GetBodyScope();
  448. Assert(scope);
  449. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  450. Assert(argSym && argSym->IsArguments());
  451. Js::RegSlot argumentsLoc = argSym->GetLocation();
  452. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  453. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  454. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  455. if (count == 0)
  456. {
  457. // If no formals to function (only "this"), then no need to create the scope object.
  458. // Leave both the arguments location and the propertyIds location as null.
  459. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  460. }
  461. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  462. {
  463. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  464. }
  465. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  466. {
  467. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  468. // at the expected location.
  469. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  470. GetFormalArgsArray(this, funcInfo, propIds);
  471. }
  472. this->m_writer.Reg1(opcode, argumentsLoc);
  473. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  474. }
  475. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  476. {
  477. Assert(funcInfo->GetHasHeapArguments());
  478. Scope *scope = funcInfo->GetBodyScope();
  479. Assert(scope);
  480. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  481. Assert(argSym && argSym->IsArguments());
  482. Js::RegSlot argumentsLoc = argSym->GetLocation();
  483. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  484. this->m_writer.Reg1(op, argumentsLoc);
  485. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  486. }
  487. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  488. {
  489. Assert(stringNodeList);
  490. uint index = 0;
  491. Js::Var str;
  492. IdentPtr pid;
  493. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  494. while (stringNodeList->nop == knopList)
  495. {
  496. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  497. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  498. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  499. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  500. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  501. index++;
  502. }
  503. Assert(stringNodeList->nop == knopStr);
  504. pid = stringNodeList->AsParseNodeStr()->pid;
  505. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  506. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  507. return pArr;
  508. }
  509. // For now, this just assigns field ids for the current script.
  510. // Later, we will combine this information with the global field id map.
  511. // This temporary code will not work if a global member is accessed both with and without a LHS.
  512. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  513. {
  514. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  515. {
  516. this->AssignPropertyId(sym, functionInfo);
  517. });
  518. }
  519. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  520. {
  521. Assert(pnodeBlock->nop == knopBlock);
  522. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  523. {
  524. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  525. // the debugger scope will not be created.
  526. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  527. FuncInfo *funcInfo = this->TopFuncInfo();
  528. Symbol *sym = pnode->AsParseNodeVar()->sym;
  529. Scope *scope = sym->GetScope();
  530. if (sym->GetIsGlobal())
  531. {
  532. Js::PropertyId propertyId = sym->EnsurePosition(this);
  533. if (this->flags & fscrEval)
  534. {
  535. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  536. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  537. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  538. }
  539. else
  540. {
  541. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  542. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  543. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  544. }
  545. }
  546. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  547. {
  548. if (scope->GetIsObject())
  549. {
  550. Js::RegSlot scopeLocation = scope->GetLocation();
  551. Js::PropertyId propertyId = sym->EnsurePosition(this);
  552. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  553. {
  554. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  555. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  556. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  557. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  558. }
  559. else
  560. {
  561. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  562. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  563. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  564. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  565. }
  566. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  567. }
  568. else
  569. {
  570. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  571. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  572. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  573. funcInfo->ReleaseTmpRegister(tmpReg);
  574. // Slot array properties are tracked in non-debug mode as well because they need to stay
  575. // around for heap enumeration and escaping during attach/detach.
  576. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  577. }
  578. }
  579. else if (!sym->GetIsModuleExportStorage())
  580. {
  581. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  582. {
  583. // let/const declared in a switch is the only case of a variable that must be checked for
  584. // use-before-declaration dynamically within its own function.
  585. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  586. }
  587. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  588. // will live only in slots, so tell the debugger to find them there.
  589. if (sym->NeedsSlotAlloc(this, funcInfo))
  590. {
  591. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  592. }
  593. else
  594. {
  595. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  596. }
  597. }
  598. };
  599. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  600. }
  601. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  602. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  603. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  604. {
  605. Assert(pnode);
  606. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  607. {
  608. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  609. // don't add a block to the chain if it has no let/const variables at all.
  610. return nullptr;
  611. }
  612. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  613. }
  614. // Records the end of the current scope, but only if the current block has block scoped content.
  615. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  616. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  617. {
  618. Assert(pnodeBlock);
  619. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  620. {
  621. return;
  622. }
  623. this->Writer()->RecordEndScopeObject();
  624. }
  625. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  626. {
  627. Js::DebuggerScope* debuggerScope = nullptr;
  628. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  629. {
  630. Scope *scope = pnodeBlock->scope;
  631. byteCodeGenerator->PushScope(scope);
  632. Js::RegSlot scopeLocation = scope->GetLocation();
  633. if (scope->GetMustInstantiate())
  634. {
  635. Assert(scopeLocation == Js::Constants::NoRegister);
  636. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  637. if (scope->GetIsObject())
  638. {
  639. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  640. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  641. }
  642. else
  643. {
  644. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  645. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  646. // TODO: Handle heap enumeration
  647. int scopeSlotCount = scope->GetScopeSlotCount();
  648. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  649. }
  650. }
  651. else
  652. {
  653. // In the direct register access case, there is no block scope emitted but we can still track
  654. // the start and end offset of the block. The location registers for let/const variables will still be
  655. // captured along with this range in InitBlockScopedContent().
  656. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  657. }
  658. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  659. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  660. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  661. ParseNodePtr pnodeScope;
  662. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  663. {
  664. switch (pnodeScope->nop)
  665. {
  666. case knopFncDecl:
  667. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  668. {
  669. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  670. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  671. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  672. // So we'll supply a temp that we allocate and release here.
  673. if (frameDisplayLoc == Js::Constants::NoRegister)
  674. {
  675. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  676. {
  677. frameDisplayLoc = funcInfo->frameDisplayRegister;
  678. }
  679. else
  680. {
  681. frameDisplayLoc = funcInfo->GetEnvRegister();
  682. }
  683. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  684. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  685. }
  686. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  687. }
  688. // If this is the global eval block scope, the function is actually assigned to the global
  689. // so we don't need to keep the registers.
  690. if (isGlobalEvalBlockScope)
  691. {
  692. funcInfo->ReleaseLoc(pnodeScope);
  693. pnodeScope->location = Js::Constants::NoRegister;
  694. }
  695. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  696. break;
  697. case knopBlock:
  698. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  699. break;
  700. case knopCatch:
  701. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  702. break;
  703. case knopWith:
  704. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  705. break;
  706. }
  707. }
  708. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  709. {
  710. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  711. }
  712. }
  713. else
  714. {
  715. Scope *scope = pnodeBlock->scope;
  716. if (scope)
  717. {
  718. if (scope->GetMustInstantiate())
  719. {
  720. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  721. }
  722. else
  723. {
  724. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  725. }
  726. }
  727. else
  728. {
  729. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  730. }
  731. }
  732. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  733. }
  734. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  735. {
  736. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  737. {
  738. Scope *scope = pnodeBlock->scope;
  739. Assert(scope);
  740. Assert(scope == byteCodeGenerator->GetCurrentScope());
  741. byteCodeGenerator->PopScope();
  742. }
  743. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  744. }
  745. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  746. {
  747. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  748. {
  749. // Only let variables have observable behavior when there are per iteration
  750. // bindings. const variables do not since they are immutable. Therefore,
  751. // (and the spec agrees), only create new scope clones if the loop variable
  752. // is a let declaration.
  753. bool isConst = false;
  754. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  755. // Exploit the fact that a for loop sxBlock can only have let and const
  756. // declarations, and can only have one or the other, regardless of how
  757. // many syms there might be. Thus only check the first sym.
  758. isConst = sym->GetDecl()->nop == knopConstDecl;
  759. return true;
  760. });
  761. if (!isConst)
  762. {
  763. Scope *scope = pnodeBlock->scope;
  764. Assert(scope == byteCodeGenerator->GetCurrentScope());
  765. if (scope->GetMustInstantiate())
  766. {
  767. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  768. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  769. }
  770. }
  771. }
  772. }
  773. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  774. {
  775. Assert(pnodeBlock->nop == knopBlock);
  776. ParseNode *pnode = pnodeBlock->pnodeStmt;
  777. if (pnode == nullptr)
  778. {
  779. return;
  780. }
  781. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  782. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  783. while (pnode->nop == knopList)
  784. {
  785. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  786. if (stmt == pnodeLastValStmt)
  787. {
  788. // This is the last guaranteed return value, so any potential return values have to be
  789. // copied to the return register from this point forward.
  790. pnodeLastValStmt = nullptr;
  791. }
  792. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  793. pnode = pnode->AsParseNodeBin()->pnode2;
  794. }
  795. if (pnode == pnodeLastValStmt)
  796. {
  797. pnodeLastValStmt = nullptr;
  798. }
  799. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  800. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  801. }
  802. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  803. {
  804. if (emitFunc->IsTmpReg(pnode->location))
  805. {
  806. pnode->location = Js::Constants::NoRegister;
  807. }
  808. }
  809. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  810. {
  811. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  812. {
  813. // Function declarations (not function-declaration RHS's) are already fully processed.
  814. // Skip them here so the temp registers don't get messed up.
  815. return;
  816. }
  817. if (stmt->nop == knopName || stmt->nop == knopDot)
  818. {
  819. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  820. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  821. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  822. StartStatement(stmt);
  823. Writer()->Empty(Js::OpCode::Nop);
  824. EndStatement(stmt);
  825. }
  826. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, Js::Constants::NoRegister/*computedPropertyLocation*/, true/*isTopLevel*/);
  827. if (funcInfo->IsTmpReg(stmt->location))
  828. {
  829. if (!stmt->isUsed && !fReturnValue)
  830. {
  831. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  832. }
  833. funcInfo->ReleaseLoc(stmt);
  834. }
  835. }
  836. // ByteCodeGenerator::DefineFunctions
  837. //
  838. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  839. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  840. // to make sure that sources of the stores have been defined.
  841. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  842. {
  843. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  844. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  845. if (funcInfoParent->GetHasCachedScope())
  846. {
  847. this->DefineCachedFunctions(funcInfoParent);
  848. }
  849. else
  850. {
  851. this->DefineUncachedFunctions(funcInfoParent);
  852. }
  853. }
  854. // Iterate over all child functions in a function's parameter and body scopes.
  855. template<typename Fn>
  856. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  857. {
  858. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  859. {
  860. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  861. {
  862. switch (pnode->nop)
  863. {
  864. case knopFncDecl:
  865. fn(pnode);
  866. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  867. break;
  868. case knopBlock:
  869. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  870. break;
  871. case knopCatch:
  872. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  873. break;
  874. case knopWith:
  875. pnode = pnode->AsParseNodeWith()->pnodeNext;
  876. break;
  877. default:
  878. AssertMsg(false, "Unexpected opcode in tree of scopes");
  879. return;
  880. }
  881. }
  882. };
  883. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  884. }
  885. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  886. {
  887. ParseNode *pnodeParent = funcInfoParent->root;
  888. uint slotCount = 0;
  889. auto countFncSlots = [&](ParseNode *pnodeFnc)
  890. {
  891. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  892. {
  893. slotCount++;
  894. }
  895. };
  896. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  897. if (slotCount == 0)
  898. {
  899. return;
  900. }
  901. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  902. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  903. if (extraBytesActual > INT_MAX)
  904. {
  905. Js::Throw::OutOfMemory();
  906. }
  907. int extraBytes = (int)extraBytesActual;
  908. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  909. // slotCount is guaranteed to be non-zero here.
  910. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  911. slotCount = 0;
  912. auto fillEntries = [&](ParseNode *pnodeFnc)
  913. {
  914. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  915. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration()))
  916. {
  917. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  918. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  919. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  920. entry->scopeSlot = sym->GetScopeSlot();
  921. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  922. slotCount++;
  923. }
  924. };
  925. MapContainerScopeFunctions(pnodeParent, fillEntries);
  926. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  927. info,
  928. sizeof(Js::FuncInfoArray) + extraBytes,
  929. sizeof(Js::FuncInfoArray) + extraBytes);
  930. slotCount = 0;
  931. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  932. {
  933. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  934. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  935. {
  936. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  937. // Only happens if the sym is null (e.g., function x.y(){}).
  938. if (sym == nullptr)
  939. {
  940. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  941. }
  942. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  943. {
  944. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  945. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  946. }
  947. // The "x = function() {...}" case is being generated on the fly, during emission,
  948. // so the caller expects to be able to release this register.
  949. funcInfoParent->ReleaseLoc(pnodeFnc);
  950. pnodeFnc->location = Js::Constants::NoRegister;
  951. slotCount++;
  952. }
  953. };
  954. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  955. AdeletePlus(alloc, extraBytes, info);
  956. }
  957. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  958. {
  959. ParseNode *pnodeParent = funcInfoParent->root;
  960. auto defineCheck = [&](ParseNode *pnodeFnc)
  961. {
  962. Assert(pnodeFnc->nop == knopFncDecl);
  963. //
  964. // Don't define the function upfront in following cases
  965. // 1. x = function() {...};
  966. // Don't define the function for all modes.
  967. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  968. // rather than the scope entry to save a register (and possibly save the whole definition).
  969. //
  970. // 2. x = function f() {...};
  971. // f is not visible in the enclosing scope.
  972. // Such function expressions should be emitted only at the assignment point, as can be used only
  973. // after the assignment. Might save register.
  974. //
  975. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  976. {
  977. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  978. // The "x = function() {...}" case is being generated on the fly, during emission,
  979. // so the caller expects to be able to release this register.
  980. funcInfoParent->ReleaseLoc(pnodeFnc);
  981. pnodeFnc->location = Js::Constants::NoRegister;
  982. }
  983. };
  984. MapContainerScopeFunctions(pnodeParent, defineCheck);
  985. }
  986. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  987. {
  988. // Assign the location holding the func object reference to the given name.
  989. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  990. Symbol *sym = pnodeFnc->pnodeName->sym;
  991. if (sym != nullptr && !sym->GetIsFuncExpr())
  992. {
  993. if (sym->GetIsModuleExportStorage())
  994. {
  995. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  996. }
  997. else if (sym->GetIsGlobal())
  998. {
  999. Js::PropertyId propertyId = sym->GetPosition();
  1000. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1001. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1002. {
  1003. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1004. }
  1005. }
  1006. else
  1007. {
  1008. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1009. {
  1010. if (!sym->GetHasNonCommittedReference() ||
  1011. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1012. {
  1013. // No point in trying to optimize if there are no references before we have to commit to slot.
  1014. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1015. sym->SetIsCommittedToSlot();
  1016. }
  1017. }
  1018. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1019. {
  1020. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1021. }
  1022. else
  1023. {
  1024. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1025. }
  1026. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1027. if (fncScopeSym)
  1028. {
  1029. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1030. {
  1031. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1032. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1033. }
  1034. else
  1035. {
  1036. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1043. {
  1044. Assert(pnodeFnc->nop == knopFncDecl);
  1045. funcInfoParent->AcquireLoc(pnodeFnc);
  1046. if (regEnv == Js::Constants::NoRegister)
  1047. {
  1048. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1049. if (frameDisplayTemp != Js::Constants::NoRegister)
  1050. {
  1051. // We allocated a temp to hold a local frame display value. Use that.
  1052. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1053. regEnv = frameDisplayTemp;
  1054. }
  1055. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1056. {
  1057. // This function has built a frame display, so pass it down.
  1058. regEnv = funcInfoParent->frameDisplayRegister;
  1059. }
  1060. else
  1061. {
  1062. // This function has no captured locals but inherits a closure environment, so pass it down.
  1063. regEnv = funcInfoParent->GetEnvRegister();
  1064. }
  1065. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1066. }
  1067. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1068. // "We need a closure for the nested function");
  1069. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1070. // 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
  1071. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1072. {
  1073. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1074. }
  1075. else
  1076. {
  1077. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1078. }
  1079. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1080. {
  1081. // A function declared at global scope in eval is untrackable,
  1082. // so make sure the caller's cached scope is invalidated.
  1083. this->funcEscapes = true;
  1084. }
  1085. else
  1086. {
  1087. if (pnodeFnc->IsDeclaration())
  1088. {
  1089. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1090. if (funcSymbol)
  1091. {
  1092. // In the case where a let/const declaration is the same symbol name
  1093. // as the function declaration (shadowing case), the let/const var and
  1094. // the function declaration symbol are the same and share the same flags
  1095. // (particularly, sym->GetIsBlockVar() for this code path).
  1096. //
  1097. // For example:
  1098. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1099. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1100. //
  1101. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1102. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1103. //
  1104. // In order to tell if the function is actually part
  1105. // of a block scope, we compare against the function scope here.
  1106. // Note that having a function with the same name as a let/const declaration
  1107. // is a redeclaration error, but we're pushing the fix for this out since it's
  1108. // a bit involved.
  1109. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1110. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1111. // Track all vars/lets/consts register slot function declarations.
  1112. if (ShouldTrackDebuggerMetadata()
  1113. // If this is a let binding function declaration at global level, we want to
  1114. // be sure to track the register location as well.
  1115. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1116. {
  1117. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1118. {
  1119. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1120. }
  1121. }
  1122. if (isFunctionDeclarationInBlock)
  1123. {
  1124. // We only track inner let bindings for the debugger side.
  1125. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. if (pnodeFnc->IsDefaultModuleExport())
  1131. {
  1132. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1133. }
  1134. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1135. {
  1136. return regEnv;
  1137. }
  1138. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1139. return regEnv;
  1140. }
  1141. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1142. {
  1143. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1144. // by an existing initialization.
  1145. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1146. ParseNode *pnode;
  1147. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1148. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1149. // Just assign one on the fly and re-use it for all initializations.
  1150. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1151. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1152. {
  1153. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1154. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1155. {
  1156. if (sym->IsSpecialSymbol())
  1157. {
  1158. // Special symbols have already had their initial values stored into their registers.
  1159. // In default-argument case we've stored those values into their slot locations, as well.
  1160. // We must do that because a default parameter may access a special symbol through a scope slot.
  1161. // In the non-default-argument case, though, we didn't yet store the values into the
  1162. // slots so let's do that now.
  1163. if (!funcInfo->root->HasNonSimpleParameterList())
  1164. {
  1165. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1166. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1167. {
  1168. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1169. }
  1170. }
  1171. continue;
  1172. }
  1173. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1174. {
  1175. // The init node was bound to the catch object, because it's inside a catch and has the
  1176. // same name as the catch object. But we want to define a user var at function scope,
  1177. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1178. // This also applies to a var declaration in the same scope as a let declaration.
  1179. #if DBG
  1180. if (sym->IsArguments())
  1181. {
  1182. // There is a block scoped var named arguments
  1183. Assert(!funcInfo->GetHasArguments());
  1184. continue;
  1185. }
  1186. else if (!sym->GetIsCatch())
  1187. {
  1188. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1189. Assert(funcInfo->bodyScope != sym->GetScope());
  1190. }
  1191. #endif
  1192. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1193. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1194. }
  1195. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1196. {
  1197. if (fGlobal)
  1198. {
  1199. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1200. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1201. // But we first need to make sure we're not trashing built-ins.
  1202. if (this->flags & fscrEval)
  1203. {
  1204. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1205. {
  1206. // Check/Init the property of the frame object
  1207. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1208. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1209. }
  1210. else
  1211. {
  1212. // The check and the init involve the first element in the scope chain.
  1213. this->m_writer.ElementScopedU(
  1214. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1215. }
  1216. }
  1217. else
  1218. {
  1219. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1220. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1221. }
  1222. }
  1223. else if (!sym->IsArguments())
  1224. {
  1225. if (sym->NeedsSlotAlloc(this, funcInfo))
  1226. {
  1227. if (!sym->GetHasNonCommittedReference() ||
  1228. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1229. {
  1230. // No point in trying to optimize if there are no references before we have to commit to slot.
  1231. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1232. sym->SetIsCommittedToSlot();
  1233. }
  1234. }
  1235. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1236. // is delayed) or a property of an object.
  1237. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1238. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1239. {
  1240. Js::RegSlot reg = sym->GetLocation();
  1241. if (reg == Js::Constants::NoRegister)
  1242. {
  1243. Assert(sym->IsInSlot(this, funcInfo));
  1244. reg = funcInfo->AcquireTmpRegister();
  1245. }
  1246. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1247. this->EmitLocalPropInit(reg, sym, funcInfo);
  1248. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1249. {
  1250. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1251. }
  1252. funcInfo->ReleaseTmpRegister(reg);
  1253. }
  1254. }
  1255. else if (ShouldTrackDebuggerMetadata())
  1256. {
  1257. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1258. {
  1259. Js::RegSlot reg = sym->GetLocation();
  1260. if (reg != Js::Constants::NoRegister)
  1261. {
  1262. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1263. }
  1264. }
  1265. }
  1266. sym->SetHasInit(TRUE);
  1267. }
  1268. }
  1269. }
  1270. if (tmpReg != Js::Constants::NoRegister)
  1271. {
  1272. funcInfo->ReleaseTmpRegister(tmpReg);
  1273. }
  1274. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1275. {
  1276. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1277. }
  1278. }
  1279. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1280. {
  1281. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1282. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1283. // This protects us from, for instance, trying to restore garbage on bailout.
  1284. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1285. // garbage on exit from jitted loop bodies.
  1286. while (pnode)
  1287. {
  1288. switch (pnode->nop)
  1289. {
  1290. case knopFncDecl:
  1291. {
  1292. // If this is a block-scoped function, initialize it.
  1293. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1294. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1295. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1296. {
  1297. Symbol *sym = pnodeName->sym;
  1298. Assert(sym);
  1299. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1300. sym->GetScope()->IsBlockScope(funcInfo) &&
  1301. sym->GetScope()->GetFunc() == funcInfo)
  1302. {
  1303. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1304. }
  1305. }
  1306. // No need to recurse to the nested scopes, as they belong to a nested function.
  1307. pnode = pnodeFnc->pnodeNext;
  1308. break;
  1309. }
  1310. case knopBlock:
  1311. {
  1312. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1313. Scope *scope = pnodeBlock->scope;
  1314. if (scope)
  1315. {
  1316. if (scope->IsBlockScope(funcInfo))
  1317. {
  1318. Js::RegSlot scopeLoc = scope->GetLocation();
  1319. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1320. {
  1321. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1322. }
  1323. }
  1324. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1325. {
  1326. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1327. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1328. {
  1329. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1330. }
  1331. };
  1332. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1333. }
  1334. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1335. pnode = pnodeBlock->pnodeNext;
  1336. break;
  1337. }
  1338. case knopCatch:
  1339. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1340. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1341. break;
  1342. case knopWith:
  1343. {
  1344. Js::RegSlot withLoc = pnode->location;
  1345. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1346. "We should put with objects at known stack locations in debug mode");
  1347. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1348. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1349. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1350. break;
  1351. }
  1352. default:
  1353. Assert(false);
  1354. return;
  1355. }
  1356. }
  1357. }
  1358. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1359. {
  1360. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1361. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1362. {
  1363. return;
  1364. }
  1365. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1366. uint slotCount = currentScope->GetScopeSlotCount();
  1367. uint cachedFuncCount = 0;
  1368. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1369. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1370. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1371. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1372. // Create and fill the array of local property ID's.
  1373. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1374. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1375. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1376. ParseNode *pnode;
  1377. Symbol *sym;
  1378. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1379. {
  1380. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1381. }
  1382. if (funcInfo->GetHasArguments())
  1383. {
  1384. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1385. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1386. Js::PropertyId slot = 0;
  1387. auto initArg = [&](ParseNode *pnode)
  1388. {
  1389. if (pnode->IsVarLetOrConst())
  1390. {
  1391. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1392. Assert(sym);
  1393. if (sym->GetScopeSlot() == slot)
  1394. {
  1395. // This is the last appearance of the formal, so record the ID.
  1396. Symbol::SaveToPropIdArray(sym, propIds, this);
  1397. }
  1398. else
  1399. {
  1400. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1401. // since this slot can't be accessed by name.
  1402. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1403. propIds->elements[slot] = Js::Constants::NoProperty;
  1404. }
  1405. }
  1406. else
  1407. {
  1408. // This is for patterns
  1409. propIds->elements[slot] = Js::Constants::NoProperty;
  1410. }
  1411. slot++;
  1412. };
  1413. MapFormalsWithoutRest(pnodeFnc, initArg);
  1414. // If the rest is in the slot - we need to keep that slot.
  1415. if (pnodeFnc->pnodeRest != nullptr && pnodeFnc->pnodeRest->sym->IsInSlot(this, funcInfo))
  1416. {
  1417. Symbol::SaveToPropIdArray(pnodeFnc->pnodeRest->sym, propIds, this);
  1418. }
  1419. }
  1420. else
  1421. {
  1422. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1423. {
  1424. if (pnode->IsVarLetOrConst())
  1425. {
  1426. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1427. }
  1428. });
  1429. }
  1430. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1431. {
  1432. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1433. {
  1434. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1435. if (pnodeName != nullptr)
  1436. {
  1437. while (pnodeName->nop == knopList)
  1438. {
  1439. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1440. {
  1441. sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1442. if (sym)
  1443. {
  1444. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1445. }
  1446. }
  1447. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1448. }
  1449. if (pnodeName->nop == knopVarDecl)
  1450. {
  1451. sym = pnodeName->AsParseNodeVar()->sym;
  1452. if (sym)
  1453. {
  1454. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1455. cachedFuncCount++;
  1456. }
  1457. }
  1458. }
  1459. }
  1460. };
  1461. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1462. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1463. {
  1464. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1465. {
  1466. sym = pnode->AsParseNodeVar()->sym;
  1467. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1468. {
  1469. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1470. {
  1471. sym = currentScope->FindLocalSymbol(sym->GetName());
  1472. }
  1473. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1474. }
  1475. }
  1476. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1477. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1478. {
  1479. sym = pnode->AsParseNodeVar()->sym;
  1480. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1481. }
  1482. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1483. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1484. {
  1485. sym = pnode->AsParseNodeVar()->sym;
  1486. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1487. }
  1488. }
  1489. else
  1490. {
  1491. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1492. }
  1493. // Write the first func slot and first var slot into the auxiliary data
  1494. Js::PropertyId *slots = propIds->elements + slotCount;
  1495. slots[0] = cachedFuncCount;
  1496. slots[1] = firstFuncSlot;
  1497. slots[2] = firstVarSlot;
  1498. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1499. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1500. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1501. }
  1502. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1503. {
  1504. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1505. {
  1506. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1507. }
  1508. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1509. {
  1510. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1511. byteCodeFunction->SetHasScopeObject(true);
  1512. }
  1513. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1514. {
  1515. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1516. }
  1517. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1518. {
  1519. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1520. }
  1521. }
  1522. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1523. {
  1524. if (byteCodeFunction->IsCoroutine())
  1525. {
  1526. // EmitYield uses 'false' to create the IteratorResult object
  1527. funcInfo->AssignFalseConstRegister();
  1528. }
  1529. if (funcInfo->NeedEnvRegister())
  1530. {
  1531. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1532. funcInfo->AssignEnvRegister(constReg);
  1533. }
  1534. // Set the function body's constant count before emitting anything so that the byte code writer
  1535. // can distinguish constants from variables.
  1536. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1537. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1538. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1539. {
  1540. // Give permanent registers to the inner scopes in debug mode.
  1541. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1542. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1543. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1544. // EmitOneFunction.
  1545. uint innerScopeCount = funcInfo->InnerScopeCount();
  1546. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1547. if (innerScopeCount)
  1548. {
  1549. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1550. for (uint i = 1; i < innerScopeCount; i++)
  1551. {
  1552. funcInfo->NextVarRegister();
  1553. }
  1554. }
  1555. }
  1556. // NOTE: The FB expects the yield reg to be the final non-temp.
  1557. if (byteCodeFunction->IsCoroutine())
  1558. {
  1559. funcInfo->AssignYieldRegister();
  1560. }
  1561. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1562. funcInfo->SetFirstTmpReg(firstTmpReg);
  1563. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1564. }
  1565. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1566. {
  1567. // Record slots info for ScopeSlots/ScopeObject.
  1568. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1569. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1570. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1571. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1572. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1573. {
  1574. return;
  1575. }
  1576. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1577. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1578. {
  1579. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1580. }
  1581. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1582. if (scopeSlotCount)
  1583. {
  1584. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1585. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1586. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1587. "The slot array size is different between debug and non-debug mode");
  1588. #if DEBUG
  1589. for (UINT i = 0; i < scopeSlotCount; i++)
  1590. {
  1591. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1592. }
  1593. #endif
  1594. auto setPropertyIdForScopeSlotArray =
  1595. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1596. (Js::PropertyId slot, Js::PropertyId propId)
  1597. {
  1598. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1599. {
  1600. Js::Throw::FatalInternalError();
  1601. }
  1602. propertyIdsForScopeSlotArray[slot] = propId;
  1603. };
  1604. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1605. {
  1606. if (sym->NeedsSlotAlloc(this, funcInfo))
  1607. {
  1608. // All properties should get correct propertyId here.
  1609. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1610. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1611. }
  1612. };
  1613. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1614. #if DEBUG
  1615. for (UINT i = 0; i < scopeSlotCount; i++)
  1616. {
  1617. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1618. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1619. }
  1620. #endif
  1621. }
  1622. }
  1623. // temporarily load all constants and special registers in a single block
  1624. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1625. {
  1626. Symbol *sym;
  1627. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1628. byteCodeFunction->CreateConstantTable();
  1629. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1630. {
  1631. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1632. }
  1633. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1634. {
  1635. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1636. }
  1637. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1638. {
  1639. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1640. }
  1641. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1642. {
  1643. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1644. }
  1645. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1646. {
  1647. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1648. if (!funcInfo->GetApplyEnclosesArgs())
  1649. {
  1650. this->EmitScopeObjectInit(funcInfo);
  1651. }
  1652. #if DBG
  1653. uint count = 0;
  1654. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1655. {
  1656. if (sym->NeedsSlotAlloc(this, funcInfo))
  1657. {
  1658. // All properties should get correct propertyId here.
  1659. count++;
  1660. }
  1661. });
  1662. if (funcInfo->GetParamScope() != nullptr)
  1663. {
  1664. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1665. {
  1666. if (sym->NeedsSlotAlloc(this, funcInfo))
  1667. {
  1668. // All properties should get correct propertyId here.
  1669. count++;
  1670. }
  1671. });
  1672. }
  1673. // A reparse should result in the same size of the activation object.
  1674. // Exclude functions which were created from the ByteCodeCache.
  1675. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1676. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1677. "The activation object size is different between debug and non-debug mode");
  1678. byteCodeFunction->scopeObjectSize = count;
  1679. #endif
  1680. }
  1681. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1682. {
  1683. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1684. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1685. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1686. {
  1687. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1688. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1689. }
  1690. }
  1691. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1692. {
  1693. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1694. byteCodeFunction->SetEnvDepth((uint16)-1);
  1695. }
  1696. bool thisLoadedFromParams = false;
  1697. if (funcInfo->NeedEnvRegister())
  1698. {
  1699. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1700. if (funcInfo->GetIsTopLevelEventHandler())
  1701. {
  1702. if (funcInfo->GetThisSymbol())
  1703. {
  1704. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1705. }
  1706. // The environment is the namespace hierarchy starting with "this".
  1707. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1708. thisLoadedFromParams = true;
  1709. this->InvalidateCachedOuterScopes(funcInfo);
  1710. }
  1711. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1712. {
  1713. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1714. if (funcInfo->GetIsStrictMode())
  1715. {
  1716. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1717. }
  1718. else
  1719. {
  1720. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1721. }
  1722. }
  1723. else
  1724. {
  1725. // environment may be required to load "this"
  1726. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1727. this->InvalidateCachedOuterScopes(funcInfo);
  1728. }
  1729. }
  1730. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1731. {
  1732. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1733. }
  1734. this->RecordAllIntConstants(funcInfo);
  1735. this->RecordAllStrConstants(funcInfo);
  1736. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1737. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1738. {
  1739. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1740. });
  1741. // WARNING !!!
  1742. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1743. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1744. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1745. if (funcInfo->GetHasArguments())
  1746. {
  1747. sym = funcInfo->GetArgumentsSymbol();
  1748. Assert(sym);
  1749. Assert(funcInfo->GetHasHeapArguments());
  1750. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1751. {
  1752. this->LoadHeapArguments(funcInfo);
  1753. }
  1754. }
  1755. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1756. {
  1757. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1758. if (count != 0)
  1759. {
  1760. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1761. GetFormalArgsArray(this, funcInfo, propIds);
  1762. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1763. }
  1764. }
  1765. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1766. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1767. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1768. if (funcInfo->IsClassConstructor())
  1769. {
  1770. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1771. }
  1772. // new.target may be used to construct the 'this' register so make sure to load it first
  1773. if (funcInfo->GetNewTargetSymbol())
  1774. {
  1775. this->LoadNewTargetObject(funcInfo);
  1776. }
  1777. if (funcInfo->GetThisSymbol())
  1778. {
  1779. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1780. }
  1781. else if (ShouldLoadConstThis(funcInfo))
  1782. {
  1783. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1784. }
  1785. if (funcInfo->GetSuperSymbol())
  1786. {
  1787. this->LoadSuperObject(funcInfo);
  1788. }
  1789. if (funcInfo->GetSuperConstructorSymbol())
  1790. {
  1791. this->LoadSuperConstructorObject(funcInfo);
  1792. }
  1793. //
  1794. // If the function is a function expression with a name,
  1795. // load the function object at runtime to its activation object.
  1796. //
  1797. sym = funcInfo->root->GetFuncSymbol();
  1798. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1799. if (funcExprWithName)
  1800. {
  1801. if (funcInfo->GetFuncExprNameReference() ||
  1802. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1803. {
  1804. //
  1805. // x = function f(...) { ... }
  1806. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1807. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1808. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1809. // scope's register namespace. So use a tmp register.
  1810. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1811. // from it's register namespace, which LdFuncExpr can use.
  1812. //
  1813. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1814. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1815. if (sym->IsInSlot(this, funcInfo))
  1816. {
  1817. Js::RegSlot scopeLocation;
  1818. AnalysisAssert(funcInfo->funcExprScope);
  1819. if (funcInfo->funcExprScope->GetIsObject())
  1820. {
  1821. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1822. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1823. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1824. }
  1825. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1826. {
  1827. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1828. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1829. }
  1830. else
  1831. {
  1832. Assert(sym->HasScopeSlot());
  1833. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1834. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1835. }
  1836. }
  1837. else if (ShouldTrackDebuggerMetadata())
  1838. {
  1839. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1840. }
  1841. }
  1842. }
  1843. }
  1844. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1845. {
  1846. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1847. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1848. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1849. uint32 envIndex = 0;
  1850. while (scope && scope->GetFunc() == funcInfo)
  1851. {
  1852. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1853. scope = scope->GetEnclosingScope();
  1854. }
  1855. for (; scope; scope = scope->GetEnclosingScope())
  1856. {
  1857. FuncInfo *func = scope->GetFunc();
  1858. if (scope == func->GetBodyScope())
  1859. {
  1860. if (func->Escapes() && func->GetHasCachedScope())
  1861. {
  1862. AssertOrFailFast(scope->GetIsObject());
  1863. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1864. }
  1865. }
  1866. if (scope->GetMustInstantiate())
  1867. {
  1868. envIndex++;
  1869. }
  1870. }
  1871. }
  1872. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1873. {
  1874. Symbol* thisSym = funcInfo->GetThisSymbol();
  1875. Assert(thisSym);
  1876. Assert(!funcInfo->IsLambda());
  1877. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1878. {
  1879. // Derived class constructors initialize 'this' to be Undecl
  1880. // - we'll check this value during a super call and during 'this' access
  1881. //
  1882. // Base class constructors initialize 'this' to a new object using new.target
  1883. if (funcInfo->IsBaseClassConstructor())
  1884. {
  1885. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1886. Assert(newTargetSym);
  1887. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1888. }
  1889. else
  1890. {
  1891. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1892. }
  1893. }
  1894. else if (!funcInfo->IsGlobalFunction())
  1895. {
  1896. //
  1897. // thisLoadedFromParams would be true for the event Handler case,
  1898. // "this" would have been loaded from parameters to put in the environment
  1899. //
  1900. if (!thisLoadedFromParams)
  1901. {
  1902. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1903. m_writer.ArgIn0(tmpReg);
  1904. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1905. funcInfo->ReleaseTmpRegister(tmpReg);
  1906. }
  1907. else
  1908. {
  1909. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1910. }
  1911. }
  1912. else
  1913. {
  1914. Assert(funcInfo->IsGlobalFunction());
  1915. Js::RegSlot root = funcInfo->nullConstantRegister;
  1916. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1917. }
  1918. }
  1919. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1920. {
  1921. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1922. Assert(newTargetSym);
  1923. if (funcInfo->IsClassConstructor())
  1924. {
  1925. Assert(!funcInfo->IsLambda());
  1926. m_writer.ArgIn0(newTargetSym->GetLocation());
  1927. }
  1928. else if (funcInfo->IsGlobalFunction())
  1929. {
  1930. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1931. }
  1932. else
  1933. {
  1934. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1935. }
  1936. }
  1937. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1938. {
  1939. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1940. Assert(superConstructorSym);
  1941. Assert(!funcInfo->IsLambda());
  1942. if (funcInfo->IsDerivedClassConstructor())
  1943. {
  1944. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1945. }
  1946. else
  1947. {
  1948. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1949. }
  1950. }
  1951. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1952. {
  1953. Symbol* superSym = funcInfo->GetSuperSymbol();
  1954. Assert(superSym);
  1955. Assert(!funcInfo->IsLambda());
  1956. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1957. }
  1958. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue)
  1959. {
  1960. FuncInfo* nonLambdaFunc = funcInfo;
  1961. bool isResultUsed = pnodeSuperCall->isUsed;
  1962. if (funcInfo->IsLambda())
  1963. {
  1964. nonLambdaFunc = this->FindEnclosingNonLambda();
  1965. }
  1966. if (nonLambdaFunc->IsBaseClassConstructor())
  1967. {
  1968. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  1969. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  1970. return;
  1971. }
  1972. pnodeSuperCall->isUsed = true;
  1973. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  1974. // and the result of the super() expression itself
  1975. funcInfo->AcquireLoc(pnodeSuperCall);
  1976. // 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)
  1977. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  1978. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  1979. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  1980. Assert(pnodeSuperCall->isSuperCall);
  1981. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  1982. //
  1983. // if (super is class constructor) {
  1984. // _this = new.target;
  1985. // } else {
  1986. // _this = NewScObjFull(new.target);
  1987. // }
  1988. //
  1989. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  1990. // if (temp is object) {
  1991. // _this = temp;
  1992. // }
  1993. //
  1994. // if (UndeclBlockVar === this) {
  1995. // this = _this;
  1996. // } else {
  1997. // throw ReferenceError;
  1998. // }
  1999. //
  2000. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2001. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2002. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2003. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2004. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2005. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2006. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2007. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2008. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2009. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2010. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2011. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2012. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2013. this->Writer()->MarkLabel(makeCallLabel);
  2014. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2015. // We have to use another temp for the this value before assigning to this register.
  2016. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2017. // Ex:
  2018. // _this = new.target;
  2019. // temp = super.call(_this);
  2020. // if (temp is object) {
  2021. // _this = temp; // creates a new sym for _this as it was previously used
  2022. // }
  2023. // this = _this; // tries to loads a value from the old sym (which is dead)
  2024. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2025. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2026. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2027. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2028. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnodeSuperCall->location);
  2029. this->Writer()->MarkLabel(doneLabel);
  2030. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2031. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2032. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2033. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2034. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2035. this->Writer()->MarkLabel(skipLabel);
  2036. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2037. if (isResultUsed)
  2038. {
  2039. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2040. }
  2041. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2042. this->Writer()->Reg2(Js::OpCode::StrictLdThis, pnodeSuperCall->pnodeThis->location, valueForThis);
  2043. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2044. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2045. funcInfo->ReleaseTmpRegister(valueForThis);
  2046. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2047. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2048. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2049. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2050. }
  2051. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2052. {
  2053. Symbol* thisSym = funcInfo->GetThisSymbol();
  2054. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2055. {
  2056. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2057. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2058. }
  2059. }
  2060. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2061. {
  2062. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2063. {
  2064. m_writer.Reg2(Js::OpCode::StrictLdThis, lhsLocation, fromRegister);
  2065. }
  2066. else
  2067. {
  2068. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2069. }
  2070. }
  2071. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2072. {
  2073. if (pnodeFormal->IsVarLetOrConst())
  2074. {
  2075. // Get the param from its argument position into its assigned register.
  2076. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2077. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2078. if (formal->GetLocation() + 1 == pos)
  2079. {
  2080. // Transfer to the frame object, etc., if necessary.
  2081. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2082. }
  2083. }
  2084. }
  2085. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2086. {
  2087. if (ShouldTrackDebuggerMetadata())
  2088. {
  2089. // Add formals to the debugger propertyidcontainer for reg slots
  2090. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2091. {
  2092. if (pnodeFormal->IsVarLetOrConst())
  2093. {
  2094. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2095. if (!formal->IsInSlot(this, funcInfo))
  2096. {
  2097. Assert(!formal->GetHasInit());
  2098. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2099. }
  2100. }
  2101. };
  2102. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2103. }
  2104. // Transfer formal parameters to their home locations on the local frame.
  2105. if (funcInfo->GetHasArguments())
  2106. {
  2107. if (funcInfo->root->pnodeRest != nullptr)
  2108. {
  2109. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2110. EmitLoadFormalIntoRegister(funcInfo->root->pnodeRest, funcInfo->root->pnodeRest->sym->GetLocation() + 1, funcInfo);
  2111. }
  2112. // The arguments object creation helper does this work for us.
  2113. return;
  2114. }
  2115. Js::ArgSlot pos = 1;
  2116. auto loadFormal = [&](ParseNode *pnodeFormal)
  2117. {
  2118. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2119. pos++;
  2120. };
  2121. MapFormals(funcInfo->root, loadFormal);
  2122. }
  2123. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2124. {
  2125. funcInfo->singleExit = m_writer.DefineLabel();
  2126. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2127. while (iter.Next())
  2128. {
  2129. ParseNodeStmt * node = iter.Data();
  2130. node->breakLabel = m_writer.DefineLabel();
  2131. node->continueLabel = m_writer.DefineLabel();
  2132. node->emitLabels = true;
  2133. }
  2134. }
  2135. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2136. {
  2137. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2138. // return value.
  2139. ParseNode *pnode = funcInfo->root->pnodeBody;
  2140. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2141. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2142. {
  2143. // We're not guaranteed to compute any values, so fix up the return register at the top
  2144. // in case.
  2145. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2146. }
  2147. while (pnode->nop == knopList)
  2148. {
  2149. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2150. if (stmt == pnodeLastVal)
  2151. {
  2152. pnodeLastVal = nullptr;
  2153. }
  2154. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2155. {
  2156. EmitTopLevelStatement(stmt, funcInfo, true);
  2157. }
  2158. else
  2159. {
  2160. // Haven't hit the post-dominating return value yet,
  2161. // so don't bother with the return register.
  2162. EmitTopLevelStatement(stmt, funcInfo, false);
  2163. }
  2164. pnode = pnode->AsParseNodeBin()->pnode2;
  2165. }
  2166. EmitTopLevelStatement(pnode, funcInfo, false);
  2167. }
  2168. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2169. {
  2170. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2171. // get copied to the return register.
  2172. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2173. ParseNode *pnode = pnodeBody;
  2174. while (pnode->nop == knopList)
  2175. {
  2176. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2177. if (stmt->CapturesSyms())
  2178. {
  2179. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2180. SList<Symbol*> *list = map->Item(stmt);
  2181. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2182. {
  2183. if (!sym->GetIsCommittedToSlot())
  2184. {
  2185. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2186. sym->SetIsCommittedToSlot();
  2187. ParseNode *decl = sym->GetDecl();
  2188. Assert(decl);
  2189. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2190. {
  2191. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2192. sym->GetName().GetBuffer());
  2193. Output::Flush();
  2194. }
  2195. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2196. // what is this doing? Why are we assigning sym to itself?
  2197. bool old = sym->GetNeedDeclaration();
  2198. sym->SetNeedDeclaration(false);
  2199. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2200. sym->SetNeedDeclaration(old);
  2201. }
  2202. }
  2203. NEXT_SLIST_ENTRY;
  2204. }
  2205. EmitTopLevelStatement(stmt, funcInfo, false);
  2206. pnode = pnode->AsParseNodeBin()->pnode2;
  2207. }
  2208. Assert(!pnode->CapturesSyms());
  2209. EmitTopLevelStatement(pnode, funcInfo, false);
  2210. }
  2211. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2212. {
  2213. // Indicate that the binding phase is over.
  2214. this->isBinding = false;
  2215. this->trackEnvDepth = true;
  2216. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2217. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2218. // Use the temp allocator in bytecode write temp buffer.
  2219. m_writer.InitData(this->alloc, initSize);
  2220. #ifdef LOG_BYTECODE_AST_RATIO
  2221. // log the max Ast size
  2222. Output::Print(_u("Max Ast size: %d"), initSize);
  2223. #endif
  2224. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2225. if (this->parentScopeInfo)
  2226. {
  2227. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2228. // Start emitting with the nested scope (i.e., the deferred function).
  2229. this->EmitScopeList(pnodeProg->pnodeScopes);
  2230. }
  2231. else
  2232. {
  2233. this->EmitScopeList(pnodeProg);
  2234. }
  2235. }
  2236. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2237. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2238. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2239. {
  2240. Js::DebuggerScope *debuggerScope = nullptr;
  2241. auto processArg = [&](ParseNode *pnodeArg) {
  2242. if (pnodeArg->IsVarLetOrConst())
  2243. {
  2244. if (debuggerScope == nullptr)
  2245. {
  2246. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2247. debuggerScope->SetBegin(beginOffset);
  2248. }
  2249. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2250. }
  2251. };
  2252. MapFormals(pnodeFnc, processArg);
  2253. MapFormalsFromPattern(pnodeFnc, processArg);
  2254. if (debuggerScope != nullptr)
  2255. {
  2256. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2257. {
  2258. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2259. }
  2260. RecordEndScopeObject(pnodeFnc);
  2261. }
  2262. }
  2263. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2264. {
  2265. if (sym)
  2266. {
  2267. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2268. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2269. Js::RegSlot location = sym->GetLocation();
  2270. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2271. {
  2272. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2273. location = funcBody->MapRegSlot(location);
  2274. }
  2275. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2276. }
  2277. }
  2278. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2279. {
  2280. uint beginOffset = m_writer.GetCurrentOffset();
  2281. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2282. {
  2283. if (pnodeArg->nop == knopParamPattern)
  2284. {
  2285. this->StartStatement(pnodeArg);
  2286. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2287. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2288. if (pnode1->IsPattern())
  2289. {
  2290. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2291. }
  2292. else
  2293. {
  2294. Assert(pnode1->nop == knopAsg);
  2295. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2296. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2297. pnodeArg->AsParseNodeParamPattern()->location,
  2298. pnode1->AsParseNodeBin()->pnode2,
  2299. false /*isNonPatternAssignmentTarget*/,
  2300. this,
  2301. funcInfo);
  2302. }
  2303. this->EndStatement(pnodeArg);
  2304. return;
  2305. }
  2306. else if (pnodeArg->IsVarLetOrConst())
  2307. {
  2308. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2309. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2310. {
  2311. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2312. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2313. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2314. return;
  2315. }
  2316. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2317. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2318. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2319. this->StartStatement(pnodeArg);
  2320. // Let us use strict not equal to differentiate between null and undefined
  2321. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2322. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2323. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2324. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2325. {
  2326. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2327. m_writer.Br(endLabel);
  2328. }
  2329. else
  2330. {
  2331. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2332. }
  2333. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2334. m_writer.MarkLabel(noDefaultLabel);
  2335. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2336. {
  2337. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2338. m_writer.MarkLabel(endLabel);
  2339. }
  2340. this->EndStatement(pnodeArg);
  2341. }
  2342. };
  2343. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2344. if (pnodeFnc->IsAsync())
  2345. {
  2346. uint cacheId;
  2347. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2348. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2349. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2350. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2351. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2352. // try
  2353. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2354. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2355. // Rest cannot have a default argument, so we ignore it.
  2356. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2357. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2358. m_writer.Empty(Js::OpCode::Leave);
  2359. m_writer.Br(doneLabel);
  2360. // catch
  2361. m_writer.MarkLabel(catchLabel);
  2362. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2363. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2364. m_writer.Empty(Js::OpCode::Nop);
  2365. // return Promise.reject(error);
  2366. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2367. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2368. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2369. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2370. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2371. m_writer.Empty(Js::OpCode::Leave);
  2372. m_writer.Br(funcInfo->singleExit);
  2373. m_writer.Empty(Js::OpCode::Leave);
  2374. m_writer.MarkLabel(doneLabel);
  2375. this->SetHasTry(true);
  2376. funcInfo->ReleaseTmpRegister(rejectLocation);
  2377. funcInfo->ReleaseTmpRegister(promiseLocation);
  2378. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2379. }
  2380. else
  2381. {
  2382. // Rest cannot have a default argument, so we ignore it.
  2383. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2384. }
  2385. if (m_writer.GetCurrentOffset() > beginOffset)
  2386. {
  2387. PopulateFormalsScope(beginOffset, funcInfo, pnodeFnc);
  2388. }
  2389. }
  2390. void ByteCodeGenerator::EmitOneFunction(ParseNodeFnc *pnodeFnc)
  2391. {
  2392. Assert(pnodeFnc && (pnodeFnc->nop == knopProg || pnodeFnc->nop == knopFncDecl));
  2393. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2394. Assert(funcInfo != nullptr);
  2395. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2396. {
  2397. return;
  2398. }
  2399. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2400. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2401. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2402. funcInfo->root,
  2403. !!(this->flags & fscrEvalCode),
  2404. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2405. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2406. if (pnodeFnc->HasDefaultArguments())
  2407. {
  2408. deferParseFunction->SetReportedInParamsCount(pnodeFnc->firstDefaultArg + 1);
  2409. }
  2410. else
  2411. {
  2412. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2413. }
  2414. // Note: Don't check the actual attributes on the functionInfo here, since CanDefer has been cleared while
  2415. // we're generating byte code.
  2416. if (deferParseFunction->IsDeferred() || funcInfo->canDefer)
  2417. {
  2418. Js::ScopeInfo::SaveEnclosingScopeInfo(this, funcInfo);
  2419. }
  2420. if (funcInfo->root->pnodeBody == nullptr)
  2421. {
  2422. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase) && (this->GetFlags() & fscrCreateParserState) == fscrCreateParserState && deferParseFunction->GetCompileCount() == 0)
  2423. {
  2424. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2425. }
  2426. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2427. return;
  2428. }
  2429. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2430. try
  2431. {
  2432. if (!funcInfo->IsGlobalFunction())
  2433. {
  2434. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2435. // In that case the flag already has the value we want.
  2436. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2437. {
  2438. #if DBG
  2439. byteCodeFunction->SetCanDoStackNestedFunc();
  2440. #endif
  2441. if (funcInfo->root->astSize <= ParseNodeFnc::MaxStackClosureAST)
  2442. {
  2443. byteCodeFunction->SetStackNestedFunc(true);
  2444. }
  2445. }
  2446. }
  2447. if (byteCodeFunction->DoStackNestedFunc())
  2448. {
  2449. uint nestedCount = byteCodeFunction->GetNestedCount();
  2450. for (uint i = 0; i < nestedCount; i++)
  2451. {
  2452. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2453. if (nested->IsFunctionBody())
  2454. {
  2455. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2456. }
  2457. }
  2458. }
  2459. if (byteCodeFunction->GetByteCode() != nullptr)
  2460. {
  2461. // Previously compiled function nested within a re-deferred and re-compiled function.
  2462. return;
  2463. }
  2464. // Bug : 301517
  2465. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2466. // and do operation on 'this' and its property, which may not be defined yet.
  2467. if (funcInfo->root->HasOnlyThisStmts() && !IsInDebugMode())
  2468. {
  2469. byteCodeFunction->SetHasOnlyThisStmts(true);
  2470. }
  2471. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2472. {
  2473. if ((pnodeFnc->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnodeFnc, this))
  2474. {
  2475. bool applyEnclosesArgs = true;
  2476. for (ParseNode* pnodeVar = funcInfo->root->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2477. {
  2478. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2479. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2480. {
  2481. applyEnclosesArgs = false;
  2482. break;
  2483. }
  2484. }
  2485. auto constAndLetCheck = [](ParseNodeBlock *pnodeBlock, bool *applyEnclosesArgs)
  2486. {
  2487. if (*applyEnclosesArgs)
  2488. {
  2489. for (auto lexvar = pnodeBlock->pnodeLexVars; lexvar; lexvar = lexvar->AsParseNodeVar()->pnodeNext)
  2490. {
  2491. Symbol* sym = lexvar->AsParseNodeVar()->sym;
  2492. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2493. {
  2494. *applyEnclosesArgs = false;
  2495. break;
  2496. }
  2497. }
  2498. }
  2499. };
  2500. constAndLetCheck(funcInfo->root->pnodeScopes, &applyEnclosesArgs);
  2501. constAndLetCheck(funcInfo->root->pnodeBodyScope, &applyEnclosesArgs);
  2502. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2503. }
  2504. }
  2505. InitScopeSlotArray(funcInfo);
  2506. FinalizeRegisters(funcInfo, byteCodeFunction);
  2507. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2508. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2509. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2510. // Need to revisit the condition when enabling JitES6Generators.
  2511. uint innerScopeCount = funcInfo->InnerScopeCount();
  2512. if (!this->IsInDebugMode() && !byteCodeFunction->IsCoroutine())
  2513. {
  2514. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2515. if (innerScopeCount)
  2516. {
  2517. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2518. for (uint i = 1; i < innerScopeCount; i++)
  2519. {
  2520. funcInfo->AcquireTmpRegister();
  2521. }
  2522. }
  2523. }
  2524. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2525. alloc,
  2526. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2527. );
  2528. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2529. alloc,
  2530. 10);
  2531. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2532. alloc,
  2533. 10);
  2534. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2535. alloc,
  2536. 10);
  2537. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2538. alloc,
  2539. 10);
  2540. byteCodeFunction->AllocateLiteralRegexArray();
  2541. m_callSiteId = 0;
  2542. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2543. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2544. this->inPrologue = true;
  2545. Scope* paramScope = funcInfo->GetParamScope();
  2546. Scope* bodyScope = funcInfo->GetBodyScope();
  2547. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2548. LoadAllConstants(funcInfo);
  2549. HomeArguments(funcInfo);
  2550. if (!funcInfo->IsBodyAndParamScopeMerged())
  2551. {
  2552. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2553. // Pop the body scope before emitting the default args
  2554. PopScope();
  2555. Assert(this->GetCurrentScope() == paramScope);
  2556. }
  2557. if (funcInfo->root->pnodeRest != nullptr)
  2558. {
  2559. byteCodeFunction->SetHasRestParameter();
  2560. }
  2561. if (funcInfo->IsGlobalFunction())
  2562. {
  2563. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2564. }
  2565. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2566. DefineLabels(funcInfo);
  2567. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2568. // argument expressions reference those special names.
  2569. if (pnodeFnc->HasNonSimpleParameterList())
  2570. {
  2571. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2572. // need to walk over the var list.
  2573. if (funcInfo->IsBodyAndParamScopeMerged())
  2574. {
  2575. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2576. {
  2577. #if DBG
  2578. bool reachedEndOfSpecialSymbols = false;
  2579. #endif
  2580. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2581. if (sym != nullptr && sym->IsSpecialSymbol())
  2582. {
  2583. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2584. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2585. {
  2586. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2587. }
  2588. }
  2589. else
  2590. {
  2591. #if DBG
  2592. reachedEndOfSpecialSymbols = true;
  2593. #else
  2594. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2595. // so we can quit walking at the first non-special one we see.
  2596. break;
  2597. #endif
  2598. }
  2599. #if DBG
  2600. if (reachedEndOfSpecialSymbols)
  2601. {
  2602. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2603. }
  2604. #endif
  2605. }
  2606. }
  2607. else
  2608. {
  2609. paramScope->ForEachSymbol([&](Symbol* sym) {
  2610. if (sym && sym->IsSpecialSymbol())
  2611. {
  2612. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2613. }
  2614. });
  2615. }
  2616. }
  2617. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2618. {
  2619. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2620. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2621. EmitDefaultArgs(funcInfo, pnodeFnc);
  2622. if (!funcInfo->IsBodyAndParamScopeMerged())
  2623. {
  2624. Assert(this->GetCurrentScope() == paramScope);
  2625. // Push the body scope
  2626. PushScope(bodyScope);
  2627. funcInfo->SetCurrentChildScope(bodyScope);
  2628. // Mark the beginning of the body scope so that new scope slots can be created.
  2629. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2630. }
  2631. }
  2632. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2633. // (that is when the function is called). This yield opcode is to mark the begining of the function body.
  2634. // TODO: Inserting a yield should have almost no impact on perf as it is a direct return from the function. But this needs
  2635. // to be verified. Ideally if the function has simple parameter list then we can avoid inserting the opcode and the additional call.
  2636. if (pnodeFnc->IsGenerator())
  2637. {
  2638. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2639. EmitYield(funcInfo->AssignUndefinedConstRegister(), tempReg, this, funcInfo);
  2640. m_writer.Reg1(Js::OpCode::Unused, tempReg);
  2641. funcInfo->ReleaseTmpRegister(tempReg);
  2642. }
  2643. DefineUserVars(funcInfo);
  2644. // Emit all scope-wide function definitions before emitting function bodies
  2645. // so that calls may reference functions they precede lexically.
  2646. // Note, global eval scope is a fake local scope and is handled as if it were
  2647. // a lexical block instead of a true global scope, so do not define the functions
  2648. // here. They will be defined during BeginEmitBlock.
  2649. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2650. {
  2651. // This only handles function declarations, which param scope cannot have any.
  2652. DefineFunctions(funcInfo);
  2653. }
  2654. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2655. {
  2656. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2657. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2658. }
  2659. else
  2660. {
  2661. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2662. }
  2663. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2664. {
  2665. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2666. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2667. }
  2668. // Rest needs to trigger use before declaration until all default args have been processed.
  2669. if (pnodeFnc->pnodeRest != nullptr)
  2670. {
  2671. pnodeFnc->pnodeRest->sym->SetNeedDeclaration(false);
  2672. }
  2673. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2674. if (!funcInfo->IsBodyAndParamScopeMerged())
  2675. {
  2676. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2677. // We have to do this after the rest param is marked as false for need declaration.
  2678. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2679. paramScope->ForEachSymbol([&](Symbol* param) {
  2680. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2681. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2682. // is expected to stay inside the function expression scope
  2683. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2684. {
  2685. if (!varSym->GetNeedDeclaration())
  2686. {
  2687. if (param->IsInSlot(this, funcInfo))
  2688. {
  2689. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2690. // Walking the scope chain is not possible at this time.
  2691. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2692. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2693. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2694. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2695. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2696. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2697. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2698. funcInfo->ReleaseTmpRegister(tempReg);
  2699. }
  2700. else if (param->GetLocation() != Js::Constants::NoRegister)
  2701. {
  2702. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2703. }
  2704. else
  2705. {
  2706. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2707. }
  2708. }
  2709. else
  2710. {
  2711. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2712. // re-declaration error.
  2713. Assert(param->IsArguments());
  2714. }
  2715. }
  2716. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2717. {
  2718. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2719. {
  2720. formalsUpperBound = param->GetLocation();
  2721. }
  2722. }
  2723. });
  2724. }
  2725. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2726. {
  2727. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2728. }
  2729. if (pnodeFnc->pnodeBodyScope != nullptr)
  2730. {
  2731. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2732. }
  2733. this->inPrologue = false;
  2734. if (funcInfo->IsGlobalFunction())
  2735. {
  2736. EmitGlobalBody(funcInfo);
  2737. }
  2738. else
  2739. {
  2740. EmitFunctionBody(funcInfo);
  2741. }
  2742. if (pnodeFnc->pnodeBodyScope != nullptr)
  2743. {
  2744. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2745. }
  2746. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2747. if (!this->IsInDebugMode())
  2748. {
  2749. // Release the temp registers that we reserved for inner scopes above.
  2750. if (innerScopeCount)
  2751. {
  2752. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2753. for (uint i = 0; i < innerScopeCount; i++)
  2754. {
  2755. funcInfo->ReleaseTmpRegister(tmpReg);
  2756. tmpReg--;
  2757. }
  2758. }
  2759. }
  2760. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2761. Assert(funcInfo->curTmpReg == firstTmpReg);
  2762. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2763. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2764. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2765. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2766. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2767. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2768. #if DBG_DUMP
  2769. if (PHASE_STATS1(Js::ByteCodePhase))
  2770. {
  2771. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2772. m_writer.ByteCodeDataSize(),
  2773. m_writer.AuxiliaryDataSize(),
  2774. m_writer.AuxiliaryContextDataSize(),
  2775. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2776. funcInfo->name);
  2777. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2778. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2779. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2780. }
  2781. #endif
  2782. this->MapCacheIdsToPropertyIds(funcInfo);
  2783. this->MapReferencedPropertyIds(funcInfo);
  2784. Assert(this->TopFuncInfo() == funcInfo);
  2785. PopFuncInfo(_u("EmitOneFunction"));
  2786. m_writer.SetCallSiteCount(m_callSiteId);
  2787. #ifdef LOG_BYTECODE_AST_RATIO
  2788. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2789. #else
  2790. m_writer.End();
  2791. #endif
  2792. }
  2793. catch (...)
  2794. {
  2795. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2796. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2797. byteCodeFunction->ResetByteCodeGenState();
  2798. m_writer.Reset();
  2799. throw;
  2800. }
  2801. #ifdef PERF_HINT
  2802. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2803. {
  2804. if (byteCodeFunction->GetHasTry())
  2805. {
  2806. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2807. }
  2808. if (funcInfo->GetCallsEval())
  2809. {
  2810. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2811. }
  2812. else if (funcInfo->GetChildCallsEval())
  2813. {
  2814. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2815. }
  2816. }
  2817. #endif
  2818. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2819. {
  2820. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2821. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2822. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2823. {
  2824. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2825. {
  2826. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2827. }
  2828. return true;
  2829. });
  2830. }
  2831. byteCodeFunction->SetInitialDefaultEntryPoint();
  2832. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2833. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2834. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2835. {
  2836. if (m_utf8SourceInfo->GetIsLibraryCode())
  2837. {
  2838. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2839. }
  2840. else
  2841. {
  2842. Js::Throw::FatalInternalError();
  2843. }
  2844. }
  2845. #endif
  2846. #if DBG_DUMP
  2847. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2848. {
  2849. pnodeFnc->Dump();
  2850. }
  2851. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2852. {
  2853. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2854. }
  2855. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2856. {
  2857. byteCodeFunction->DumpScopes();
  2858. }
  2859. #endif
  2860. #if ENABLE_NATIVE_CODEGEN
  2861. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2862. && !this->forceNoNative
  2863. && !this->scriptContext->GetConfig()->IsNoNative())
  2864. {
  2865. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2866. }
  2867. #endif
  2868. }
  2869. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2870. {
  2871. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2872. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2873. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2874. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2875. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2876. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2877. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2878. if (totalFieldAccessInlineCacheCount == 0)
  2879. {
  2880. return;
  2881. }
  2882. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2883. {
  2884. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2885. {
  2886. if (inlineCacheList)
  2887. {
  2888. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2889. {
  2890. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2891. if (cacheUnit.loadCacheId != -1)
  2892. {
  2893. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2894. }
  2895. if (cacheUnit.loadMethodCacheId != -1)
  2896. {
  2897. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2898. }
  2899. if (cacheUnit.storeCacheId != -1)
  2900. {
  2901. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2902. }
  2903. });
  2904. }
  2905. });
  2906. });
  2907. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2908. {
  2909. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2910. });
  2911. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2912. {
  2913. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2914. });
  2915. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2916. {
  2917. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2918. });
  2919. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2920. while (valueOfIter.Next())
  2921. {
  2922. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2923. }
  2924. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2925. while (toStringIter.Next())
  2926. {
  2927. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2928. }
  2929. #if DBG
  2930. functionBody->VerifyCacheIdToPropertyIdMap();
  2931. #endif
  2932. }
  2933. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2934. {
  2935. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2936. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2937. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2938. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2939. {
  2940. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2941. });
  2942. #if DBG
  2943. functionBody->VerifyReferencedPropertyIdMap();
  2944. #endif
  2945. }
  2946. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2947. {
  2948. while (pnode)
  2949. {
  2950. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2951. {
  2952. break;
  2953. }
  2954. switch (pnode->nop)
  2955. {
  2956. case knopFncDecl:
  2957. #ifdef ASMJS_PLAT
  2958. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2959. {
  2960. Js::ExclusiveContext context(this, GetScriptContext());
  2961. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2962. {
  2963. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2964. break;
  2965. }
  2966. else if (CONFIG_FLAG(AsmJsStopOnError))
  2967. {
  2968. exit(JSERR_AsmJsCompileError);
  2969. }
  2970. else
  2971. {
  2972. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2973. throw Js::AsmJsParseException();
  2974. }
  2975. }
  2976. #endif
  2977. // FALLTHROUGH
  2978. case knopProg:
  2979. if (pnode->AsParseNodeFnc()->funcInfo)
  2980. {
  2981. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  2982. Scope* paramScope = funcInfo->GetParamScope();
  2983. if (!funcInfo->IsBodyAndParamScopeMerged())
  2984. {
  2985. funcInfo->SetCurrentChildScope(paramScope);
  2986. }
  2987. else
  2988. {
  2989. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  2990. }
  2991. this->StartEmitFunction(pnode->AsParseNodeFnc());
  2992. if (!funcInfo->IsBodyAndParamScopeMerged())
  2993. {
  2994. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  2995. }
  2996. else
  2997. {
  2998. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  2999. }
  3000. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3001. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3002. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3003. funcInfo->SetCurrentChildScope(nullptr);
  3004. }
  3005. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3006. break;
  3007. case knopBlock:
  3008. {
  3009. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3010. this->StartEmitBlock(pnodeBlock);
  3011. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3012. this->EndEmitBlock(pnodeBlock);
  3013. pnode = pnodeBlock->pnodeNext;
  3014. break;
  3015. }
  3016. case knopCatch:
  3017. {
  3018. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3019. this->StartEmitCatch(pnodeCatch);
  3020. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3021. this->EndEmitCatch(pnodeCatch);
  3022. pnode = pnodeCatch->pnodeNext;
  3023. break;
  3024. }
  3025. case knopWith:
  3026. this->StartEmitWith(pnode);
  3027. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3028. this->EndEmitWith(pnode);
  3029. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3030. break;
  3031. default:
  3032. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3038. {
  3039. if (pnodeFnc->pnodeName)
  3040. {
  3041. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3042. Symbol *sym = pnodeFnc->pnodeName->sym;
  3043. // If this function is shadowing the arguments symbol in body then skip it.
  3044. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3045. if (sym && !sym->IsArguments())
  3046. {
  3047. sym->EnsureScopeSlot(this, funcInfo);
  3048. }
  3049. }
  3050. }
  3051. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3052. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3053. {
  3054. if (pnodeFnc->pnodeName)
  3055. {
  3056. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3057. Symbol *sym = pnodeFnc->pnodeName->sym;
  3058. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3059. {
  3060. sym->EnsureScopeSlot(this, funcInfo);
  3061. }
  3062. }
  3063. }
  3064. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3065. {
  3066. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3067. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3068. Scope * const bodyScope = funcInfo->GetBodyScope();
  3069. Scope * const paramScope = funcInfo->GetParamScope();
  3070. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3071. {
  3072. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3073. {
  3074. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3075. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3076. }
  3077. if (funcInfo->GetCallsEval())
  3078. {
  3079. funcInfo->byteCodeFunction->SetDontInline(true);
  3080. }
  3081. Scope * const funcExprScope = funcInfo->funcExprScope;
  3082. if (funcExprScope)
  3083. {
  3084. if (funcInfo->GetCallsEval())
  3085. {
  3086. Assert(funcExprScope->GetIsObject());
  3087. }
  3088. if (funcExprScope->GetIsObject())
  3089. {
  3090. funcExprScope->SetCapturesAll(true);
  3091. funcExprScope->SetMustInstantiate(true);
  3092. PushScope(funcExprScope);
  3093. }
  3094. else
  3095. {
  3096. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3097. if (funcInfo->IsBodyAndParamScopeMerged())
  3098. {
  3099. funcInfo->bodyScope->AddSymbol(sym);
  3100. }
  3101. else
  3102. {
  3103. funcInfo->paramScope->AddSymbol(sym);
  3104. }
  3105. sym->EnsureScopeSlot(this, funcInfo);
  3106. if (sym->GetHasNonLocalReference())
  3107. {
  3108. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3109. }
  3110. }
  3111. }
  3112. if (pnodeFnc->nop != knopProg)
  3113. {
  3114. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3115. {
  3116. Assert(bodyScope->GetIsObject());
  3117. }
  3118. if (bodyScope->GetIsObject())
  3119. {
  3120. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3121. }
  3122. else
  3123. {
  3124. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3125. }
  3126. if (!funcInfo->IsBodyAndParamScopeMerged())
  3127. {
  3128. if (paramScope->GetIsObject())
  3129. {
  3130. paramScope->SetLocation(funcInfo->frameObjRegister);
  3131. }
  3132. else
  3133. {
  3134. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3135. }
  3136. }
  3137. if (bodyScope->GetIsObject())
  3138. {
  3139. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3140. funcInfo->SetHasCachedScope(
  3141. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3142. !funcInfo->Escapes() &&
  3143. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3144. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3145. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3146. !pnodeFnc->HasDefaultArguments() &&
  3147. !pnodeFnc->HasDestructuredParams() &&
  3148. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3149. #if ENABLE_TTD
  3150. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3151. #endif
  3152. && !funcInfo->byteCodeFunction->IsCoroutine()
  3153. );
  3154. if (funcInfo->GetHasCachedScope())
  3155. {
  3156. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3157. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3158. if (funcSym && funcSym->GetIsFuncExpr())
  3159. {
  3160. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3161. {
  3162. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3163. }
  3164. else
  3165. {
  3166. funcInfo->funcObjRegister = funcSym->GetLocation();
  3167. }
  3168. }
  3169. else
  3170. {
  3171. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3172. }
  3173. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3174. }
  3175. ParseNode *pnode;
  3176. Symbol *sym;
  3177. if (funcInfo->GetHasArguments())
  3178. {
  3179. // Process function's formal parameters
  3180. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3181. {
  3182. if (pnode->IsVarLetOrConst())
  3183. {
  3184. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3185. }
  3186. });
  3187. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3188. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3189. // doesn't require scope slot for "arguments" because inner functions can't access
  3190. // outer function's arguments directly.
  3191. sym = funcInfo->GetArgumentsSymbol();
  3192. Assert(sym);
  3193. if (sym->NeedsSlotAlloc(this, funcInfo))
  3194. {
  3195. sym->EnsureScopeSlot(this, funcInfo);
  3196. }
  3197. }
  3198. sym = funcInfo->root->GetFuncSymbol();
  3199. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3200. {
  3201. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3202. {
  3203. sym->SetScopeSlot(0);
  3204. }
  3205. else if (funcInfo->GetFuncExprNameReference())
  3206. {
  3207. sym->EnsureScopeSlot(this, funcInfo);
  3208. }
  3209. }
  3210. if (!funcInfo->GetHasArguments())
  3211. {
  3212. Symbol *formal;
  3213. Js::ArgSlot pos = 1;
  3214. auto moveArgToReg = [&](ParseNode *pnode)
  3215. {
  3216. if (pnode->IsVarLetOrConst())
  3217. {
  3218. formal = pnode->AsParseNodeVar()->sym;
  3219. // Get the param from its argument position into its assigned register.
  3220. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3221. if (formal->GetLocation() + 1 == pos)
  3222. {
  3223. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3224. }
  3225. }
  3226. pos++;
  3227. };
  3228. MapFormals(pnodeFnc, moveArgToReg);
  3229. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3230. }
  3231. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3232. {
  3233. sym = pnode->AsParseNodeVar()->sym;
  3234. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3235. {
  3236. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3237. {
  3238. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3239. }
  3240. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3241. {
  3242. sym->EnsureScopeSlot(this, funcInfo);
  3243. }
  3244. }
  3245. }
  3246. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3247. {
  3248. for (pnode = pnodeScope; pnode;)
  3249. {
  3250. switch (pnode->nop)
  3251. {
  3252. case knopFncDecl:
  3253. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3254. {
  3255. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3256. }
  3257. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3258. break;
  3259. case knopBlock:
  3260. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3261. break;
  3262. case knopCatch:
  3263. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3264. break;
  3265. case knopWith:
  3266. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3267. break;
  3268. }
  3269. }
  3270. };
  3271. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3272. if (pnodeFnc->pnodeBody)
  3273. {
  3274. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3275. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3276. }
  3277. }
  3278. else
  3279. {
  3280. ParseNode *pnode;
  3281. Symbol *sym;
  3282. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3283. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3284. {
  3285. sym = pnode->AsParseNodeVar()->sym;
  3286. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3287. {
  3288. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3289. {
  3290. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3291. }
  3292. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3293. {
  3294. sym->EnsureScopeSlot(this, funcInfo);
  3295. }
  3296. }
  3297. }
  3298. auto ensureScopeSlot = [&](ParseNode *pnode)
  3299. {
  3300. if (pnode->IsVarLetOrConst())
  3301. {
  3302. sym = pnode->AsParseNodeVar()->sym;
  3303. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3304. {
  3305. sym->EnsureScopeSlot(this, funcInfo);
  3306. }
  3307. }
  3308. };
  3309. // Process function's formal parameters
  3310. MapFormals(pnodeFnc, ensureScopeSlot);
  3311. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3312. if (funcInfo->GetHasArguments())
  3313. {
  3314. sym = funcInfo->GetArgumentsSymbol();
  3315. Assert(sym);
  3316. // There is no eval so the arguments may be captured in a lambda.
  3317. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3318. sym->EnsureScopeSlot(this, funcInfo);
  3319. }
  3320. if (pnodeFnc->pnodeBody)
  3321. {
  3322. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3323. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3324. }
  3325. }
  3326. // 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.
  3327. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3328. {
  3329. bodyScope->SetMustInstantiate(true);
  3330. }
  3331. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3332. {
  3333. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3334. if (pnodeFnc->IsBodyAndParamScopeMerged() && paramScope && paramScope->GetHasNestedParamFunc())
  3335. {
  3336. paramScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3337. }
  3338. }
  3339. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3340. {
  3341. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3342. {
  3343. paramScope->SetMustInstantiate(true);
  3344. }
  3345. else
  3346. {
  3347. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3348. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3349. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3350. }
  3351. }
  3352. }
  3353. else
  3354. {
  3355. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3356. if (newScopeForEval)
  3357. {
  3358. Assert(bodyScope->GetIsObject());
  3359. }
  3360. }
  3361. }
  3362. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3363. if (!funcInfo->IsBodyAndParamScopeMerged())
  3364. {
  3365. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3366. Assert(paramBlock->blockType == Parameter);
  3367. PushScope(paramScope);
  3368. // While emitting the functions we have to stop when we see the body scope block.
  3369. // Otherwise functions defined in the body scope will not be able to get the right references.
  3370. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3371. Assert(this->GetCurrentScope() == paramScope);
  3372. }
  3373. PushScope(bodyScope);
  3374. }
  3375. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3376. {
  3377. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3378. {
  3379. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3380. }
  3381. else
  3382. {
  3383. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3384. if (opcode == Js::OpCode::LdModuleSlot)
  3385. {
  3386. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3387. }
  3388. }
  3389. }
  3390. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3391. {
  3392. Assert(sym->GetIsModuleExportStorage());
  3393. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3394. {
  3395. return true;
  3396. }
  3397. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3398. library->EnsureModuleRecordList();
  3399. uint moduleIndex = this->GetModuleID();
  3400. uint moduleSlotIndex;
  3401. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3402. if (sym->GetIsModuleImport())
  3403. {
  3404. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3405. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3406. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3407. {
  3408. return false;
  3409. }
  3410. AnalysisAssert(moduleNameRecord != nullptr);
  3411. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3412. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3413. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3414. moduleIndex = resolvedModuleRecord->GetModuleId();
  3415. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3416. }
  3417. else
  3418. {
  3419. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3420. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3421. }
  3422. sym->SetModuleIndex(moduleIndex);
  3423. sym->SetScopeSlot(moduleSlotIndex);
  3424. return true;
  3425. }
  3426. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3427. {
  3428. // We are assigning pnode to the default export of the current module.
  3429. uint moduleIndex = this->GetModuleID();
  3430. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3431. library->EnsureModuleRecordList();
  3432. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3433. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3434. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3435. }
  3436. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3437. {
  3438. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3439. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3440. {
  3441. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3442. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3443. {
  3444. sym->EnsureScopeSlot(this, funcInfo);
  3445. this->ProcessCapturedSym(sym);
  3446. }
  3447. });
  3448. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3449. }
  3450. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3451. {
  3452. while (pnode)
  3453. {
  3454. switch (pnode->nop)
  3455. {
  3456. case knopFncDecl:
  3457. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3458. {
  3459. this->CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3460. }
  3461. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3462. break;
  3463. case knopBlock:
  3464. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3465. break;
  3466. case knopCatch:
  3467. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3468. break;
  3469. case knopWith:
  3470. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3471. break;
  3472. }
  3473. }
  3474. }
  3475. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3476. {
  3477. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3478. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3479. PopScope(); // function body
  3480. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3481. Scope* paramScope = funcInfo->paramScope;
  3482. if (!funcInfo->IsBodyAndParamScopeMerged())
  3483. {
  3484. Assert(this->GetCurrentScope() == paramScope);
  3485. PopScope(); // Pop the param scope
  3486. }
  3487. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3488. {
  3489. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3490. // TODO: Refactor Start and EndEmitFunction for clarity.
  3491. Scope *scope = funcInfo->funcExprScope;
  3492. if (scope && scope->GetMustInstantiate())
  3493. {
  3494. Assert(currentScope == scope);
  3495. PopScope();
  3496. }
  3497. }
  3498. Assert(funcInfo == this->TopFuncInfo());
  3499. PopFuncInfo(_u("EndEmitFunction"));
  3500. }
  3501. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3502. {
  3503. Assert(pnodeCatch->nop == knopCatch);
  3504. Scope *scope = pnodeCatch->scope;
  3505. FuncInfo *funcInfo = scope->GetFunc();
  3506. // 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).
  3507. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3508. {
  3509. scope->SetIsObject();
  3510. }
  3511. ParseNode * pnodeParam = pnodeCatch->GetParam();
  3512. if (pnodeParam->nop == knopParamPattern)
  3513. {
  3514. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3515. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3516. Parser::MapBindIdentifier(pnodeParam->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  3517. {
  3518. Symbol *sym = item->AsParseNodeVar()->sym;
  3519. if (funcInfo->IsGlobalFunction())
  3520. {
  3521. sym->SetIsGlobalCatch(true);
  3522. }
  3523. if (sym->NeedsScopeObject())
  3524. {
  3525. scope->SetIsObject();
  3526. }
  3527. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3528. if (sym->NeedsSlotAlloc(this, funcInfo))
  3529. {
  3530. sym->EnsureScopeSlot(this, funcInfo);
  3531. }
  3532. });
  3533. // In the case of pattern we will always going to push the scope.
  3534. PushScope(scope);
  3535. }
  3536. else
  3537. {
  3538. Symbol *sym = pnodeParam->AsParseNodeName()->sym;
  3539. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3540. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3541. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3542. if (funcInfo->IsGlobalFunction())
  3543. {
  3544. sym->SetIsGlobalCatch(true);
  3545. }
  3546. if (sym->NeedsScopeObject())
  3547. {
  3548. scope->SetIsObject();
  3549. }
  3550. if (scope->GetMustInstantiate())
  3551. {
  3552. if (sym->IsInSlot(this, funcInfo))
  3553. {
  3554. // Since there is only one symbol we are pushing to slot.
  3555. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3556. this->ProcessCapturedSym(sym);
  3557. sym->EnsureScopeSlot(this, funcInfo);
  3558. }
  3559. }
  3560. PushScope(scope);
  3561. }
  3562. }
  3563. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3564. {
  3565. Assert(pnodeCatch->nop == knopCatch);
  3566. Assert(currentScope == pnodeCatch->scope);
  3567. PopScope();
  3568. }
  3569. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3570. {
  3571. if (!BlockHasOwnScope(pnodeBlock, this))
  3572. {
  3573. return;
  3574. }
  3575. Assert(pnodeBlock->nop == knopBlock);
  3576. PushBlock(pnodeBlock);
  3577. Scope *scope = pnodeBlock->scope;
  3578. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3579. {
  3580. Assert(scope->GetIsObject());
  3581. }
  3582. // TODO: Consider nested deferred parsing.
  3583. if (scope->GetMustInstantiate())
  3584. {
  3585. FuncInfo *funcInfo = scope->GetFunc();
  3586. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3587. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3588. PushScope(scope);
  3589. }
  3590. }
  3591. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3592. {
  3593. if (!BlockHasOwnScope(pnodeBlock, this))
  3594. {
  3595. return;
  3596. }
  3597. Assert(pnodeBlock->nop == knopBlock);
  3598. Scope *scope = pnodeBlock->scope;
  3599. if (scope && scope->GetMustInstantiate())
  3600. {
  3601. Assert(currentScope == pnodeBlock->scope);
  3602. PopScope();
  3603. }
  3604. PopBlock();
  3605. }
  3606. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3607. {
  3608. Assert(pnodeWith->nop == knopWith);
  3609. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3610. AssertOrFailFast(scope->GetIsObject());
  3611. PushScope(scope);
  3612. }
  3613. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3614. {
  3615. Assert(pnodeWith->nop == knopWith);
  3616. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3617. PopScope();
  3618. }
  3619. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3620. {
  3621. Scope *currScope = this->currentScope;
  3622. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3623. if (currScope == funcScope)
  3624. {
  3625. return evalEnv;
  3626. }
  3627. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3628. if (acquireTempLoc)
  3629. {
  3630. tempLoc = funcInfo->AcquireTmpRegister();
  3631. }
  3632. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3633. // but the list must first be reversed so that innermost scopes appear first in the list.
  3634. while (currScope != funcScope)
  3635. {
  3636. Scope *innerScope;
  3637. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3638. ;
  3639. if (innerScope->GetMustInstantiate())
  3640. {
  3641. if (!innerScope->HasInnerScopeIndex())
  3642. {
  3643. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3644. {
  3645. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3646. }
  3647. else
  3648. {
  3649. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3650. }
  3651. }
  3652. else
  3653. {
  3654. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3655. {
  3656. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3657. }
  3658. else
  3659. {
  3660. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3661. }
  3662. }
  3663. evalEnv = tempLoc;
  3664. }
  3665. funcScope = innerScope;
  3666. }
  3667. if (acquireTempLoc)
  3668. {
  3669. funcInfo->ReleaseTmpRegister(tempLoc);
  3670. }
  3671. return evalEnv;
  3672. }
  3673. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3674. {
  3675. Js::ByteCodeLabel doneLabel = 0;
  3676. bool fLabelDefined = false;
  3677. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3678. Js::RegSlot thisLocation = *pThisLocation;
  3679. Js::RegSlot instLocation = *pInstLocation;
  3680. Js::PropertyId envIndex = -1;
  3681. Scope *scope = nullptr;
  3682. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3683. Assert(symScope);
  3684. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3685. {
  3686. *pInstLocation = Js::Constants::NoRegister;
  3687. return;
  3688. }
  3689. for (;;)
  3690. {
  3691. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3692. if (scope == this->globalScope)
  3693. {
  3694. break;
  3695. }
  3696. if (scope != symScope)
  3697. {
  3698. // We're not sure where the function is (eval/with/etc).
  3699. // So we're going to need registers to hold the instance where we (dynamically) find
  3700. // the function, and possibly to hold the "this" pointer we will pass to it.
  3701. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3702. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3703. if (instLocation == Js::Constants::NoRegister)
  3704. {
  3705. instLocation = funcInfo->AcquireTmpRegister();
  3706. // The "this" pointer will not be the same as the instance, so give it its own register.
  3707. thisLocation = funcInfo->AcquireTmpRegister();
  3708. }
  3709. }
  3710. if (envIndex == -1)
  3711. {
  3712. Assert(funcInfo == scope->GetFunc());
  3713. scopeLocation = scope->GetLocation();
  3714. }
  3715. if (scope == symScope)
  3716. {
  3717. break;
  3718. }
  3719. // Found a scope to which the property may have been added.
  3720. Assert(scope && scope->GetIsDynamic());
  3721. if (!fLabelDefined)
  3722. {
  3723. fLabelDefined = true;
  3724. doneLabel = this->m_writer.DefineLabel();
  3725. }
  3726. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3727. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3728. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3729. if (envIndex != -1)
  3730. {
  3731. this->m_writer.BrEnvProperty(
  3732. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3733. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3734. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3735. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3736. AssertOrFailFast(scope->GetIsObject());
  3737. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3738. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3739. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3740. this->m_writer.Reg2(op, instLocation, tmpReg);
  3741. if (thisLocation != Js::Constants::NoRegister)
  3742. {
  3743. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3744. }
  3745. funcInfo->ReleaseTmpRegister(tmpReg);
  3746. }
  3747. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3748. {
  3749. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3750. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3751. Assert(!unwrapWithObj);
  3752. AssertOrFailFast(scope->GetIsObject());
  3753. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3754. if (thisLocation != Js::Constants::NoRegister)
  3755. {
  3756. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3757. }
  3758. }
  3759. else
  3760. {
  3761. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3762. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3763. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3764. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3765. if (thisLocation != Js::Constants::NoRegister)
  3766. {
  3767. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3768. }
  3769. }
  3770. this->m_writer.Br(doneLabel);
  3771. this->m_writer.MarkLabel(nextLabel);
  3772. }
  3773. if (sym == nullptr || sym->GetIsGlobal())
  3774. {
  3775. if (this->flags & (fscrEval | fscrImplicitThis))
  3776. {
  3777. // Load of a symbol with unknown scope from within eval.
  3778. // Get it from the closure environment.
  3779. if (instLocation == Js::Constants::NoRegister)
  3780. {
  3781. instLocation = funcInfo->AcquireTmpRegister();
  3782. }
  3783. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3784. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3785. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3786. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3787. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3788. if (thisLocation == Js::Constants::NoRegister)
  3789. {
  3790. thisLocation = funcInfo->AcquireTmpRegister();
  3791. }
  3792. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3793. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3794. }
  3795. else
  3796. {
  3797. if (instLocation == Js::Constants::NoRegister)
  3798. {
  3799. instLocation = ByteCodeGenerator::RootObjectRegister;
  3800. }
  3801. else
  3802. {
  3803. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3804. }
  3805. if (thisLocation == Js::Constants::NoRegister)
  3806. {
  3807. thisLocation = funcInfo->undefinedConstantRegister;
  3808. }
  3809. else
  3810. {
  3811. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3812. }
  3813. }
  3814. }
  3815. else if (instLocation != Js::Constants::NoRegister)
  3816. {
  3817. if (envIndex != -1)
  3818. {
  3819. AssertOrFailFast(scope->GetIsObject());
  3820. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3821. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3822. }
  3823. else if (scope->HasInnerScopeIndex())
  3824. {
  3825. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3826. }
  3827. else if (symScope == funcInfo->GetParamScope())
  3828. {
  3829. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3830. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3831. }
  3832. else if (symScope != funcInfo->GetBodyScope())
  3833. {
  3834. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3835. }
  3836. else
  3837. {
  3838. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3839. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3840. }
  3841. if (thisLocation != Js::Constants::NoRegister)
  3842. {
  3843. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3844. }
  3845. else
  3846. {
  3847. thisLocation = funcInfo->undefinedConstantRegister;
  3848. }
  3849. }
  3850. *pThisLocation = thisLocation;
  3851. *pInstLocation = instLocation;
  3852. if (fLabelDefined)
  3853. {
  3854. this->m_writer.MarkLabel(doneLabel);
  3855. }
  3856. }
  3857. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3858. {
  3859. // Note: declared variables and assignments in the global function go to the root object directly.
  3860. if (this->flags & fscrEval)
  3861. {
  3862. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3863. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3864. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3865. // into one operation). See WOOB 1121763 and 1120973.
  3866. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3867. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3868. }
  3869. else
  3870. {
  3871. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3872. }
  3873. }
  3874. void
  3875. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3876. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3877. {
  3878. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3879. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3880. }
  3881. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3882. {
  3883. Scope *scope = sym->GetScope();
  3884. // Check consistency of sym->IsInSlot.
  3885. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3886. // Arrived at the scope in which the property was defined.
  3887. if (sym->NeedsSlotAlloc(this, funcInfo))
  3888. {
  3889. // The property is in memory rather than register. We'll have to load it from the slots.
  3890. if (scope->GetIsObject())
  3891. {
  3892. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3893. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3894. Js::RegSlot objReg;
  3895. if (scope->HasInnerScopeIndex())
  3896. {
  3897. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3898. }
  3899. else
  3900. {
  3901. objReg = scope->GetLocation();
  3902. }
  3903. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3904. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3905. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3906. {
  3907. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3908. }
  3909. else if (scope->HasInnerScopeIndex())
  3910. {
  3911. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3912. }
  3913. else
  3914. {
  3915. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3916. }
  3917. }
  3918. else
  3919. {
  3920. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3921. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3922. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3923. // Now store the property to its slot.
  3924. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3925. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3926. {
  3927. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3928. }
  3929. else
  3930. {
  3931. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3932. }
  3933. }
  3934. }
  3935. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3936. {
  3937. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3938. }
  3939. }
  3940. Js::OpCode
  3941. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  3942. {
  3943. Js::OpCode op;
  3944. if (envIndex != -1)
  3945. {
  3946. if (scope->GetIsObject())
  3947. {
  3948. op = Js::OpCode::StEnvObjSlot;
  3949. }
  3950. else
  3951. {
  3952. op = Js::OpCode::StEnvSlot;
  3953. }
  3954. }
  3955. else if (scopeLocation != Js::Constants::NoRegister &&
  3956. scopeLocation == funcInfo->frameSlotsRegister)
  3957. {
  3958. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3959. {
  3960. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3961. // We should use the param scope's bytecode now.
  3962. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3963. op = Js::OpCode::StParamSlot;
  3964. }
  3965. else
  3966. {
  3967. op = Js::OpCode::StLocalSlot;
  3968. }
  3969. }
  3970. else if (scopeLocation != Js::Constants::NoRegister &&
  3971. scopeLocation == funcInfo->frameObjRegister)
  3972. {
  3973. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3974. {
  3975. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3976. // We should use the param scope's bytecode now.
  3977. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3978. op = Js::OpCode::StParamObjSlot;
  3979. }
  3980. else
  3981. {
  3982. op = Js::OpCode::StLocalObjSlot;
  3983. }
  3984. }
  3985. else
  3986. {
  3987. Assert(scope->HasInnerScopeIndex());
  3988. if (scope->GetIsObject())
  3989. {
  3990. op = Js::OpCode::StInnerObjSlot;
  3991. }
  3992. else
  3993. {
  3994. op = Js::OpCode::StInnerSlot;
  3995. }
  3996. }
  3997. if (chkBlockVar)
  3998. {
  3999. op = this->ToChkUndeclOp(op);
  4000. }
  4001. return op;
  4002. }
  4003. Js::OpCode
  4004. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4005. {
  4006. Js::OpCode op;
  4007. if (scopeLocation != Js::Constants::NoRegister &&
  4008. scopeLocation == funcInfo->frameObjRegister)
  4009. {
  4010. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4011. }
  4012. else if (scope->HasInnerScopeIndex())
  4013. {
  4014. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4015. }
  4016. else
  4017. {
  4018. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4019. }
  4020. return op;
  4021. }
  4022. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4023. {
  4024. Js::ByteCodeLabel doneLabel = 0;
  4025. bool fLabelDefined = false;
  4026. Js::PropertyId envIndex = -1;
  4027. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4028. Assert(symScope);
  4029. // isFncDeclVar denotes that the symbol being stored to here is the var
  4030. // binding of a function declaration and we know we want to store directly
  4031. // to it, skipping over any dynamic scopes that may lie in between.
  4032. Scope *scope = nullptr;
  4033. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4034. bool scopeAcquired = false;
  4035. Js::OpCode op;
  4036. if (sym && sym->GetIsModuleExportStorage())
  4037. {
  4038. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4039. {
  4040. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4041. }
  4042. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4043. return;
  4044. }
  4045. if (isFncDeclVar)
  4046. {
  4047. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4048. // of the parent function, so we need to calculate envIndex in lieu of the while
  4049. // loop below.
  4050. do
  4051. {
  4052. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4053. } while (scope != symScope);
  4054. Assert(scope == symScope);
  4055. scopeLocation = scope->GetLocation();
  4056. }
  4057. while (!isFncDeclVar)
  4058. {
  4059. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4060. if (scope == this->globalScope)
  4061. {
  4062. break;
  4063. }
  4064. if (envIndex == -1)
  4065. {
  4066. Assert(funcInfo == scope->GetFunc());
  4067. scopeLocation = scope->GetLocation();
  4068. }
  4069. if (scope == symScope)
  4070. {
  4071. break;
  4072. }
  4073. // Found a scope to which the property may have been added.
  4074. Assert(scope && scope->GetIsDynamic());
  4075. if (!fLabelDefined)
  4076. {
  4077. fLabelDefined = true;
  4078. doneLabel = this->m_writer.DefineLabel();
  4079. }
  4080. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4081. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4082. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4083. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4084. if (envIndex != -1)
  4085. {
  4086. this->m_writer.BrEnvProperty(
  4087. Js::OpCode::BrOnNoEnvProperty,
  4088. nextLabel,
  4089. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4090. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4091. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4092. AssertOrFailFast(scope->GetIsObject());
  4093. this->m_writer.SlotI1(
  4094. Js::OpCode::LdEnvObj,
  4095. instLocation,
  4096. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4097. if (unwrapWithObj)
  4098. {
  4099. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4100. }
  4101. this->m_writer.PatchableProperty(
  4102. Js::OpCode::StFld,
  4103. rhsLocation,
  4104. instLocation,
  4105. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4106. funcInfo->ReleaseTmpRegister(instLocation);
  4107. }
  4108. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4109. {
  4110. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4111. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4112. Assert(!unwrapWithObj);
  4113. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4114. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4115. }
  4116. else
  4117. {
  4118. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4119. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4120. if (unwrapWithObj)
  4121. {
  4122. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4123. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4124. scopeLocation = unwrappedScopeLocation;
  4125. }
  4126. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4127. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4128. if (unwrapWithObj)
  4129. {
  4130. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4131. }
  4132. }
  4133. this->m_writer.Br(doneLabel);
  4134. this->m_writer.MarkLabel(nextLabel);
  4135. }
  4136. // Arrived at the scope in which the property was defined.
  4137. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4138. {
  4139. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4140. // Intentionally continue on to do normal EmitPropStore behavior so
  4141. // that the bytecode ends up well-formed for the backend. This is
  4142. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4143. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4144. // of their load and then they skip emitting their own bytecode.
  4145. // Potayto potahto.
  4146. }
  4147. if (sym == nullptr || sym->GetIsGlobal())
  4148. {
  4149. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4150. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4151. if (this->flags & fscrEval)
  4152. {
  4153. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4154. {
  4155. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4156. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4157. }
  4158. else
  4159. {
  4160. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4161. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4162. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4163. }
  4164. }
  4165. else if (this->flags & fscrImplicitThis)
  4166. {
  4167. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4168. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4169. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4170. }
  4171. else
  4172. {
  4173. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false), rhsLocation, propertyId, false, true, funcInfo);
  4174. }
  4175. }
  4176. else if (sym->GetIsFuncExpr())
  4177. {
  4178. // Store to function expr variable.
  4179. // strict mode: we need to throw type error
  4180. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4181. {
  4182. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4183. // It doesn't matter which register we use, as long as it's valid for this function.
  4184. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4185. }
  4186. }
  4187. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4188. {
  4189. if (!isConstDecl && sym->GetIsConst())
  4190. {
  4191. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4192. // we have to catch it at runtime.
  4193. this->m_writer.W1(
  4194. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4195. }
  4196. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4197. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4198. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4199. // The property is in memory rather than register. We'll have to load it from the slots.
  4200. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4201. if (envIndex != -1)
  4202. {
  4203. this->m_writer.SlotI2(op, rhsLocation,
  4204. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4205. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4206. }
  4207. else if (scopeLocation != Js::Constants::NoRegister &&
  4208. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4209. {
  4210. this->m_writer.SlotI1(op, rhsLocation,
  4211. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4212. }
  4213. else
  4214. {
  4215. Assert(scope->HasInnerScopeIndex());
  4216. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4217. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4218. }
  4219. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4220. {
  4221. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4222. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4223. }
  4224. }
  4225. else if (isConstDecl)
  4226. {
  4227. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4228. if (this->ShouldTrackDebuggerMetadata())
  4229. {
  4230. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4231. }
  4232. }
  4233. else
  4234. {
  4235. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4236. {
  4237. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4238. // we have to catch it at runtime.
  4239. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4240. }
  4241. if (rhsLocation != sym->GetLocation())
  4242. {
  4243. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4244. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4245. {
  4246. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4247. }
  4248. }
  4249. }
  4250. if (fLabelDefined)
  4251. {
  4252. this->m_writer.MarkLabel(doneLabel);
  4253. }
  4254. if (scopeAcquired)
  4255. {
  4256. funcInfo->ReleaseTmpRegister(scopeLocation);
  4257. }
  4258. }
  4259. Js::OpCode
  4260. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4261. {
  4262. Js::OpCode op;
  4263. if (envIndex != -1)
  4264. {
  4265. if (scope->GetIsObject())
  4266. {
  4267. op = Js::OpCode::LdEnvObjSlot;
  4268. }
  4269. else
  4270. {
  4271. op = Js::OpCode::LdEnvSlot;
  4272. }
  4273. }
  4274. else if (scopeLocation != Js::Constants::NoRegister &&
  4275. scopeLocation == funcInfo->frameSlotsRegister)
  4276. {
  4277. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4278. {
  4279. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4280. // We should use the param scope's bytecode now.
  4281. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4282. op = Js::OpCode::LdParamSlot;
  4283. }
  4284. else
  4285. {
  4286. op = Js::OpCode::LdLocalSlot;
  4287. }
  4288. }
  4289. else if (scopeLocation != Js::Constants::NoRegister &&
  4290. scopeLocation == funcInfo->frameObjRegister)
  4291. {
  4292. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4293. {
  4294. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4295. // We should use the param scope's bytecode now.
  4296. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4297. op = Js::OpCode::LdParamObjSlot;
  4298. }
  4299. else
  4300. {
  4301. op = Js::OpCode::LdLocalObjSlot;
  4302. }
  4303. }
  4304. else if (scope->HasInnerScopeIndex())
  4305. {
  4306. if (scope->GetIsObject())
  4307. {
  4308. op = Js::OpCode::LdInnerObjSlot;
  4309. }
  4310. else
  4311. {
  4312. op = Js::OpCode::LdInnerSlot;
  4313. }
  4314. }
  4315. else
  4316. {
  4317. AssertOrFailFast(scope->GetIsObject());
  4318. op = Js::OpCode::LdObjSlot;
  4319. }
  4320. return op;
  4321. }
  4322. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4323. {
  4324. #if DBG
  4325. // We should load a const 'this' binding if the following holds
  4326. // - The function has a 'this' name node
  4327. // - We are in a global or global lambda function
  4328. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4329. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4330. {
  4331. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4332. && !funcInfo->GetThisSymbol()
  4333. && !(this->flags & fscrEval));
  4334. }
  4335. #endif
  4336. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4337. }
  4338. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4339. {
  4340. Symbol* sym = pnodeSpecialName->sym;
  4341. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4342. {
  4343. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4344. }
  4345. else
  4346. {
  4347. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4348. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4349. {
  4350. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4351. }
  4352. }
  4353. }
  4354. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4355. {
  4356. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4357. {
  4358. if (init)
  4359. {
  4360. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4361. }
  4362. else
  4363. {
  4364. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4365. }
  4366. }
  4367. }
  4368. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4369. {
  4370. // If sym belongs to a parent frame, get it from the closure environment.
  4371. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4372. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4373. // Otherwise, just copy the value to the lhsLocation.
  4374. Js::ByteCodeLabel doneLabel = 0;
  4375. bool fLabelDefined = false;
  4376. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4377. Js::PropertyId envIndex = -1;
  4378. Scope *scope = nullptr;
  4379. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4380. Assert(symScope);
  4381. if (sym && sym->GetIsModuleExportStorage())
  4382. {
  4383. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4384. return;
  4385. }
  4386. for (;;)
  4387. {
  4388. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4389. if (scope == this->globalScope)
  4390. {
  4391. break;
  4392. }
  4393. scopeLocation = scope->GetLocation();
  4394. if (scope == symScope)
  4395. {
  4396. break;
  4397. }
  4398. // Found a scope to which the property may have been added.
  4399. Assert(scope && scope->GetIsDynamic());
  4400. if (!fLabelDefined)
  4401. {
  4402. fLabelDefined = true;
  4403. doneLabel = this->m_writer.DefineLabel();
  4404. }
  4405. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4406. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4407. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4408. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4409. if (envIndex != -1)
  4410. {
  4411. this->m_writer.BrEnvProperty(
  4412. Js::OpCode::BrOnNoEnvProperty,
  4413. nextLabel,
  4414. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4415. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4416. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4417. AssertOrFailFast(scope->GetIsObject());
  4418. this->m_writer.SlotI1(
  4419. Js::OpCode::LdEnvObj,
  4420. instLocation,
  4421. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4422. if (unwrapWithObj)
  4423. {
  4424. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4425. }
  4426. this->m_writer.PatchableProperty(
  4427. Js::OpCode::LdFld,
  4428. lhsLocation,
  4429. instLocation,
  4430. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4431. funcInfo->ReleaseTmpRegister(instLocation);
  4432. }
  4433. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4434. {
  4435. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4436. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4437. Assert(!unwrapWithObj);
  4438. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4439. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4440. }
  4441. else
  4442. {
  4443. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4444. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4445. if (unwrapWithObj)
  4446. {
  4447. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4448. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4449. scopeLocation = unwrappedScopeLocation;
  4450. }
  4451. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4452. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4453. if (unwrapWithObj)
  4454. {
  4455. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4456. }
  4457. }
  4458. this->m_writer.Br(doneLabel);
  4459. this->m_writer.MarkLabel(nextLabel);
  4460. }
  4461. // Arrived at the scope in which the property was defined.
  4462. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4463. {
  4464. // Ensure this symbol has a slot if it needs one.
  4465. if (sym->IsInSlot(this, funcInfo))
  4466. {
  4467. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4468. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4469. }
  4470. if (skipUseBeforeDeclarationCheck)
  4471. {
  4472. if (lhsLocation != Js::Constants::NoRegister)
  4473. {
  4474. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4475. }
  4476. }
  4477. else
  4478. {
  4479. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4480. }
  4481. }
  4482. else if (sym == nullptr || sym->GetIsGlobal())
  4483. {
  4484. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4485. if (this->flags & fscrEval)
  4486. {
  4487. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4488. {
  4489. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4490. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4491. }
  4492. else
  4493. {
  4494. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4495. // Load of a symbol with unknown scope from within eval
  4496. // Get it from the closure environment.
  4497. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4498. }
  4499. }
  4500. else if (this->flags & fscrImplicitThis)
  4501. {
  4502. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4503. // Load of a symbol with unknown scope from within event handler.
  4504. // Get it from the closure environment.
  4505. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4506. }
  4507. else
  4508. {
  4509. // Special case non-writable built-ins
  4510. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4511. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4512. // next time we run. May want to catch that in the JIT.
  4513. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4514. // These properties are non-writable
  4515. switch (propertyId)
  4516. {
  4517. case Js::PropertyIds::NaN:
  4518. opcode = Js::OpCode::LdNaN;
  4519. break;
  4520. case Js::PropertyIds::Infinity:
  4521. opcode = Js::OpCode::LdInfinity;
  4522. break;
  4523. case Js::PropertyIds::undefined:
  4524. opcode = Js::OpCode::LdUndef;
  4525. break;
  4526. case Js::PropertyIds::__chakraLibrary:
  4527. if (CONFIG_FLAG(LdChakraLib)) {
  4528. opcode = Js::OpCode::LdChakraLib;
  4529. }
  4530. break;
  4531. }
  4532. if (opcode == Js::OpCode::LdRootFld)
  4533. {
  4534. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4535. }
  4536. else
  4537. {
  4538. this->Writer()->Reg1(opcode, lhsLocation);
  4539. }
  4540. }
  4541. }
  4542. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4543. {
  4544. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4545. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4546. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4547. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4548. Js::OpCode op;
  4549. // Now get the property from its slot.
  4550. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4551. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4552. if (envIndex != -1)
  4553. {
  4554. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4555. }
  4556. else if (scopeLocation != Js::Constants::NoRegister &&
  4557. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4558. {
  4559. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4560. }
  4561. else if (scope->HasInnerScopeIndex())
  4562. {
  4563. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4564. }
  4565. else
  4566. {
  4567. AssertOrFailFast(scope->GetIsObject());
  4568. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4569. }
  4570. if (chkBlockVar)
  4571. {
  4572. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4573. }
  4574. }
  4575. else
  4576. {
  4577. if (lhsLocation != sym->GetLocation())
  4578. {
  4579. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4580. }
  4581. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4582. {
  4583. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4584. }
  4585. }
  4586. if (fLabelDefined)
  4587. {
  4588. this->m_writer.MarkLabel(doneLabel);
  4589. }
  4590. }
  4591. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4592. {
  4593. bool tdz = sym->GetIsBlockVar()
  4594. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4595. return tdz || sym->GetIsNonSimpleParameter();
  4596. }
  4597. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4598. {
  4599. // If sym belongs to a parent frame, delete it from the closure environment.
  4600. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4601. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4602. // Otherwise, just return false.
  4603. Js::ByteCodeLabel doneLabel = 0;
  4604. bool fLabelDefined = false;
  4605. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4606. Js::PropertyId envIndex = -1;
  4607. Scope *scope = nullptr;
  4608. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4609. Assert(symScope);
  4610. for (;;)
  4611. {
  4612. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4613. if (scope == this->globalScope)
  4614. {
  4615. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4616. }
  4617. else if (envIndex == -1)
  4618. {
  4619. Assert(funcInfo == scope->GetFunc());
  4620. scopeLocation = scope->GetLocation();
  4621. }
  4622. if (scope == symScope)
  4623. {
  4624. break;
  4625. }
  4626. // Found a scope to which the property may have been added.
  4627. Assert(scope && scope->GetIsDynamic());
  4628. if (!fLabelDefined)
  4629. {
  4630. fLabelDefined = true;
  4631. doneLabel = this->m_writer.DefineLabel();
  4632. }
  4633. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4634. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4635. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4636. if (envIndex != -1)
  4637. {
  4638. this->m_writer.BrEnvProperty(
  4639. Js::OpCode::BrOnNoEnvProperty,
  4640. nextLabel,
  4641. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4642. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4643. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4644. AssertOrFailFast(scope->GetIsObject());
  4645. this->m_writer.SlotI1(
  4646. Js::OpCode::LdEnvObj,
  4647. instLocation,
  4648. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4649. if (unwrapWithObj)
  4650. {
  4651. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4652. }
  4653. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4654. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4655. funcInfo->ReleaseTmpRegister(instLocation);
  4656. }
  4657. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4658. {
  4659. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4660. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4661. Assert(!unwrapWithObj);
  4662. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4663. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4664. }
  4665. else
  4666. {
  4667. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4668. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4669. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4670. if (unwrapWithObj)
  4671. {
  4672. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4673. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4674. scopeLocation = unwrappedScopeLocation;
  4675. }
  4676. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4677. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4678. if (unwrapWithObj)
  4679. {
  4680. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4681. }
  4682. }
  4683. this->m_writer.Br(doneLabel);
  4684. this->m_writer.MarkLabel(nextLabel);
  4685. }
  4686. // Arrived at the scope in which the property was defined.
  4687. if (sym == nullptr || sym->GetIsGlobal())
  4688. {
  4689. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4690. if (this->flags & (fscrEval | fscrImplicitThis))
  4691. {
  4692. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4693. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4694. }
  4695. else
  4696. {
  4697. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4698. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4699. }
  4700. }
  4701. else
  4702. {
  4703. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4704. sym->EnsureScopeSlot(this, funcInfo);
  4705. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4706. }
  4707. if (fLabelDefined)
  4708. {
  4709. this->m_writer.MarkLabel(doneLabel);
  4710. }
  4711. }
  4712. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4713. {
  4714. uint cacheId;
  4715. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4716. switch (ldFldOp)
  4717. {
  4718. case Js::OpCode::LdRootFldForTypeOf:
  4719. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4720. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4721. break;
  4722. case Js::OpCode::LdLocalFld:
  4723. case Js::OpCode::ScopedLdFldForTypeOf:
  4724. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4725. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4726. break;
  4727. default:
  4728. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4729. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4730. break;
  4731. }
  4732. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4733. funcInfo->ReleaseTmpRegister(tmpReg);
  4734. }
  4735. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4736. {
  4737. // If sym belongs to a parent frame, delete it from the closure environment.
  4738. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4739. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4740. // Otherwise, just return false
  4741. Js::ByteCodeLabel doneLabel = 0;
  4742. bool fLabelDefined = false;
  4743. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4744. Js::PropertyId envIndex = -1;
  4745. Scope *scope = nullptr;
  4746. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4747. Assert(symScope);
  4748. if (sym && sym->GetIsModuleExportStorage())
  4749. {
  4750. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4751. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4752. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4753. funcInfo->ReleaseTmpRegister(tmpLocation);
  4754. return;
  4755. }
  4756. for (;;)
  4757. {
  4758. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4759. if (scope == this->globalScope)
  4760. {
  4761. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4762. }
  4763. else if (envIndex == -1)
  4764. {
  4765. Assert(funcInfo == scope->GetFunc());
  4766. scopeLocation = scope->GetLocation();
  4767. }
  4768. if (scope == symScope)
  4769. {
  4770. break;
  4771. }
  4772. // Found a scope to which the property may have been added.
  4773. Assert(scope && scope->GetIsDynamic());
  4774. if (!fLabelDefined)
  4775. {
  4776. fLabelDefined = true;
  4777. doneLabel = this->m_writer.DefineLabel();
  4778. }
  4779. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4780. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4781. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4782. if (envIndex != -1)
  4783. {
  4784. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4785. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4786. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4787. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4788. AssertOrFailFast(scope->GetIsObject());
  4789. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4790. instLocation,
  4791. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4792. if (unwrapWithObj)
  4793. {
  4794. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4795. }
  4796. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4797. funcInfo->ReleaseTmpRegister(instLocation);
  4798. }
  4799. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4800. {
  4801. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4802. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4803. Assert(!unwrapWithObj);
  4804. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4805. }
  4806. else
  4807. {
  4808. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4809. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4810. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4811. if (unwrapWithObj)
  4812. {
  4813. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4814. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4815. scopeLocation = unwrappedScopeLocation;
  4816. }
  4817. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4818. if (unwrapWithObj)
  4819. {
  4820. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4821. }
  4822. }
  4823. this->m_writer.Br(doneLabel);
  4824. this->m_writer.MarkLabel(nextLabel);
  4825. }
  4826. // Arrived at the scope in which the property was defined.
  4827. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4828. {
  4829. // Ensure this symbol has a slot if it needs one.
  4830. if (sym->IsInSlot(this, funcInfo))
  4831. {
  4832. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4833. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4834. }
  4835. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4836. }
  4837. else if (sym == nullptr || sym->GetIsGlobal())
  4838. {
  4839. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4840. if (this->flags & fscrEval)
  4841. {
  4842. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4843. {
  4844. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4845. }
  4846. else
  4847. {
  4848. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4849. }
  4850. }
  4851. else if (this->flags & fscrImplicitThis)
  4852. {
  4853. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4854. }
  4855. else
  4856. {
  4857. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4858. }
  4859. }
  4860. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4861. {
  4862. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4863. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4864. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4865. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4866. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4867. Js::OpCode op;
  4868. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4869. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4870. if (envIndex != -1)
  4871. {
  4872. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4873. }
  4874. else if (scopeLocation != Js::Constants::NoRegister &&
  4875. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4876. {
  4877. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4878. }
  4879. else if (scope->HasInnerScopeIndex())
  4880. {
  4881. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4882. }
  4883. else
  4884. {
  4885. AssertOrFailFast(scope->GetIsObject());
  4886. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4887. }
  4888. if (chkBlockVar)
  4889. {
  4890. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4891. }
  4892. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4893. funcInfo->ReleaseTmpRegister(tmpLocation);
  4894. }
  4895. else
  4896. {
  4897. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4898. }
  4899. if (fLabelDefined)
  4900. {
  4901. this->m_writer.MarkLabel(doneLabel);
  4902. }
  4903. }
  4904. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  4905. {
  4906. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4907. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4908. // remain local to the eval code.
  4909. Assert(pnodeBlock->nop == knopBlock);
  4910. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4911. if (!(this->flags & fscrEvalCode))
  4912. {
  4913. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4914. {
  4915. FuncInfo *funcInfo = this->TopFuncInfo();
  4916. Symbol *sym = pnode->AsParseNodeVar()->sym;
  4917. Assert(sym->GetIsGlobal());
  4918. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4919. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4920. });
  4921. }
  4922. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo)
  4923. {
  4924. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4925. if (this->flags & fscrEval)
  4926. {
  4927. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4928. {
  4929. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4930. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4931. }
  4932. }
  4933. else
  4934. {
  4935. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4936. }
  4937. };
  4938. // scan for function declarations
  4939. // these behave like "var" declarations
  4940. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  4941. {
  4942. switch (pnode->nop) {
  4943. case knopFncDecl:
  4944. if (pnode->AsParseNodeFnc()->IsDeclaration())
  4945. {
  4946. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo);
  4947. }
  4948. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  4949. break;
  4950. case knopBlock:
  4951. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  4952. break;
  4953. case knopCatch:
  4954. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  4955. break;
  4956. case knopWith:
  4957. pnode = pnode->AsParseNodeWith()->pnodeNext;
  4958. break;
  4959. default:
  4960. Assert(UNREACHED);
  4961. }
  4962. }
  4963. // scan for var declarations
  4964. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  4965. {
  4966. Symbol* sym = pnode->AsParseNodeVar()->sym;
  4967. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  4968. continue;
  4969. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4970. {
  4971. // The init node was bound to the catch object, because it's inside a catch and has the
  4972. // same name as the catch object. But we want to define a user var at function scope,
  4973. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4974. // This also applies to a var declaration in the same scope as a let declaration.
  4975. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4976. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  4977. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4978. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4979. }
  4980. Assert(sym->GetIsGlobal());
  4981. if (sym->GetSymbolType() == STVariable)
  4982. {
  4983. emitRedeclCheck(sym, funcInfo);
  4984. }
  4985. }
  4986. }
  4987. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  4988. {
  4989. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4990. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  4991. {
  4992. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  4993. });
  4994. }
  4995. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  4996. {
  4997. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4998. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  4999. {
  5000. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  5001. });
  5002. }
  5003. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5004. {
  5005. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5006. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5007. {
  5008. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5009. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  5010. Js::RecyclableObject* callsiteObject = library->TryGetStringTemplateCallsiteObject(pnode);
  5011. if (callsiteObject == nullptr)
  5012. {
  5013. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5014. rawArray->Freeze();
  5015. callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5016. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5017. callsiteObject->Freeze();
  5018. library->AddStringTemplateCallsiteObject(callsiteObject);
  5019. }
  5020. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5021. });
  5022. }
  5023. bool IsApplyArgs(ParseNodeCall* callNode)
  5024. {
  5025. ParseNode* target = callNode->pnodeTarget;
  5026. ParseNode* args = callNode->pnodeArgs;
  5027. if ((target != nullptr) && (target->nop == knopDot))
  5028. {
  5029. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5030. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5031. {
  5032. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5033. if (nameNode != nullptr)
  5034. {
  5035. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5036. if (nameIsApply && args != nullptr && args->nop == knopList)
  5037. {
  5038. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5039. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5040. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5041. {
  5042. return arg2->AsParseNodeName()->sym->IsArguments();
  5043. }
  5044. }
  5045. }
  5046. }
  5047. }
  5048. return false;
  5049. }
  5050. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5051. {
  5052. if ((pnode == nullptr) || (!applyCheck->matches))
  5053. {
  5054. return;
  5055. }
  5056. if (pnode->nop == knopCall)
  5057. {
  5058. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5059. {
  5060. if (!applyCheck->insideApplyCall)
  5061. {
  5062. applyCheck->matches = false;
  5063. }
  5064. applyCheck->insideApplyCall = false;
  5065. }
  5066. }
  5067. }
  5068. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5069. {
  5070. if ((pnode == nullptr) || (!applyCheck->matches))
  5071. {
  5072. return;
  5073. }
  5074. switch (pnode->nop)
  5075. {
  5076. case knopName:
  5077. {
  5078. Symbol* sym = pnode->AsParseNodeName()->sym;
  5079. if (sym != nullptr)
  5080. {
  5081. if (sym->IsArguments())
  5082. {
  5083. if (!applyCheck->insideApplyCall)
  5084. {
  5085. applyCheck->matches = false;
  5086. }
  5087. }
  5088. }
  5089. break;
  5090. }
  5091. case knopCall:
  5092. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5093. {
  5094. // no nested apply calls
  5095. if (applyCheck->insideApplyCall)
  5096. {
  5097. applyCheck->matches = false;
  5098. }
  5099. else
  5100. {
  5101. applyCheck->insideApplyCall = true;
  5102. applyCheck->sawApply = true;
  5103. pnode->AsParseNodeCall()->isApplyCall = true;
  5104. }
  5105. }
  5106. break;
  5107. }
  5108. }
  5109. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5110. {
  5111. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5112. // side-effects in the argument list. We need to know this so that the call target
  5113. // operands can be preserved if necessary.
  5114. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5115. // but we can be more precise if we need to be.
  5116. if (pSideEffect)
  5117. {
  5118. *pSideEffect = FALSE;
  5119. }
  5120. unsigned int argCount = 1;
  5121. if (pnode != nullptr)
  5122. {
  5123. while (pnode->nop == knopList)
  5124. {
  5125. argCount++;
  5126. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5127. {
  5128. *pSideEffect = TRUE;
  5129. }
  5130. pnode = pnode->AsParseNodeBin()->pnode2;
  5131. }
  5132. argCount++;
  5133. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5134. {
  5135. *pSideEffect = TRUE;
  5136. }
  5137. }
  5138. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5139. return argCount;
  5140. }
  5141. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5142. {
  5143. // Save a local name to a register other than its home location.
  5144. // This guards against side-effects in cases like x.foo(x = bar()).
  5145. Symbol *sym = nullptr;
  5146. if (pnode->nop == knopName)
  5147. {
  5148. sym = pnode->AsParseNodeName()->sym;
  5149. }
  5150. else if (pnode->nop == knopComputedName)
  5151. {
  5152. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5153. if (pnode1->nop == knopName)
  5154. {
  5155. sym = pnode1->AsParseNodeName()->sym;
  5156. }
  5157. }
  5158. if (sym == nullptr)
  5159. {
  5160. return;
  5161. }
  5162. // If the target is a local being kept in its home location,
  5163. // protect the target's value in the event the home location is overwritten.
  5164. if (pnode->location != Js::Constants::NoRegister &&
  5165. sym->GetScope()->GetFunc() == funcInfo &&
  5166. pnode->location == sym->GetLocation())
  5167. {
  5168. pnode->location = funcInfo->AcquireTmpRegister();
  5169. }
  5170. }
  5171. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5172. {
  5173. Assert(TopFuncInfo() != nullptr);
  5174. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5175. }
  5176. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5177. {
  5178. m_writer.EndStatement(node);
  5179. }
  5180. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5181. {
  5182. Assert(TopFuncInfo() != nullptr);
  5183. m_writer.StartSubexpression(node);
  5184. }
  5185. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5186. {
  5187. m_writer.EndSubexpression(node);
  5188. }
  5189. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5190. {
  5191. // Generate code for the LHS of an assignment.
  5192. switch (pnode->nop)
  5193. {
  5194. case knopDot:
  5195. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5196. break;
  5197. case knopIndex:
  5198. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5199. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5200. break;
  5201. case knopName:
  5202. break;
  5203. case knopArrayPattern:
  5204. case knopObjectPattern:
  5205. break;
  5206. case knopCall:
  5207. case knopNew:
  5208. // Emit the operands of a call that will be used as a LHS.
  5209. // These have to be emitted before the RHS, but they have to persist until
  5210. // the end of the expression.
  5211. // Emit the call target operands first.
  5212. // The call target does not need to be emitted for a super call - EmitSuperCall will do this.
  5213. if (!pnode->AsParseNodeCall()->isSuperCall)
  5214. {
  5215. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5216. {
  5217. case knopDot:
  5218. case knopIndex:
  5219. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5220. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5221. break;
  5222. case knopName:
  5223. {
  5224. Symbol* sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5225. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5226. {
  5227. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5228. }
  5229. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5230. {
  5231. // Can't get the value from the assigned register, so load it here.
  5232. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5233. }
  5234. else
  5235. {
  5236. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5237. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5238. // must manually check here.
  5239. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5240. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5241. }
  5242. break;
  5243. }
  5244. default:
  5245. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5246. break;
  5247. }
  5248. }
  5249. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5250. if (pnode->AsParseNodeCall()->pnodeArgs)
  5251. {
  5252. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5253. while (pnodeArg->nop == knopList)
  5254. {
  5255. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5256. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5257. }
  5258. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5259. }
  5260. break;
  5261. default:
  5262. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5263. break;
  5264. }
  5265. }
  5266. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5267. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5268. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5269. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5270. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5271. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5272. {
  5273. switch (elem->nop)
  5274. {
  5275. case knopVarDecl:
  5276. case knopLetDecl:
  5277. case knopConstDecl:
  5278. // We manually need to set NeedDeclaration since the node won't be visited.
  5279. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5280. break;
  5281. default:
  5282. EmitReference(elem, byteCodeGenerator, funcInfo);
  5283. }
  5284. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5285. funcInfo->ReleaseReference(elem);
  5286. }
  5287. void EmitDestructuredRestArray(ParseNode *elem,
  5288. Js::RegSlot iteratorLocation,
  5289. Js::RegSlot shouldCallReturnFunctionLocation,
  5290. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5291. ByteCodeGenerator *byteCodeGenerator,
  5292. FuncInfo *funcInfo)
  5293. {
  5294. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5295. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5296. if (isAssignmentTarget)
  5297. {
  5298. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5299. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5300. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5301. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5302. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5303. }
  5304. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5305. Js::OpCode::NewScArray,
  5306. restArrayLocation,
  5307. ByteCodeGenerator::DefaultArraySize);
  5308. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5309. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5310. // convey this is live on the back edge.
  5311. // As a workaround, we have a persistent var reg that is used for the loop counter
  5312. Js::RegSlot counterLocation = elem->location;
  5313. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5314. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5315. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5316. // loopTop:
  5317. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5318. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5319. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5320. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5321. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5322. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5323. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5324. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5325. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5326. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5327. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5328. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5329. byteCodeGenerator->Writer()->Element(
  5330. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5331. valueLocation, restArrayLocation, counterLocation);
  5332. funcInfo->ReleaseTmpRegister(valueLocation);
  5333. funcInfo->ReleaseTmpRegister(doneLocation);
  5334. funcInfo->ReleaseTmpRegister(itemLocation);
  5335. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5336. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5337. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5338. byteCodeGenerator->Writer()->Br(loopTop);
  5339. // iteratorDone:
  5340. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5341. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5342. if (isAssignmentTarget)
  5343. {
  5344. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5345. funcInfo->ReleaseReference(restElem);
  5346. }
  5347. else
  5348. {
  5349. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5350. }
  5351. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5352. }
  5353. void EmitDestructuredArray(
  5354. ParseNode *lhs,
  5355. Js::RegSlot rhsLocation,
  5356. ByteCodeGenerator *byteCodeGenerator,
  5357. FuncInfo *funcInfo);
  5358. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5359. {
  5360. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5361. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5362. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5363. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5364. }
  5365. /*
  5366. EmitDestructuredArray(lhsArray, rhs):
  5367. iterator = rhs[@@iterator]
  5368. if lhsArray empty
  5369. return
  5370. for each element in lhsArray except rest
  5371. value = iterator.next()
  5372. if element is a nested destructured array
  5373. EmitDestructuredArray(element, value)
  5374. else
  5375. if value is undefined and there is an initializer
  5376. evaluate initializer
  5377. evaluate element reference
  5378. element = initializer
  5379. else
  5380. element = value
  5381. if lhsArray has a rest element
  5382. rest = []
  5383. while iterator is not done
  5384. value = iterator.next()
  5385. rest.append(value)
  5386. */
  5387. void EmitDestructuredArrayCore(
  5388. ParseNode *list,
  5389. Js::RegSlot iteratorLocation,
  5390. Js::RegSlot shouldCallReturnFunctionLocation,
  5391. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5392. ByteCodeGenerator *byteCodeGenerator,
  5393. FuncInfo *funcInfo
  5394. )
  5395. {
  5396. Assert(list != nullptr);
  5397. ParseNode *elem = nullptr;
  5398. while (list != nullptr)
  5399. {
  5400. ParseNode *init = nullptr;
  5401. if (list->nop == knopList)
  5402. {
  5403. elem = list->AsParseNodeBin()->pnode1;
  5404. }
  5405. else
  5406. {
  5407. elem = list;
  5408. }
  5409. if (elem->nop == knopEllipsis)
  5410. {
  5411. break;
  5412. }
  5413. switch (elem->nop)
  5414. {
  5415. case knopAsg:
  5416. // An assignment node will always have an initializer
  5417. init = elem->AsParseNodeBin()->pnode2;
  5418. elem = elem->AsParseNodeBin()->pnode1;
  5419. break;
  5420. case knopVarDecl:
  5421. case knopLetDecl:
  5422. case knopConstDecl:
  5423. init = elem->AsParseNodeVar()->pnodeInit;
  5424. break;
  5425. default:
  5426. break;
  5427. }
  5428. byteCodeGenerator->StartStatement(elem);
  5429. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5430. if (isAssignmentTarget)
  5431. {
  5432. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5433. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5434. EmitReference(elem, byteCodeGenerator, funcInfo);
  5435. }
  5436. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5437. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5438. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5439. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5440. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5441. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5442. if (elem->nop == knopEmpty)
  5443. {
  5444. if (list->nop == knopList)
  5445. {
  5446. list = list->AsParseNodeBin()->pnode2;
  5447. funcInfo->ReleaseTmpRegister(doneLocation);
  5448. funcInfo->ReleaseTmpRegister(itemLocation);
  5449. continue;
  5450. }
  5451. else
  5452. {
  5453. Assert(list->nop == knopEmpty);
  5454. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5455. funcInfo->ReleaseTmpRegister(doneLocation);
  5456. funcInfo->ReleaseTmpRegister(itemLocation);
  5457. break;
  5458. }
  5459. }
  5460. // If the iterator hasn't completed, skip assigning undefined.
  5461. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5462. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5463. // We're not done with the iterator, so assign the .next() value.
  5464. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5465. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5466. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5467. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5468. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5469. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5470. // iteratorAlreadyDone:
  5471. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5472. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5473. // beforeDefaultAssign:
  5474. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5475. if (elem->IsPattern())
  5476. {
  5477. // If we get an undefined value and have an initializer, use it in place of undefined.
  5478. if (init != nullptr)
  5479. {
  5480. /*
  5481. the IR builder uses two symbols for a temp register in the if else path
  5482. R9 <- R3
  5483. if (...)
  5484. R9 <- R2
  5485. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5486. hence we have to create a new temp
  5487. TEMP REG USED TO FIX THIS PRODUCES THIS
  5488. R9 <- R3
  5489. if (BrEq_A R9, R3)
  5490. R10 <- R2 :
  5491. else
  5492. R10 <- R9 : skipdefault
  5493. ... = R10[@@iterator] : loadIter
  5494. */
  5495. // Temp Register
  5496. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5497. byteCodeGenerator->StartStatement(init);
  5498. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5499. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5500. // check value is undefined
  5501. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5502. // Evaluate the default expression and assign it.
  5503. Emit(init, byteCodeGenerator, funcInfo, false);
  5504. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5505. funcInfo->ReleaseLoc(init);
  5506. // jmp to loadIter
  5507. byteCodeGenerator->Writer()->Br(loadIter);
  5508. // skipDefault:
  5509. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5510. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5511. // loadIter:
  5512. // @@iterator
  5513. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5514. byteCodeGenerator->EndStatement(init);
  5515. if (elem->nop == knopObjectPattern)
  5516. {
  5517. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5518. }
  5519. else
  5520. {
  5521. // Recursively emit a destructured array using the current .next() as the RHS.
  5522. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5523. }
  5524. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5525. }
  5526. else
  5527. {
  5528. if (elem->nop == knopObjectPattern)
  5529. {
  5530. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5531. }
  5532. else
  5533. {
  5534. // Recursively emit a destructured array using the current .next() as the RHS.
  5535. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5536. }
  5537. }
  5538. }
  5539. else
  5540. {
  5541. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5542. }
  5543. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5544. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5545. if (list->nop != knopList)
  5546. {
  5547. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5548. }
  5549. funcInfo->ReleaseTmpRegister(valueLocation);
  5550. funcInfo->ReleaseTmpRegister(doneLocation);
  5551. funcInfo->ReleaseTmpRegister(itemLocation);
  5552. if (isAssignmentTarget)
  5553. {
  5554. funcInfo->ReleaseReference(elem);
  5555. }
  5556. byteCodeGenerator->EndStatement(elem);
  5557. if (list->nop == knopList)
  5558. {
  5559. list = list->AsParseNodeBin()->pnode2;
  5560. }
  5561. else
  5562. {
  5563. break;
  5564. }
  5565. }
  5566. // If we saw a rest element, emit the rest array.
  5567. if (elem != nullptr && elem->nop == knopEllipsis)
  5568. {
  5569. EmitDestructuredRestArray(elem,
  5570. iteratorLocation,
  5571. shouldCallReturnFunctionLocation,
  5572. shouldCallReturnFunctionLocationFinally,
  5573. byteCodeGenerator,
  5574. funcInfo);
  5575. }
  5576. }
  5577. // Generating
  5578. // try {
  5579. // CallIteratorClose
  5580. // } catch (e) {
  5581. // do nothing
  5582. // }
  5583. void EmitTryCatchAroundClose(
  5584. Js::RegSlot iteratorLocation,
  5585. Js::ByteCodeLabel endLabel,
  5586. ByteCodeGenerator *byteCodeGenerator,
  5587. FuncInfo *funcInfo)
  5588. {
  5589. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5590. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5591. //
  5592. // There is no need to add TryScopeRecord here as we are going to call 'return' function and there is not yield expression here.
  5593. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5594. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5595. byteCodeGenerator->Writer()->Br(endLabel);
  5596. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5597. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5598. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5599. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5600. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5601. }
  5602. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5603. {
  5604. Js::OpCode op;
  5605. Js::ByteCodeLabel label;
  5606. Js::RegSlot reg1;
  5607. Js::RegSlot reg2;
  5608. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5609. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5610. };
  5611. // Generating
  5612. // catch(e) {
  5613. // if (shouldCallReturn)
  5614. // CallReturnWhichWrappedByTryCatch
  5615. // throw e;
  5616. // }
  5617. void EmitTopLevelCatch(Js::ByteCodeLabel catchLabel,
  5618. Js::RegSlot iteratorLocation,
  5619. Js::RegSlot shouldCallReturnLocation,
  5620. Js::RegSlot shouldCallReturnLocationFinally,
  5621. ByteCodeGenerator *byteCodeGenerator,
  5622. FuncInfo *funcInfo)
  5623. {
  5624. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5625. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5626. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5627. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5628. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5629. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5630. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  5631. if (funcInfo->byteCodeFunction->IsCoroutine())
  5632. {
  5633. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  5634. }
  5635. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5636. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5637. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnLocationFinally);
  5638. EmitTryCatchAroundClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo);
  5639. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5640. // Rethrow the exception.
  5641. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5642. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5643. if (funcInfo->byteCodeFunction->IsCoroutine())
  5644. {
  5645. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5646. }
  5647. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5648. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5649. }
  5650. // Generating
  5651. // finally {
  5652. // if (shouldCallReturn)
  5653. // CallReturn
  5654. // }
  5655. void EmitTopLevelFinally(Js::ByteCodeLabel finallyLabel,
  5656. Js::RegSlot iteratorLocation,
  5657. Js::RegSlot shouldCallReturnLocation,
  5658. Js::RegSlot yieldExceptionLocation,
  5659. Js::RegSlot yieldOffsetLocation,
  5660. ByteCodeGenerator *byteCodeGenerator,
  5661. FuncInfo *funcInfo)
  5662. {
  5663. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5664. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5665. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5666. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5667. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5668. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5669. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5670. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5671. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, yieldExceptionLocation, yieldOffsetLocation);
  5672. if (isCoroutine)
  5673. {
  5674. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  5675. }
  5676. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5677. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5678. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5679. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5680. if (isCoroutine)
  5681. {
  5682. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5683. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5684. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5685. }
  5686. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5687. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5688. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5689. }
  5690. void EmitCatchAndFinallyBlocks(Js::ByteCodeLabel catchLabel,
  5691. Js::ByteCodeLabel finallyLabel,
  5692. Js::RegSlot iteratorLocation,
  5693. Js::RegSlot shouldCallReturnFunctionLocation,
  5694. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5695. Js::RegSlot yieldExceptionLocation,
  5696. Js::RegSlot yieldOffsetLocation,
  5697. ByteCodeGenerator *byteCodeGenerator,
  5698. FuncInfo *funcInfo
  5699. )
  5700. {
  5701. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5702. if (isCoroutine)
  5703. {
  5704. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5705. }
  5706. EmitTopLevelCatch(catchLabel,
  5707. iteratorLocation,
  5708. shouldCallReturnFunctionLocation,
  5709. shouldCallReturnFunctionLocationFinally,
  5710. byteCodeGenerator,
  5711. funcInfo);
  5712. if (isCoroutine)
  5713. {
  5714. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5715. }
  5716. EmitTopLevelFinally(finallyLabel,
  5717. iteratorLocation,
  5718. shouldCallReturnFunctionLocationFinally,
  5719. yieldExceptionLocation,
  5720. yieldOffsetLocation,
  5721. byteCodeGenerator,
  5722. funcInfo);
  5723. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  5724. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  5725. }
  5726. // Emit a wrapper try..finaly block around the destructuring elements
  5727. void EmitDestructuredArray(
  5728. ParseNode *lhs,
  5729. Js::RegSlot rhsLocation,
  5730. ByteCodeGenerator *byteCodeGenerator,
  5731. FuncInfo *funcInfo)
  5732. {
  5733. byteCodeGenerator->StartStatement(lhs);
  5734. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5735. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5736. Assert(lhs->nop == knopArrayPattern);
  5737. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  5738. if (list == nullptr)
  5739. { // Handline this case ([] = obj);
  5740. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5741. // No elements to bind or assign.
  5742. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5743. byteCodeGenerator->EndStatement(lhs);
  5744. return;
  5745. }
  5746. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  5747. // this variable will be set to true.
  5748. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  5749. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  5750. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5751. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5752. byteCodeGenerator->SetHasFinally(true);
  5753. byteCodeGenerator->SetHasTry(true);
  5754. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  5755. Js::RegSlot regException = Js::Constants::NoRegister;
  5756. Js::RegSlot regOffset = Js::Constants::NoRegister;
  5757. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5758. if (isCoroutine)
  5759. {
  5760. regException = funcInfo->AcquireTmpRegister();
  5761. regOffset = funcInfo->AcquireTmpRegister();
  5762. }
  5763. // Insert try node here
  5764. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  5765. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5766. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5767. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  5768. if (isCoroutine)
  5769. {
  5770. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  5771. tryRecForTryFinally.reg1 = regException;
  5772. tryRecForTryFinally.reg2 = regOffset;
  5773. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  5774. }
  5775. else
  5776. {
  5777. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  5778. }
  5779. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5780. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  5781. if (isCoroutine)
  5782. {
  5783. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  5784. }
  5785. EmitDestructuredArrayCore(list,
  5786. iteratorLocation,
  5787. shouldCallReturnFunctionLocation,
  5788. shouldCallReturnFunctionLocationFinally,
  5789. byteCodeGenerator,
  5790. funcInfo);
  5791. EmitCatchAndFinallyBlocks(catchLabel,
  5792. finallyLabel,
  5793. iteratorLocation,
  5794. shouldCallReturnFunctionLocation,
  5795. shouldCallReturnFunctionLocationFinally,
  5796. regException,
  5797. regOffset,
  5798. byteCodeGenerator,
  5799. funcInfo);
  5800. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5801. byteCodeGenerator->EndStatement(lhs);
  5802. }
  5803. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5804. Js::RegSlot objectLocation,
  5805. ParseNodePtr nameNode,
  5806. ByteCodeGenerator* byteCodeGenerator,
  5807. FuncInfo* funcInfo)
  5808. {
  5809. Assert(nameNode != nullptr);
  5810. if (nameNode->nop == knopComputedName)
  5811. {
  5812. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  5813. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5814. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5815. funcInfo->ReleaseLoc(pnode1);
  5816. }
  5817. else
  5818. {
  5819. Assert(nameNode->nop == knopStr);
  5820. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5821. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5822. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5823. }
  5824. }
  5825. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5826. Js::RegSlot rhsLocation,
  5827. ParseNodePtr initializer,
  5828. bool isNonPatternAssignmentTarget,
  5829. ByteCodeGenerator *byteCodeGenerator,
  5830. FuncInfo *funcInfo)
  5831. {
  5832. // 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
  5833. Js::ByteCodeLabel useDefault = -1;
  5834. Js::ByteCodeLabel end = -1;
  5835. Js::RegSlot rhsLocationTmp = rhsLocation;
  5836. if (initializer != nullptr)
  5837. {
  5838. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5839. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5840. end = byteCodeGenerator->Writer()->DefineLabel();
  5841. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5842. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5843. byteCodeGenerator->Writer()->Br(end);
  5844. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5845. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5846. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5847. funcInfo->ReleaseLoc(initializer);
  5848. byteCodeGenerator->Writer()->MarkLabel(end);
  5849. }
  5850. if (lhsElementNode->nop == knopArrayPattern)
  5851. {
  5852. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5853. }
  5854. else if (lhsElementNode->nop == knopObjectPattern)
  5855. {
  5856. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5857. }
  5858. else if (isNonPatternAssignmentTarget)
  5859. {
  5860. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5861. }
  5862. else
  5863. {
  5864. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5865. }
  5866. if (initializer != nullptr)
  5867. {
  5868. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5869. }
  5870. }
  5871. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5872. Js::RegSlot rhsLocation,
  5873. ByteCodeGenerator *byteCodeGenerator,
  5874. FuncInfo *funcInfo)
  5875. {
  5876. Assert(memberNode->nop == knopObjectPatternMember);
  5877. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5878. EmitNameInvoke(nameLocation, rhsLocation, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  5879. // Imagine we are transforming
  5880. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5881. ParseNodePtr lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  5882. ParseNodePtr init = nullptr;
  5883. if (lhsElementNode->IsVarLetOrConst())
  5884. {
  5885. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  5886. }
  5887. else if (lhsElementNode->nop == knopAsg)
  5888. {
  5889. init = lhsElementNode->AsParseNodeBin()->pnode2;
  5890. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  5891. }
  5892. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  5893. funcInfo->ReleaseTmpRegister(nameLocation);
  5894. }
  5895. void EmitDestructuredObject(ParseNode *lhs,
  5896. Js::RegSlot rhsLocationOrig,
  5897. ByteCodeGenerator *byteCodeGenerator,
  5898. FuncInfo *funcInfo)
  5899. {
  5900. Assert(lhs->nop == knopObjectPattern);
  5901. ParseNodePtr pnode1 = lhs->AsParseNodeUni()->pnode1;
  5902. byteCodeGenerator->StartStatement(lhs);
  5903. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5904. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  5905. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  5906. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  5907. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  5908. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5909. if (pnode1 != nullptr)
  5910. {
  5911. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember);
  5912. ParseNodePtr current = pnode1;
  5913. while (current->nop == knopList)
  5914. {
  5915. ParseNodePtr memberNode = current->AsParseNodeBin()->pnode1;
  5916. EmitDestructuredObjectMember(memberNode, rhsLocation, byteCodeGenerator, funcInfo);
  5917. current = current->AsParseNodeBin()->pnode2;
  5918. }
  5919. EmitDestructuredObjectMember(current, rhsLocation, byteCodeGenerator, funcInfo);
  5920. }
  5921. funcInfo->ReleaseTmpRegister(rhsLocation);
  5922. byteCodeGenerator->EndStatement(lhs);
  5923. }
  5924. void EmitAssignment(
  5925. ParseNode *asgnNode,
  5926. ParseNode *lhs,
  5927. Js::RegSlot rhsLocation,
  5928. ByteCodeGenerator *byteCodeGenerator,
  5929. FuncInfo *funcInfo)
  5930. {
  5931. switch (lhs->nop)
  5932. {
  5933. // assignment to a local or global variable
  5934. case knopVarDecl:
  5935. case knopLetDecl:
  5936. case knopConstDecl:
  5937. {
  5938. Symbol *sym = lhs->AsParseNodeVar()->sym;
  5939. Assert(sym != nullptr);
  5940. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  5941. break;
  5942. }
  5943. case knopName:
  5944. {
  5945. // Special names like 'this' or 'new.target' cannot be assigned to
  5946. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  5947. if (pnodeNameLhs->IsSpecialName())
  5948. {
  5949. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5950. }
  5951. else
  5952. {
  5953. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  5954. }
  5955. break;
  5956. }
  5957. // x.y =
  5958. case knopDot:
  5959. {
  5960. // PutValue(x, "y", rhs)
  5961. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  5962. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  5963. {
  5964. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5965. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  5966. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  5967. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  5968. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  5969. }
  5970. else
  5971. {
  5972. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  5973. byteCodeGenerator->Writer()->PatchableProperty(
  5974. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  5975. }
  5976. break;
  5977. }
  5978. case knopIndex:
  5979. {
  5980. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  5981. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  5982. {
  5983. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  5984. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  5985. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  5986. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5987. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  5988. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  5989. }
  5990. byteCodeGenerator->Writer()->Element(
  5991. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5992. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  5993. break;
  5994. }
  5995. case knopObjectPattern:
  5996. {
  5997. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5998. // Copy the rhs value to be the result of the assignment if needed.
  5999. if (asgnNode != nullptr)
  6000. {
  6001. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6002. }
  6003. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6004. }
  6005. case knopArrayPattern:
  6006. {
  6007. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6008. // Copy the rhs value to be the result of the assignment if needed.
  6009. if (asgnNode != nullptr)
  6010. {
  6011. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6012. }
  6013. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6014. }
  6015. case knopArray:
  6016. case knopObject:
  6017. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6018. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6019. // down early vs. runtime errors for destructuring.
  6020. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6021. break;
  6022. default:
  6023. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6024. break;
  6025. }
  6026. if (asgnNode != nullptr)
  6027. {
  6028. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6029. if (asgnNode->location != rhsLocation)
  6030. {
  6031. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6032. }
  6033. }
  6034. }
  6035. void EmitLoad(
  6036. ParseNode *lhs,
  6037. ByteCodeGenerator *byteCodeGenerator,
  6038. FuncInfo *funcInfo)
  6039. {
  6040. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6041. // in the process.
  6042. // We usually get here as part of an op-equiv expression: x.y += z;
  6043. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6044. switch (lhs->nop)
  6045. {
  6046. // load of a local or global variable
  6047. case knopName:
  6048. {
  6049. funcInfo->AcquireLoc(lhs);
  6050. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6051. break;
  6052. }
  6053. // = x.y
  6054. case knopDot:
  6055. {
  6056. // get field id for "y"
  6057. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6058. funcInfo->AcquireLoc(lhs);
  6059. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6060. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6061. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6062. break;
  6063. }
  6064. case knopIndex:
  6065. funcInfo->AcquireLoc(lhs);
  6066. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6067. byteCodeGenerator->Writer()->Element(
  6068. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6069. break;
  6070. // f(x) +=
  6071. case knopCall:
  6072. {
  6073. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6074. if (pnodeCallLhs->isSuperCall)
  6075. {
  6076. funcInfo->AcquireLoc(pnodeCallLhs);
  6077. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6078. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCallLhs->AsParseNodeSuperCall(), /*fReturnValue=*/ false);
  6079. }
  6080. else if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6081. {
  6082. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6083. Assert(CountArguments(args) == 2); // import() takes one argument
  6084. Emit(args, byteCodeGenerator, funcInfo, false);
  6085. funcInfo->ReleaseLoc(args);
  6086. funcInfo->AcquireLoc(pnodeCallLhs);
  6087. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6088. }
  6089. else
  6090. {
  6091. funcInfo->AcquireLoc(pnodeCallLhs);
  6092. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6093. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6094. }
  6095. break;
  6096. }
  6097. default:
  6098. funcInfo->AcquireLoc(lhs);
  6099. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6100. break;
  6101. }
  6102. }
  6103. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6104. {
  6105. if (pnode != nullptr)
  6106. {
  6107. while (pnode->nop == knopList)
  6108. {
  6109. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6110. pnode = pnode->AsParseNodeBin()->pnode2;
  6111. }
  6112. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6113. }
  6114. }
  6115. void EmitOneArg(
  6116. ParseNode *pnode,
  6117. BOOL fAssignRegs,
  6118. ByteCodeGenerator *byteCodeGenerator,
  6119. FuncInfo *funcInfo,
  6120. Js::ProfileId callSiteId,
  6121. Js::ArgSlot &argIndex,
  6122. Js::ArgSlot &spreadIndex,
  6123. Js::RegSlot argTempLocation,
  6124. bool emitProfiledArgout,
  6125. Js::AuxArray<uint32> *spreadIndices = nullptr
  6126. )
  6127. {
  6128. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6129. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6130. // We just need to emit the ArgOut instructions.
  6131. if (fAssignRegs)
  6132. {
  6133. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6134. }
  6135. if (pnode->nop == knopEllipsis)
  6136. {
  6137. Assert(spreadIndices != nullptr);
  6138. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6139. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6140. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6141. if (noArgOuts)
  6142. {
  6143. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6144. }
  6145. else
  6146. {
  6147. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6148. }
  6149. funcInfo->ReleaseTmpRegister(regVal);
  6150. }
  6151. else
  6152. {
  6153. if (noArgOuts)
  6154. {
  6155. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6156. }
  6157. else
  6158. {
  6159. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6160. }
  6161. }
  6162. argIndex++;
  6163. if (fAssignRegs)
  6164. {
  6165. funcInfo->ReleaseLoc(pnode);
  6166. }
  6167. }
  6168. size_t EmitArgsWithArgOutsAtEnd(
  6169. ParseNode *pnode,
  6170. BOOL fAssignRegs,
  6171. ByteCodeGenerator *byteCodeGenerator,
  6172. FuncInfo *funcInfo,
  6173. Js::ProfileId callSiteId,
  6174. Js::RegSlot thisLocation,
  6175. Js::ArgSlot argsCountForStartCall,
  6176. bool emitProfiledArgouts,
  6177. Js::AuxArray<uint32> *spreadIndices = nullptr
  6178. )
  6179. {
  6180. AssertOrFailFast(pnode != nullptr);
  6181. Js::ArgSlot argIndex = 0;
  6182. Js::ArgSlot spreadIndex = 0;
  6183. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6184. Js::RegSlot firstArgTempLocation = argTempLocation;
  6185. while (pnode->nop == knopList)
  6186. {
  6187. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6188. pnode = pnode->AsParseNodeBin()->pnode2;
  6189. argTempLocation = funcInfo->AcquireTmpRegister();
  6190. }
  6191. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6192. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6193. // Emit all argOuts now
  6194. if (thisLocation != Js::Constants::NoRegister)
  6195. {
  6196. // Emit the "this" object.
  6197. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6198. }
  6199. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6200. {
  6201. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6202. }
  6203. // Now release all those temps register
  6204. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6205. {
  6206. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6207. }
  6208. return argIndex;
  6209. }
  6210. size_t EmitArgs(
  6211. ParseNode *pnode,
  6212. BOOL fAssignRegs,
  6213. ByteCodeGenerator *byteCodeGenerator,
  6214. FuncInfo *funcInfo,
  6215. Js::ProfileId callSiteId,
  6216. bool emitProfiledArgouts,
  6217. Js::AuxArray<uint32> *spreadIndices = nullptr
  6218. )
  6219. {
  6220. Js::ArgSlot argIndex = 0;
  6221. Js::ArgSlot spreadIndex = 0;
  6222. if (pnode != nullptr)
  6223. {
  6224. while (pnode->nop == knopList)
  6225. {
  6226. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6227. pnode = pnode->AsParseNodeBin()->pnode2;
  6228. }
  6229. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6230. }
  6231. return argIndex;
  6232. }
  6233. void EmitArgListStart(
  6234. Js::RegSlot thisLocation,
  6235. ByteCodeGenerator *byteCodeGenerator,
  6236. FuncInfo *funcInfo,
  6237. Js::ProfileId callSiteId)
  6238. {
  6239. if (thisLocation != Js::Constants::NoRegister)
  6240. {
  6241. // Emit the "this" object.
  6242. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6243. }
  6244. }
  6245. Js::ArgSlot EmitArgListEnd(
  6246. ParseNode *pnode,
  6247. Js::RegSlot thisLocation,
  6248. Js::RegSlot evalLocation,
  6249. Js::RegSlot newTargetLocation,
  6250. ByteCodeGenerator *byteCodeGenerator,
  6251. FuncInfo *funcInfo,
  6252. size_t argIndex,
  6253. Js::ProfileId callSiteId)
  6254. {
  6255. BOOL fEvalInModule = false;
  6256. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6257. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6258. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6259. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6260. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6261. Js::ArgSlot evalIndex;
  6262. if (fIsEval && argSlotIndex > 0)
  6263. {
  6264. Assert(!fHasNewTarget);
  6265. // Pass the frame display as an extra argument to "eval".
  6266. // Do this only if eval is called with some args
  6267. Js::RegSlot evalEnv;
  6268. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6269. {
  6270. // Use current environment as the environment for the function being called when:
  6271. // - this is the root global function (not an eval's global function)
  6272. // - this is an eval's global function that is not in strict mode (see else block)
  6273. evalEnv = funcInfo->GetEnvRegister();
  6274. }
  6275. else
  6276. {
  6277. // Use the frame display as the environment for the function being called when:
  6278. // - this is not a global function and thus it will have its own scope
  6279. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6280. // has its own scope
  6281. evalEnv = funcInfo->frameDisplayRegister;
  6282. }
  6283. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6284. // Passing the FrameDisplay as an extra argument
  6285. evalIndex = argSlotIndex + 1;
  6286. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6287. {
  6288. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6289. }
  6290. else
  6291. {
  6292. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6293. }
  6294. }
  6295. if (fHasNewTarget)
  6296. {
  6297. Assert(!fIsEval);
  6298. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6299. }
  6300. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6301. // eval and no args passed, return 1 as argument count
  6302. if (fIsEval && pnode == nullptr)
  6303. {
  6304. return 1;
  6305. }
  6306. return argIntCount;
  6307. }
  6308. Js::ArgSlot EmitArgList(
  6309. ParseNode *pnode,
  6310. Js::RegSlot thisLocation,
  6311. Js::RegSlot newTargetLocation,
  6312. BOOL fIsEval,
  6313. BOOL fAssignRegs,
  6314. ByteCodeGenerator *byteCodeGenerator,
  6315. FuncInfo *funcInfo,
  6316. Js::ProfileId callSiteId,
  6317. Js::ArgSlot argsCountForStartCall,
  6318. bool emitArgOutsAtEnd,
  6319. bool emitProfiledArgouts,
  6320. uint16 spreadArgCount = 0,
  6321. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6322. {
  6323. // This function emits the arguments for a call.
  6324. // ArgOut's with uses immediately following defs.
  6325. if (!emitArgOutsAtEnd)
  6326. {
  6327. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6328. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6329. }
  6330. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6331. //
  6332. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6333. // This would be used while generating frameDisplay in EmitArgListEnd.
  6334. //
  6335. if (fIsEval)
  6336. {
  6337. evalLocation = funcInfo->AcquireTmpRegister();
  6338. }
  6339. if (spreadArgCount > 0)
  6340. {
  6341. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6342. Assert(spreadIndices != nullptr);
  6343. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6344. }
  6345. size_t argIndex = 0;
  6346. if (emitArgOutsAtEnd)
  6347. {
  6348. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6349. }
  6350. else
  6351. {
  6352. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6353. }
  6354. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6355. if (fIsEval)
  6356. {
  6357. funcInfo->ReleaseTmpRegister(evalLocation);
  6358. }
  6359. return argumentsCount;
  6360. }
  6361. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6362. {
  6363. uint index = 0;
  6364. while (args->nop == knopList && index < argCount)
  6365. {
  6366. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6367. {
  6368. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6369. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6370. }
  6371. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6372. {
  6373. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6374. #if ! FLOATVAR
  6375. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6376. #endif
  6377. vars[index++] = number;
  6378. }
  6379. else
  6380. {
  6381. AnalysisAssert(false);
  6382. }
  6383. args = args->AsParseNodeBin()->pnode2;
  6384. }
  6385. if (index == argCount)
  6386. {
  6387. Assert(false);
  6388. Js::Throw::InternalError();
  6389. return;
  6390. }
  6391. if (args->nop == knopInt)
  6392. {
  6393. int value = args->AsParseNodeInt()->lw;
  6394. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6395. }
  6396. else if (args->nop == knopFlt)
  6397. {
  6398. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6399. #if ! FLOATVAR
  6400. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6401. #endif
  6402. vars[index++] = number;
  6403. }
  6404. else
  6405. {
  6406. AnalysisAssert(false);
  6407. }
  6408. }
  6409. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6410. {
  6411. uint index = 0;
  6412. while (args->nop == knopList && index < argCount)
  6413. {
  6414. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6415. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6416. args = args->AsParseNodeBin()->pnode2;
  6417. }
  6418. if (index >= argCount)
  6419. {
  6420. Js::Throw::InternalError();
  6421. return;
  6422. }
  6423. Assert(args->nop == knopInt);
  6424. vars[index++] = args->AsParseNodeInt()->lw;
  6425. Assert(index == argCount);
  6426. }
  6427. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6428. {
  6429. uint index = 0;
  6430. while (args->nop == knopList && index < argCount)
  6431. {
  6432. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6433. if (nop == knopInt)
  6434. {
  6435. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6436. }
  6437. else
  6438. {
  6439. Assert(nop == knopFlt);
  6440. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6441. }
  6442. args = args->AsParseNodeBin()->pnode2;
  6443. }
  6444. if (index >= argCount)
  6445. {
  6446. Js::Throw::InternalError();
  6447. return;
  6448. }
  6449. if (args->nop == knopInt)
  6450. {
  6451. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6452. }
  6453. else
  6454. {
  6455. Assert(args->nop == knopFlt);
  6456. vars[index++] = args->AsParseNodeFloat()->dbl;
  6457. }
  6458. Assert(index == argCount);
  6459. }
  6460. //
  6461. // Called when we have new Ctr(constant, constant...)
  6462. //
  6463. Js::ArgSlot EmitNewObjectOfConstants(
  6464. ParseNode *pnode,
  6465. ByteCodeGenerator *byteCodeGenerator,
  6466. FuncInfo *funcInfo,
  6467. unsigned int argCount)
  6468. {
  6469. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6470. // Create the vars array
  6471. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6472. // Emit all constants to the vars array
  6473. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6474. // Finish the arg list
  6475. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6476. pnode->AsParseNodeCall()->pnodeArgs,
  6477. Js::Constants::NoRegister,
  6478. Js::Constants::NoRegister,
  6479. Js::Constants::NoRegister,
  6480. byteCodeGenerator,
  6481. funcInfo,
  6482. argCount - 1,
  6483. Js::Constants::NoProfileId);
  6484. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6485. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6486. // Generate the opcode with vars
  6487. byteCodeGenerator->Writer()->AuxiliaryContext(
  6488. Js::OpCode::NewScObject_A,
  6489. funcInfo->AcquireLoc(pnode),
  6490. vars,
  6491. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6492. pnode->AsParseNodeCall()->pnodeTarget->location);
  6493. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6494. return actualArgCount;
  6495. }
  6496. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6497. {
  6498. Js::OpCode opcode;
  6499. if (!isRoot)
  6500. {
  6501. if (callObjLocation == funcInfo->frameObjRegister)
  6502. {
  6503. opcode = Js::OpCode::LdLocalMethodFld;
  6504. }
  6505. else
  6506. {
  6507. opcode = Js::OpCode::LdMethodFld;
  6508. }
  6509. }
  6510. else if (isScoped)
  6511. {
  6512. opcode = Js::OpCode::ScopedLdMethodFld;
  6513. }
  6514. else
  6515. {
  6516. opcode = Js::OpCode::LdRootMethodFld;
  6517. }
  6518. if (isScoped || !isRoot)
  6519. {
  6520. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6521. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6522. if (callObjLocation == funcInfo->frameObjRegister)
  6523. {
  6524. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6525. }
  6526. else
  6527. {
  6528. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6529. }
  6530. }
  6531. else
  6532. {
  6533. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6534. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6535. }
  6536. }
  6537. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6538. {
  6539. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6540. // the global object, etc.)
  6541. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6542. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6543. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6544. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6545. }
  6546. // lhs.apply(this, arguments);
  6547. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6548. {
  6549. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6550. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6551. Assert(applyNode->nop == knopDot);
  6552. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6553. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6554. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6555. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6556. Assert(applyNode->nop == knopDot);
  6557. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6558. funcInfo->AcquireLoc(applyNode);
  6559. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6560. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6561. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6562. // call for apply, we won't remove the entry for "apply" cacheId from
  6563. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6564. // have removed an entry from a map upon seeing its corresponding call.
  6565. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6566. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6567. Assert(argSym && argSym->IsArguments());
  6568. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6569. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6570. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6571. // If apply is overridden, bail to slow path.
  6572. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6573. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6574. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6575. // may crash if we try to unbox it on the store.
  6576. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6577. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6578. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6579. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6580. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6581. funcInfo->ReleaseTmpRegister(argCountLocation);
  6582. funcInfo->ReleaseTmpRegister(stackArgReg);
  6583. funcInfo->ReleaseLoc(applyNode);
  6584. funcInfo->ReleaseLoc(funcNode);
  6585. // Clear these nodes as they are going to be used to re-generate the slow path.
  6586. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6587. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6588. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6589. // slow path
  6590. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6591. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6592. {
  6593. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6594. }
  6595. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6596. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6597. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6598. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6599. }
  6600. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6601. {
  6602. // Load a call target of the form x[y]().
  6603. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6604. }
  6605. void EmitCallTargetNoEvalComponents(
  6606. ParseNode *pnodeTarget,
  6607. BOOL fSideEffectArgs,
  6608. Js::RegSlot *thisLocation,
  6609. bool *releaseThisLocation,
  6610. Js::RegSlot *callObjLocation,
  6611. ByteCodeGenerator *byteCodeGenerator,
  6612. FuncInfo *funcInfo)
  6613. {
  6614. // We first get a reference to the call target, then evaluate the arguments, then
  6615. // evaluate the call target.
  6616. // - emit reference to target
  6617. // - copy instance to scratch reg if necessary.
  6618. // - assign this
  6619. // - assign instance for dynamic/global name
  6620. // - emit args
  6621. // - do call (CallFld/Elem/I)
  6622. *releaseThisLocation = true;
  6623. switch (pnodeTarget->nop)
  6624. {
  6625. case knopDot:
  6626. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6627. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6628. break;
  6629. case knopIndex:
  6630. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6631. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6632. break;
  6633. case knopName:
  6634. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6635. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  6636. if (*thisLocation == Js::Constants::NoRegister)
  6637. {
  6638. *thisLocation = funcInfo->undefinedConstantRegister;
  6639. }
  6640. break;
  6641. default:
  6642. *thisLocation = funcInfo->undefinedConstantRegister;
  6643. break;
  6644. }
  6645. }
  6646. void EmitCallTarget(
  6647. ParseNode *pnodeTarget,
  6648. BOOL fSideEffectArgs,
  6649. Js::RegSlot *thisLocation,
  6650. bool *releaseThisLocation,
  6651. Js::RegSlot *callObjLocation,
  6652. ByteCodeGenerator *byteCodeGenerator,
  6653. FuncInfo *funcInfo)
  6654. {
  6655. // - emit target
  6656. // - assign this
  6657. // - emit args
  6658. // - do call
  6659. // The call target is fully evaluated before the argument list. Note that we're not handling
  6660. // put-call cases here currently, as such cases only apply to host objects
  6661. // and are very unlikely to behave differently depending on the order of evaluation.
  6662. *releaseThisLocation = true;
  6663. switch (pnodeTarget->nop)
  6664. {
  6665. case knopDot:
  6666. {
  6667. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  6668. funcInfo->AcquireLoc(pnodeBinTarget);
  6669. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6670. // them from side-effects.
  6671. if (fSideEffectArgs)
  6672. {
  6673. // Though we're done with target evaluation after this point, still protect opnd1 from
  6674. // arg side-effects as it's the "this" pointer.
  6675. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  6676. }
  6677. Assert(pnodeBinTarget->pnode2->nop == knopName);
  6678. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  6679. {
  6680. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  6681. }
  6682. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  6683. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6684. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  6685. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  6686. {
  6687. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6688. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6689. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  6690. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  6691. // Function calls on the 'super' object should maintain current 'this' pointer
  6692. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6693. *releaseThisLocation = false;
  6694. }
  6695. else
  6696. {
  6697. *thisLocation = pnodeBinTarget->pnode1->location;
  6698. }
  6699. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6700. break;
  6701. }
  6702. case knopIndex:
  6703. {
  6704. funcInfo->AcquireLoc(pnodeTarget);
  6705. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6706. // them from side-effects.
  6707. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  6708. {
  6709. // Though we're done with target evaluation after this point, still protect opnd1 from
  6710. // arg or opnd2 side-effects as it's the "this" pointer.
  6711. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  6712. }
  6713. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  6714. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  6715. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  6716. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6717. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6718. {
  6719. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6720. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6721. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  6722. // Function calls on the 'super' object should maintain current 'this' pointer
  6723. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6724. *releaseThisLocation = false;
  6725. }
  6726. else
  6727. {
  6728. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6729. }
  6730. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6731. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  6732. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6733. {
  6734. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  6735. }
  6736. break;
  6737. }
  6738. case knopName:
  6739. {
  6740. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  6741. if (!pnodeNameTarget->IsSpecialName())
  6742. {
  6743. funcInfo->AcquireLoc(pnodeNameTarget);
  6744. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6745. // them from side-effects.
  6746. if (fSideEffectArgs)
  6747. {
  6748. SaveOpndValue(pnodeNameTarget, funcInfo);
  6749. }
  6750. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  6751. if (*callObjLocation != Js::Constants::NoRegister)
  6752. {
  6753. // Load the call target as a property of the instance.
  6754. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  6755. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6756. break;
  6757. }
  6758. }
  6759. // FALL THROUGH to evaluate call target.
  6760. }
  6761. default:
  6762. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6763. // them from side-effects.
  6764. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6765. *thisLocation = funcInfo->undefinedConstantRegister;
  6766. break;
  6767. }
  6768. // "This" pointer should have been assigned by the above.
  6769. Assert(*thisLocation != Js::Constants::NoRegister);
  6770. }
  6771. void EmitCallI(
  6772. ParseNodeCall *pnodeCall,
  6773. BOOL fEvaluateComponents,
  6774. BOOL fIsEval,
  6775. BOOL fHasNewTarget,
  6776. uint32 actualArgCount,
  6777. ByteCodeGenerator *byteCodeGenerator,
  6778. FuncInfo *funcInfo,
  6779. Js::ProfileId callSiteId,
  6780. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6781. {
  6782. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6783. // already evaluated.
  6784. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6785. Js::OpCode op;
  6786. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6787. uint spreadExtraAlloc = 0;
  6788. bool isSuperCall = pnodeCall->isSuperCall;
  6789. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6790. // check for integer overflow
  6791. if ((size_t)actualArgSlotCount != actualArgCount)
  6792. {
  6793. Js::Throw::OutOfMemory();
  6794. }
  6795. if (fEvaluateComponents && !isSuperCall)
  6796. {
  6797. // Release the call target operands we assigned above. If we didn't assign them here,
  6798. // we'll need them later, so we can't re-use them for the result of the call.
  6799. funcInfo->ReleaseLoc(pnodeTarget);
  6800. }
  6801. // Grab a register for the call result.
  6802. if (pnodeCall->isUsed)
  6803. {
  6804. funcInfo->AcquireLoc(pnodeCall);
  6805. }
  6806. if (fIsEval)
  6807. {
  6808. op = Js::OpCode::CallIExtendedFlags;
  6809. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6810. }
  6811. else
  6812. {
  6813. if (isSuperCall)
  6814. {
  6815. callFlags = Js::CallFlags_New;
  6816. }
  6817. if (fHasNewTarget)
  6818. {
  6819. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6820. }
  6821. if (pnodeCall->spreadArgCount > 0)
  6822. {
  6823. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6824. }
  6825. else
  6826. {
  6827. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6828. }
  6829. }
  6830. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6831. {
  6832. if (isSuperCall)
  6833. {
  6834. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6835. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  6836. }
  6837. else
  6838. {
  6839. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6840. }
  6841. }
  6842. else
  6843. {
  6844. uint spreadIndicesSize = 0;
  6845. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6846. if (pnodeCall->spreadArgCount > 0)
  6847. {
  6848. Assert(spreadIndices != nullptr);
  6849. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  6850. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  6851. options = Js::CallIExtended_SpreadArgs;
  6852. }
  6853. if (isSuperCall)
  6854. {
  6855. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6856. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6857. }
  6858. else
  6859. {
  6860. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6861. }
  6862. }
  6863. if (pnodeCall->spreadArgCount > 0)
  6864. {
  6865. Assert(spreadExtraAlloc != 0);
  6866. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6867. }
  6868. }
  6869. void EmitCallInstrNoEvalComponents(
  6870. ParseNodeCall *pnodeCall,
  6871. BOOL fIsEval,
  6872. Js::RegSlot thisLocation,
  6873. Js::RegSlot callObjLocation,
  6874. uint32 actualArgCount,
  6875. ByteCodeGenerator *byteCodeGenerator,
  6876. FuncInfo *funcInfo,
  6877. Js::ProfileId callSiteId,
  6878. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6879. {
  6880. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6881. // it as part of doing the actual call.
  6882. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6883. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6884. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6885. switch (pnodeTarget->nop)
  6886. {
  6887. case knopDot:
  6888. {
  6889. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  6890. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6891. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6892. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6893. }
  6894. break;
  6895. case knopIndex:
  6896. {
  6897. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  6898. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6899. }
  6900. break;
  6901. case knopName:
  6902. {
  6903. if (callObjLocation != Js::Constants::NoRegister)
  6904. {
  6905. // We still have to get the property from its instance, so emit CallFld.
  6906. if (thisLocation != callObjLocation)
  6907. {
  6908. funcInfo->ReleaseTmpRegister(thisLocation);
  6909. }
  6910. funcInfo->ReleaseTmpRegister(callObjLocation);
  6911. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  6912. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6913. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6914. break;
  6915. }
  6916. }
  6917. // FALL THROUGH
  6918. default:
  6919. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6920. break;
  6921. }
  6922. }
  6923. void EmitCallInstr(
  6924. ParseNodeCall *pnodeCall,
  6925. BOOL fIsEval,
  6926. BOOL fHasNewTarget,
  6927. Js::RegSlot thisLocation,
  6928. Js::RegSlot callObjLocation,
  6929. uint32 actualArgCount,
  6930. ByteCodeGenerator *byteCodeGenerator,
  6931. FuncInfo *funcInfo,
  6932. Js::ProfileId callSiteId,
  6933. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6934. {
  6935. // Emit a call instruction. The call target has been fully evaluated already, so we always
  6936. // emit a CallI through the register that holds the target value.
  6937. // Note that we don't handle !fEvaluateComponents cases at this point.
  6938. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  6939. if (thisLocation != Js::Constants::NoRegister)
  6940. {
  6941. funcInfo->ReleaseTmpRegister(thisLocation);
  6942. }
  6943. if (callObjLocation != Js::Constants::NoRegister &&
  6944. callObjLocation != thisLocation)
  6945. {
  6946. funcInfo->ReleaseTmpRegister(callObjLocation);
  6947. }
  6948. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6949. }
  6950. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  6951. {
  6952. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  6953. argCount++; // include "this"
  6954. BOOL fSideEffectArgs = FALSE;
  6955. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  6956. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  6957. byteCodeGenerator->StartStatement(pnode);
  6958. // Start call, allocate out param space
  6959. funcInfo->StartRecordingOutArgs(argCount);
  6960. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6961. // them from side-effects.
  6962. if (fSideEffectArgs)
  6963. {
  6964. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  6965. }
  6966. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  6967. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  6968. {
  6969. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  6970. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  6971. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  6972. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  6973. Assert(argCount == 1);
  6974. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  6975. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  6976. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  6977. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  6978. }
  6979. else
  6980. {
  6981. uint32 actualArgCount = 0;
  6982. if (IsCallOfConstants(pnode))
  6983. {
  6984. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  6985. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  6986. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  6987. }
  6988. else
  6989. {
  6990. Js::OpCode op;
  6991. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  6992. {
  6993. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  6994. }
  6995. else
  6996. {
  6997. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  6998. }
  6999. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7000. // Only emit profiled argouts if we're going to profile this call.
  7001. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7002. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7003. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7004. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, pnode->AsParseNodeCall()->hasDestructuring, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  7005. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7006. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  7007. {
  7008. Assert(spreadIndices != nullptr);
  7009. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7010. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7011. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7012. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7013. spreadIndices, spreadIndicesSize, callSiteId);
  7014. }
  7015. else
  7016. {
  7017. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7018. (uint16)actualArgCount, callSiteId);
  7019. }
  7020. }
  7021. Assert(argCount == actualArgCount);
  7022. }
  7023. // End call, pop param space
  7024. funcInfo->EndRecordingOutArgs(argCount);
  7025. return;
  7026. }
  7027. void EmitCall(
  7028. ParseNodeCall * pnodeCall,
  7029. ByteCodeGenerator* byteCodeGenerator,
  7030. FuncInfo* funcInfo,
  7031. BOOL fReturnValue,
  7032. BOOL fEvaluateComponents,
  7033. Js::RegSlot overrideThisLocation,
  7034. Js::RegSlot newTargetLocation)
  7035. {
  7036. // If the call returns a float, we'll note this in the byte code.
  7037. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7038. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7039. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7040. BOOL fSideEffectArgs = FALSE;
  7041. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7042. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7043. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7044. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7045. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7046. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7047. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7048. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7049. // "new" path, since then our native array handling can kick in.
  7050. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7051. return;*/
  7052. }
  7053. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7054. BOOL fIsEval = pnodeCall->isEvalCall;
  7055. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7056. if (fIsEval)
  7057. {
  7058. Assert(!fHasNewTarget);
  7059. //
  7060. // "eval" takes the closure environment as an extra argument
  7061. // Pass the closure env only if some argument is passed
  7062. // For just eval(), don't pass the closure environment
  7063. //
  7064. if (argCount > 1)
  7065. {
  7066. argCount++;
  7067. }
  7068. }
  7069. else if (fHasNewTarget)
  7070. {
  7071. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7072. // This is similar to how eval passes an extra argument for the frame display and is
  7073. // used to support cases where we need to pass both 'this' and new.target as part of
  7074. // a function call.
  7075. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7076. argCount++;
  7077. }
  7078. // argCount indicates the total arguments count including the extra arguments.
  7079. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7080. if (argCount < (unsigned int)argSlotCount)
  7081. {
  7082. Js::Throw::OutOfMemory();
  7083. }
  7084. if (fReturnValue)
  7085. {
  7086. pnodeCall->isUsed = true;
  7087. }
  7088. //
  7089. // Set up the call.
  7090. //
  7091. bool releaseThisLocation = true;
  7092. // We already emit the call target for super calls in EmitSuperCall
  7093. if (!fIsSuperCall)
  7094. {
  7095. if (!fEvaluateComponents)
  7096. {
  7097. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7098. }
  7099. else
  7100. {
  7101. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7102. }
  7103. }
  7104. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7105. if (overrideThisLocation != Js::Constants::NoRegister)
  7106. {
  7107. thisLocation = overrideThisLocation;
  7108. releaseThisLocation = false;
  7109. }
  7110. // Evaluate the arguments (nothing mode-specific here).
  7111. // Start call, allocate out param space
  7112. // 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
  7113. funcInfo->StartRecordingOutArgs(argCount);
  7114. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7115. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7116. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7117. Js::AuxArray<uint32> *spreadIndices;
  7118. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, pnodeCall->hasDestructuring, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7119. if (!fEvaluateComponents)
  7120. {
  7121. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7122. }
  7123. else
  7124. {
  7125. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7126. }
  7127. // End call, pop param space
  7128. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7129. }
  7130. void EmitInvoke(
  7131. Js::RegSlot location,
  7132. Js::RegSlot callObjLocation,
  7133. Js::PropertyId propertyId,
  7134. ByteCodeGenerator* byteCodeGenerator,
  7135. FuncInfo* funcInfo)
  7136. {
  7137. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7138. funcInfo->StartRecordingOutArgs(1);
  7139. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7140. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7141. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7142. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7143. }
  7144. void EmitInvoke(
  7145. Js::RegSlot location,
  7146. Js::RegSlot callObjLocation,
  7147. Js::PropertyId propertyId,
  7148. ByteCodeGenerator* byteCodeGenerator,
  7149. FuncInfo* funcInfo,
  7150. Js::RegSlot arg1Location)
  7151. {
  7152. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7153. funcInfo->StartRecordingOutArgs(2);
  7154. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7155. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7156. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7157. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7158. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7159. }
  7160. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7161. {
  7162. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7163. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7164. bool isFncDecl = exprNode->nop == knopFncDecl;
  7165. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7166. if (isFncDecl)
  7167. {
  7168. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7169. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7170. }
  7171. Js::RegSlot computedNamePropertyKey = Js::Constants::NoRegister;
  7172. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7173. // which makes this bytecode too late to influence the function.name.
  7174. if (nameNode->nop == knopComputedName)
  7175. {
  7176. // Computed property name
  7177. // Transparently pass the name expr
  7178. // The Emit will replace this with a temp register if necessary to preserve the value.
  7179. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7180. computedNamePropertyKey = funcInfo->AcquireTmpRegister();
  7181. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo, computedNamePropertyKey);
  7182. if (isFncDecl && !exprNode->AsParseNodeFnc()->IsClassConstructor() && exprNode->AsParseNodeFnc()->pnodeName == nullptr)
  7183. {
  7184. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, computedNamePropertyKey);
  7185. }
  7186. }
  7187. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  7188. // but if we don't have any members then we don't need to load the prototype.
  7189. Assert(isClassMember == (isObjectEmpty != nullptr));
  7190. if (isClassMember && *isObjectEmpty)
  7191. {
  7192. *isObjectEmpty = false;
  7193. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  7194. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  7195. }
  7196. if (nameNode->nop == knopComputedName)
  7197. {
  7198. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7199. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7200. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7201. memberNode->nop == knopSetMember ?
  7202. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7203. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7204. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, computedNamePropertyKey, true);
  7205. funcInfo->ReleaseLoc(exprNode);
  7206. funcInfo->ReleaseLoc(nameNode);
  7207. funcInfo->ReleaseTmpRegister(computedNamePropertyKey);
  7208. return;
  7209. }
  7210. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7211. if (useStore)
  7212. {
  7213. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7214. }
  7215. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7216. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7217. if (Js::PropertyIds::name == propertyId
  7218. && exprNode->nop == knopFncDecl
  7219. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7220. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7221. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7222. {
  7223. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7224. nameFunc->SetIsStaticNameFunction(true);
  7225. }
  7226. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7227. {
  7228. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7229. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7230. {
  7231. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7232. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7233. }
  7234. else
  7235. {
  7236. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7237. Js::OpCode patchablePropertyOpCode;
  7238. if (useStore)
  7239. {
  7240. patchablePropertyOpCode = stFldOpCode;
  7241. }
  7242. else if (isClassMember)
  7243. {
  7244. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7245. }
  7246. else
  7247. {
  7248. patchablePropertyOpCode = Js::OpCode::InitFld;
  7249. }
  7250. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7251. }
  7252. }
  7253. else
  7254. {
  7255. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7256. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7257. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7258. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7259. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7260. }
  7261. funcInfo->ReleaseLoc(exprNode);
  7262. if (propertyId == Js::PropertyIds::valueOf)
  7263. {
  7264. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7265. }
  7266. else if (propertyId == Js::PropertyIds::toString)
  7267. {
  7268. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7269. }
  7270. }
  7271. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7272. {
  7273. if (memberList != nullptr)
  7274. {
  7275. while (memberList->nop == knopList)
  7276. {
  7277. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7278. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7279. memberList = memberList->AsParseNodeBin()->pnode2;
  7280. }
  7281. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7282. }
  7283. }
  7284. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7285. {
  7286. ParseNode *pmemberList = memberList;
  7287. unsigned int argCount = 0;
  7288. uint32 value;
  7289. Js::PropertyId propertyId;
  7290. //
  7291. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7292. // 2. Get the count of propertyIds
  7293. // 3. Create a propertyId array of size count
  7294. // 4. Put the propIds in the auxiliary area
  7295. // 5. Get the objectLiteralCacheId
  7296. // 6. Generate propId inits with values
  7297. //
  7298. // Handle propertyId collision
  7299. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7300. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7301. bool hasComputedName = false;
  7302. if (memberList != nullptr)
  7303. {
  7304. while (memberList->nop == knopList)
  7305. {
  7306. if (memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7307. {
  7308. hasComputedName = true;
  7309. break;
  7310. }
  7311. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7312. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7313. {
  7314. propertyIds->Item(propertyId);
  7315. }
  7316. memberList = memberList->AsParseNodeBin()->pnode2;
  7317. }
  7318. if (memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedName)
  7319. {
  7320. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7321. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7322. {
  7323. propertyIds->Item(propertyId);
  7324. }
  7325. }
  7326. }
  7327. argCount = propertyIds->Count();
  7328. memberList = pmemberList;
  7329. if ((memberList == nullptr) || (argCount == 0))
  7330. {
  7331. // Empty literal or numeric property only object literal
  7332. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7333. }
  7334. else
  7335. {
  7336. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7337. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7338. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7339. {
  7340. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7341. // or not, in case the bytecode is later run with __proto__ enabled.
  7342. propIds->has__proto__ = true;
  7343. }
  7344. unsigned int argIndex = 0;
  7345. while (memberList->nop == knopList)
  7346. {
  7347. if (memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7348. {
  7349. break;
  7350. }
  7351. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7352. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7353. {
  7354. propIds->elements[argIndex] = propertyId;
  7355. argIndex++;
  7356. }
  7357. memberList = memberList->AsParseNodeBin()->pnode2;
  7358. }
  7359. if (memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedName)
  7360. {
  7361. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7362. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7363. {
  7364. propIds->elements[argIndex] = propertyId;
  7365. argIndex++;
  7366. }
  7367. }
  7368. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7369. // Generate the opcode with propIds and cacheId
  7370. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7371. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7372. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7373. }
  7374. memberList = pmemberList;
  7375. bool useStore = false;
  7376. // Generate the actual assignment to those properties
  7377. if (memberList != nullptr)
  7378. {
  7379. while (memberList->nop == knopList)
  7380. {
  7381. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7382. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7383. {
  7384. useStore = true;
  7385. }
  7386. byteCodeGenerator->StartSubexpression(memberNode);
  7387. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7388. byteCodeGenerator->EndSubexpression(memberNode);
  7389. memberList = memberList->AsParseNodeBin()->pnode2;
  7390. }
  7391. byteCodeGenerator->StartSubexpression(memberList);
  7392. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7393. byteCodeGenerator->EndSubexpression(memberList);
  7394. }
  7395. }
  7396. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7397. {
  7398. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7399. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7400. // We only need to emit code for non-tagged string templates here.
  7401. if (!pnodeStrTemplate->isTaggedTemplate)
  7402. {
  7403. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7404. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7405. {
  7406. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7407. funcInfo->AcquireLoc(pnodeStrTemplate);
  7408. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7409. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7410. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7411. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7412. }
  7413. else
  7414. {
  7415. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7416. funcInfo->AcquireLoc(pnodeStrTemplate);
  7417. // First string must be a list node since we have substitutions.
  7418. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7419. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7420. // Emit the first string and load that into the pnode location.
  7421. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7422. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7423. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7424. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7425. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7426. ParseNode* stringNode;
  7427. ParseNode* expressionNode;
  7428. // Now append the substitution expressions and remaining string constants via normal add operator
  7429. // We will always have one more string constant than substitution expression
  7430. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7431. //
  7432. // strcon1 --- step 1 (above)
  7433. // expr1 \__ step 2
  7434. // strcon2 /
  7435. // expr2 \__ step 3
  7436. // strcon3 /
  7437. while (stringNodeList->nop == knopList)
  7438. {
  7439. // If the current head of the expression list is a list, fetch the node and walk the list.
  7440. if (expressionNodeList->nop == knopList)
  7441. {
  7442. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7443. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7444. }
  7445. else
  7446. {
  7447. // This is the last element of the expression list.
  7448. expressionNode = expressionNodeList;
  7449. }
  7450. // Emit the expression and append it to the string we're building.
  7451. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7452. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7453. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7454. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7455. funcInfo->ReleaseTmpRegister(toStringLocation);
  7456. funcInfo->ReleaseLoc(expressionNode);
  7457. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7458. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7459. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7460. if (stringNodeList->nop == knopList)
  7461. {
  7462. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7463. }
  7464. else
  7465. {
  7466. // This is the last element of the string literal list.
  7467. stringNode = stringNodeList;
  7468. }
  7469. // Emit the string node following the previous expression and append it to the string.
  7470. // This is either just some string in the list or it is the last string.
  7471. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7472. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7473. funcInfo->ReleaseLoc(stringNode);
  7474. }
  7475. }
  7476. }
  7477. }
  7478. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7479. {
  7480. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7481. uint argCount = pnode->AsParseNodeArrLit()->count;
  7482. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7483. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7484. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7485. if (arrayIntOpt)
  7486. {
  7487. int extraAlloc = 0, auxSize = 0;
  7488. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7489. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7490. {
  7491. ::Math::DefaultOverflowPolicy();
  7492. }
  7493. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7494. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7495. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7496. byteCodeGenerator->Writer()->Auxiliary(
  7497. Js::OpCode::NewScIntArray,
  7498. pnode->location,
  7499. ints,
  7500. auxSize,
  7501. argCount);
  7502. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7503. return;
  7504. }
  7505. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7506. if (arrayNumOpt)
  7507. {
  7508. int extraAlloc = 0, auxSize = 0;
  7509. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7510. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7511. {
  7512. ::Math::DefaultOverflowPolicy();
  7513. }
  7514. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7515. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7516. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7517. byteCodeGenerator->Writer()->Auxiliary(
  7518. Js::OpCode::NewScFltArray,
  7519. pnode->location,
  7520. doubles,
  7521. auxSize,
  7522. argCount);
  7523. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7524. return;
  7525. }
  7526. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7527. Assert(!arrayLitOpt || !nativeArrays);
  7528. Js::RegSlot spreadArrLoc = arrayLocation;
  7529. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7530. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7531. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7532. {
  7533. arrayLocation = funcInfo->AcquireTmpRegister();
  7534. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7535. }
  7536. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7537. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7538. arrayLocation,
  7539. argCount);
  7540. if (args != nullptr)
  7541. {
  7542. Js::OpCode opcode;
  7543. Js::RegSlot arrLoc;
  7544. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7545. {
  7546. opcode = Js::OpCode::StArrItemC_CI4;
  7547. arrLoc = arrayLocation;
  7548. }
  7549. else if (arrayLitOpt)
  7550. {
  7551. opcode = Js::OpCode::StArrSegItem_A;
  7552. arrLoc = funcInfo->AcquireTmpRegister();
  7553. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7554. }
  7555. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7556. {
  7557. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7558. // should be done relative to the array header to keep it alive (instead of the array segment).
  7559. opcode = Js::OpCode::StArrInlineItem_CI4;
  7560. arrLoc = arrayLocation;
  7561. }
  7562. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7563. {
  7564. opcode = Js::OpCode::StArrSegItem_CI4;
  7565. arrLoc = funcInfo->AcquireTmpRegister();
  7566. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7567. }
  7568. else
  7569. {
  7570. opcode = Js::OpCode::StArrItemI_CI4;
  7571. arrLoc = arrayLocation;
  7572. }
  7573. if (arrayLitOpt)
  7574. {
  7575. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  7576. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  7577. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7578. // Generate the opcode with vars
  7579. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  7580. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  7581. }
  7582. else
  7583. {
  7584. uint i = 0;
  7585. unsigned spreadIndex = 0;
  7586. Js::RegSlot rhsLocation;
  7587. while (args->nop == knopList)
  7588. {
  7589. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  7590. {
  7591. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7592. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  7593. Js::RegSlot regVal = rhsLocation;
  7594. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7595. {
  7596. AnalysisAssert(spreadIndices);
  7597. regVal = funcInfo->AcquireTmpRegister();
  7598. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7599. spreadIndices->elements[spreadIndex++] = i;
  7600. }
  7601. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7602. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7603. {
  7604. funcInfo->ReleaseTmpRegister(regVal);
  7605. }
  7606. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  7607. }
  7608. args = args->AsParseNodeBin()->pnode2;
  7609. i++;
  7610. }
  7611. if (args->nop != knopEmpty)
  7612. {
  7613. Emit(args, byteCodeGenerator, funcInfo, false);
  7614. rhsLocation = args->location;
  7615. Js::RegSlot regVal = rhsLocation;
  7616. if (args->nop == knopEllipsis)
  7617. {
  7618. regVal = funcInfo->AcquireTmpRegister();
  7619. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7620. AnalysisAssert(spreadIndices);
  7621. spreadIndices->elements[spreadIndex] = i;
  7622. }
  7623. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7624. if (args->nop == knopEllipsis)
  7625. {
  7626. funcInfo->ReleaseTmpRegister(regVal);
  7627. }
  7628. funcInfo->ReleaseLoc(args);
  7629. i++;
  7630. }
  7631. Assert(i <= argCount);
  7632. }
  7633. if (arrLoc != arrayLocation)
  7634. {
  7635. funcInfo->ReleaseTmpRegister(arrLoc);
  7636. }
  7637. }
  7638. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7639. {
  7640. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  7641. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7642. funcInfo->ReleaseTmpRegister(arrayLocation);
  7643. }
  7644. }
  7645. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7646. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7647. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7648. // with special case for single-branch style.
  7649. void EmitBooleanExpression(
  7650. _In_ ParseNode* expr,
  7651. Js::ByteCodeLabel trueLabel,
  7652. Js::ByteCodeLabel falseLabel,
  7653. _In_ ByteCodeGenerator* byteCodeGenerator,
  7654. _In_ FuncInfo* funcInfo,
  7655. bool trueFallthrough,
  7656. bool falseFallthrough)
  7657. {
  7658. Assert(!trueFallthrough || !falseFallthrough);
  7659. byteCodeGenerator->StartStatement(expr);
  7660. switch (expr->nop)
  7661. {
  7662. case knopLogOr:
  7663. {
  7664. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7665. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  7666. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7667. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7668. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7669. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7670. break;
  7671. }
  7672. case knopLogAnd:
  7673. {
  7674. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7675. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  7676. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7677. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7678. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7679. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7680. break;
  7681. }
  7682. case knopLogNot:
  7683. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  7684. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7685. break;
  7686. case knopEq:
  7687. case knopEqv:
  7688. case knopNEqv:
  7689. case knopNe:
  7690. case knopLt:
  7691. case knopLe:
  7692. case knopGe:
  7693. case knopGt:
  7694. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7695. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7696. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7697. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  7698. expr->AsParseNodeBin()->pnode2->location);
  7699. if (!falseFallthrough)
  7700. {
  7701. byteCodeGenerator->Writer()->Br(falseLabel);
  7702. }
  7703. break;
  7704. case knopTrue:
  7705. if (!trueFallthrough)
  7706. {
  7707. byteCodeGenerator->Writer()->Br(trueLabel);
  7708. }
  7709. break;
  7710. case knopFalse:
  7711. if (!falseFallthrough)
  7712. {
  7713. byteCodeGenerator->Writer()->Br(falseLabel);
  7714. }
  7715. break;
  7716. default:
  7717. // Note: we usually release the temp assigned to a node after we Emit it.
  7718. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7719. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7720. Emit(expr, byteCodeGenerator, funcInfo, false);
  7721. if (trueFallthrough)
  7722. {
  7723. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7724. }
  7725. else
  7726. {
  7727. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7728. if (!falseFallthrough)
  7729. {
  7730. byteCodeGenerator->Writer()->Br(falseLabel);
  7731. }
  7732. }
  7733. break;
  7734. }
  7735. byteCodeGenerator->EndStatement(expr);
  7736. }
  7737. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  7738. ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7739. {
  7740. switch (expr->nop)
  7741. {
  7742. case knopLogOr:
  7743. {
  7744. byteCodeGenerator->StartStatement(expr);
  7745. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7746. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, byteCodeGenerator, funcInfo);
  7747. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7748. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7749. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7750. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7751. byteCodeGenerator->EndStatement(expr);
  7752. break;
  7753. }
  7754. case knopLogAnd:
  7755. {
  7756. byteCodeGenerator->StartStatement(expr);
  7757. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7758. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, byteCodeGenerator, funcInfo);
  7759. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7760. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7761. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7762. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7763. byteCodeGenerator->EndStatement(expr);
  7764. break;
  7765. }
  7766. case knopLogNot:
  7767. {
  7768. byteCodeGenerator->StartStatement(expr);
  7769. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  7770. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  7771. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  7772. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  7773. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  7774. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7775. byteCodeGenerator->Writer()->Br(trueLabel);
  7776. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  7777. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7778. if (!falsefallthrough)
  7779. {
  7780. byteCodeGenerator->Writer()->Br(falseLabel);
  7781. }
  7782. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7783. byteCodeGenerator->EndStatement(expr);
  7784. break;
  7785. }
  7786. case knopEq:
  7787. case knopEqv:
  7788. case knopNEqv:
  7789. case knopNe:
  7790. case knopLt:
  7791. case knopLe:
  7792. case knopGe:
  7793. case knopGt:
  7794. byteCodeGenerator->StartStatement(expr);
  7795. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7796. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7797. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7798. funcInfo->AcquireLoc(expr);
  7799. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  7800. expr->AsParseNodeBin()->pnode2->location);
  7801. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7802. // The inliner likes small bytecode
  7803. if (!(truefallthrough || falsefallthrough))
  7804. {
  7805. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7806. byteCodeGenerator->Writer()->Br(falseLabel);
  7807. }
  7808. else if (truefallthrough && !falsefallthrough) {
  7809. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7810. }
  7811. else if (falsefallthrough && !truefallthrough) {
  7812. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7813. }
  7814. byteCodeGenerator->EndStatement(expr);
  7815. break;
  7816. case knopTrue:
  7817. byteCodeGenerator->StartStatement(expr);
  7818. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7819. if (!truefallthrough)
  7820. {
  7821. byteCodeGenerator->Writer()->Br(trueLabel);
  7822. }
  7823. byteCodeGenerator->EndStatement(expr);
  7824. break;
  7825. case knopFalse:
  7826. byteCodeGenerator->StartStatement(expr);
  7827. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7828. if (!falsefallthrough)
  7829. {
  7830. byteCodeGenerator->Writer()->Br(falseLabel);
  7831. }
  7832. byteCodeGenerator->EndStatement(expr);
  7833. break;
  7834. default:
  7835. // Note: we usually release the temp assigned to a node after we Emit it.
  7836. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7837. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7838. // For diagnostics purposes, register the name and dot to the statement list.
  7839. if (expr->nop == knopName || expr->nop == knopDot)
  7840. {
  7841. byteCodeGenerator->StartStatement(expr);
  7842. Emit(expr, byteCodeGenerator, funcInfo, false);
  7843. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7844. // The inliner likes small bytecode
  7845. if (!(truefallthrough || falsefallthrough))
  7846. {
  7847. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7848. byteCodeGenerator->Writer()->Br(falseLabel);
  7849. }
  7850. else if (truefallthrough && !falsefallthrough) {
  7851. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7852. }
  7853. else if (falsefallthrough && !truefallthrough) {
  7854. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7855. }
  7856. byteCodeGenerator->EndStatement(expr);
  7857. }
  7858. else
  7859. {
  7860. Emit(expr, byteCodeGenerator, funcInfo, false);
  7861. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7862. // The inliner likes small bytecode
  7863. if (!(truefallthrough || falsefallthrough))
  7864. {
  7865. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7866. byteCodeGenerator->Writer()->Br(falseLabel);
  7867. }
  7868. else if (truefallthrough && !falsefallthrough) {
  7869. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7870. }
  7871. else if (falsefallthrough && !truefallthrough) {
  7872. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7873. }
  7874. }
  7875. break;
  7876. }
  7877. }
  7878. // used by while and for loops
  7879. void EmitLoop(
  7880. ParseNodeLoop *loopNode,
  7881. ParseNode *cond,
  7882. ParseNode *body,
  7883. ParseNode *incr,
  7884. ByteCodeGenerator *byteCodeGenerator,
  7885. FuncInfo *funcInfo,
  7886. BOOL fReturnValue,
  7887. BOOL doWhile = FALSE,
  7888. ParseNodeBlock *forLoopBlock = nullptr)
  7889. {
  7890. // Need to increment loop count whether we are going to profile or not for HasLoop()
  7891. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7892. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7893. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7894. loopNode->loopId = loopId;
  7895. if (doWhile)
  7896. {
  7897. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7898. funcInfo->ReleaseLoc(body);
  7899. if (loopNode->emitLabels)
  7900. {
  7901. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  7902. }
  7903. if (!ByteCodeGenerator::IsFalse(cond) ||
  7904. byteCodeGenerator->IsInDebugMode())
  7905. {
  7906. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  7907. }
  7908. funcInfo->ReleaseLoc(cond);
  7909. }
  7910. else
  7911. {
  7912. if (cond)
  7913. {
  7914. if (!(cond->nop == knopInt &&
  7915. cond->AsParseNodeInt()->lw != 0))
  7916. {
  7917. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  7918. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  7919. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  7920. }
  7921. funcInfo->ReleaseLoc(cond);
  7922. }
  7923. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7924. funcInfo->ReleaseLoc(body);
  7925. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7926. forLoopBlock != nullptr)
  7927. {
  7928. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  7929. }
  7930. if (loopNode->emitLabels)
  7931. {
  7932. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  7933. }
  7934. if (incr != nullptr)
  7935. {
  7936. Emit(incr, byteCodeGenerator, funcInfo, false);
  7937. funcInfo->ReleaseLoc(incr);
  7938. }
  7939. byteCodeGenerator->Writer()->Br(loopEntrance);
  7940. }
  7941. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7942. if (loopNode->emitLabels)
  7943. {
  7944. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  7945. }
  7946. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7947. }
  7948. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeLoop* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  7949. {
  7950. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  7951. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  7952. // emit branch around original
  7953. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  7954. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  7955. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  7956. // emit original
  7957. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  7958. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  7959. // clear temporary registers since inverted loop may share nodes with
  7960. // emitted original loop
  7961. VisitClearTmpRegs(outerLoop, this, funcInfo);
  7962. // emit branch around inverted
  7963. this->m_writer.Br(afterInvertedLoop);
  7964. this->m_writer.MarkLabel(invertedLoopLabel);
  7965. // Emit a zero trip test for the original outer-loop
  7966. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  7967. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  7968. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  7969. this->m_writer.MarkLabel(zeroTrip);
  7970. funcInfo->ReleaseLoc(testNode);
  7971. // emit inverted
  7972. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  7973. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  7974. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  7975. invertedLoop->pnodeIncr, this, funcInfo, false);
  7976. this->m_writer.MarkLabel(afterInvertedLoop);
  7977. }
  7978. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7979. {
  7980. // get iterator object from the iterable
  7981. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  7982. // throw TypeError if the result is not an object
  7983. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7984. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  7985. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7986. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7987. }
  7988. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7989. {
  7990. // invoke next() on the iterator
  7991. if (nextInputLocation == Js::Constants::NoRegister)
  7992. {
  7993. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  7994. }
  7995. else
  7996. {
  7997. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  7998. }
  7999. // throw TypeError if the result is not an object
  8000. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8001. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  8002. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8003. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8004. }
  8005. // Generating
  8006. // if (hasReturnFunction) {
  8007. // value = Call Retrun;
  8008. // if (value != Object)
  8009. // throw TypeError;
  8010. // }
  8011. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8012. {
  8013. Js::RegSlot returnLocation = funcInfo->AcquireTmpRegister();
  8014. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8015. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8016. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorLocation, Js::PropertyIds::return_, false, false);
  8017. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, returnLocation, iteratorLocation, cacheId);
  8018. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, noReturn, returnLocation, funcInfo->undefinedConstantRegister);
  8019. EmitInvoke(returnLocation, iteratorLocation, Js::PropertyIds::return_, byteCodeGenerator, funcInfo);
  8020. // throw TypeError if the result is not an Object
  8021. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, returnLocation);
  8022. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8023. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8024. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8025. funcInfo->ReleaseTmpRegister(returnLocation);
  8026. }
  8027. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8028. {
  8029. // get the iterator result's "done" property
  8030. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  8031. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  8032. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  8033. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  8034. }
  8035. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8036. {
  8037. // get the iterator result's "value" property
  8038. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  8039. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  8040. }
  8041. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8042. Js::ByteCodeLabel loopEntrance,
  8043. Js::ByteCodeLabel continuePastLoop,
  8044. ByteCodeGenerator *byteCodeGenerator,
  8045. FuncInfo *funcInfo,
  8046. BOOL fReturnValue)
  8047. {
  8048. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8049. loopNode->pnodeLval->nop != knopLetDecl &&
  8050. loopNode->pnodeLval->nop != knopConstDecl)
  8051. {
  8052. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8053. }
  8054. else
  8055. {
  8056. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8057. sym->SetNeedDeclaration(false);
  8058. }
  8059. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8060. {
  8061. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8062. }
  8063. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8064. // The StartStatement is already done in the caller of this function.
  8065. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8066. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8067. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8068. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8069. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8070. {
  8071. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8072. }
  8073. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8074. if (loopNode->emitLabels)
  8075. {
  8076. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8077. }
  8078. byteCodeGenerator->Writer()->Br(loopEntrance);
  8079. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8080. if (loopNode->emitLabels)
  8081. {
  8082. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8083. }
  8084. }
  8085. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8086. Js::ByteCodeLabel loopEntrance,
  8087. Js::ByteCodeLabel continuePastLoop,
  8088. ByteCodeGenerator *byteCodeGenerator,
  8089. FuncInfo *funcInfo,
  8090. BOOL fReturnValue)
  8091. {
  8092. Assert(loopNode->nop == knopForIn);
  8093. Assert(loopNode->location == Js::Constants::NoRegister);
  8094. // Grab registers for the enumerator and for the current enumerated item.
  8095. // The enumerator register will be released after this call returns.
  8096. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8097. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8098. // get enumerator from the collection
  8099. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8100. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8101. byteCodeGenerator->EndStatement(loopNode);
  8102. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8103. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8104. loopNode->loopId = loopId;
  8105. // The EndStatement will happen in the EmitForInOfLoopBody function
  8106. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8107. // branch past loop when MoveAndGetNext returns nullptr
  8108. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8109. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8110. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8111. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8112. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8113. {
  8114. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8115. }
  8116. }
  8117. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8118. {
  8119. bool isForIn = (loopNode->nop == knopForIn);
  8120. Assert(isForIn || loopNode->nop == knopForOf);
  8121. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8122. byteCodeGenerator->StartStatement(loopNode);
  8123. if (!isForIn)
  8124. {
  8125. funcInfo->AcquireLoc(loopNode);
  8126. }
  8127. // Record the branch bytecode offset.
  8128. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8129. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8130. // otherwise use offset of next stmt.
  8131. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8132. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8133. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8134. // See WinBlue 231880 for details.
  8135. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8136. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8137. loopNode->pnodeBlock->HasBlockScopedContent())
  8138. {
  8139. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8140. }
  8141. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8142. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8143. if (loopNode->pnodeLval->nop == knopVarDecl)
  8144. {
  8145. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8146. }
  8147. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8148. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8149. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8150. {
  8151. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8152. if (loopNode->pnodeBlock->scope != nullptr)
  8153. {
  8154. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8155. sym->SetIsTrackedForDebugger(false);
  8156. });
  8157. }
  8158. }
  8159. if (isForIn)
  8160. {
  8161. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8162. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8163. {
  8164. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8165. }
  8166. return;
  8167. }
  8168. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8169. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8170. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8171. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8172. Js::RegSlot regException = Js::Constants::NoRegister;
  8173. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8174. // These two temp variables store the information of return function to be called or not.
  8175. // 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
  8176. // to be called on abrupt loop break.
  8177. // Why two variables? since these are temps and JIT does like not flow if single variable is used in multiple blocks.
  8178. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  8179. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  8180. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8181. if (isCoroutine)
  8182. {
  8183. regException = funcInfo->AcquireTmpRegister();
  8184. regOffset = funcInfo->AcquireTmpRegister();
  8185. }
  8186. // Grab registers for the enumerator and for the current enumerated item.
  8187. // The enumerator register will be released after this call returns.
  8188. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8189. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8190. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8191. // to the profiler and JIT.
  8192. byteCodeGenerator->SetHasFinally(true);
  8193. byteCodeGenerator->SetHasTry(true);
  8194. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8195. // do a ToObject on the collection
  8196. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8197. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8198. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8199. funcInfo->ReleaseTmpRegister(tmpObj);
  8200. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8201. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8202. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8203. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8204. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8205. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8206. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  8207. if (isCoroutine)
  8208. {
  8209. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8210. tryRecForTryFinally.reg1 = regException;
  8211. tryRecForTryFinally.reg2 = regOffset;
  8212. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  8213. }
  8214. else
  8215. {
  8216. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8217. }
  8218. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8219. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  8220. if (isCoroutine)
  8221. {
  8222. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  8223. }
  8224. byteCodeGenerator->EndStatement(loopNode);
  8225. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8226. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8227. loopNode->loopId = loopId;
  8228. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8229. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8230. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8231. EmitIteratorNext(loopNode->itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  8232. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8233. EmitIteratorComplete(doneLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8234. // branch past loop if the result's done property is truthy
  8235. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8236. funcInfo->ReleaseTmpRegister(doneLocation);
  8237. // otherwise put result's value property in itemLocation
  8238. EmitIteratorValue(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8239. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8240. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8241. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8242. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8243. EmitCatchAndFinallyBlocks(catchLabel,
  8244. finallyLabel,
  8245. loopNode->location,
  8246. shouldCallReturnFunctionLocation,
  8247. shouldCallReturnFunctionLocationFinally,
  8248. regException,
  8249. regOffset,
  8250. byteCodeGenerator,
  8251. funcInfo);
  8252. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8253. {
  8254. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8255. }
  8256. }
  8257. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8258. {
  8259. funcInfo->AcquireLoc(pnode);
  8260. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8261. if (args == nullptr)
  8262. {
  8263. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8264. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8265. pnode->location,
  8266. ByteCodeGenerator::DefaultArraySize);
  8267. }
  8268. else
  8269. {
  8270. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8271. }
  8272. }
  8273. void EmitJumpCleanup(ParseNodeStmt *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  8274. {
  8275. for (; pnode != pnodeTarget; pnode = pnode->pnodeOuter)
  8276. {
  8277. switch (pnode->nop)
  8278. {
  8279. case knopTry:
  8280. case knopCatch:
  8281. case knopFinally:
  8282. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8283. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  8284. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  8285. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8286. break;
  8287. case knopForOf:
  8288. #if ENABLE_PROFILE_INFO
  8289. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8290. {
  8291. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8292. }
  8293. #endif
  8294. // The ForOf loop code is wrapped around try..catch..finally - Forcing couple Leave bytecode over here
  8295. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8296. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8297. break;
  8298. #if ENABLE_PROFILE_INFO
  8299. case knopWhile:
  8300. case knopDoWhile:
  8301. case knopFor:
  8302. case knopForIn:
  8303. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8304. {
  8305. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8306. }
  8307. break;
  8308. #endif
  8309. }
  8310. }
  8311. }
  8312. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, Js::RegSlot computedPropertyLocation)
  8313. {
  8314. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8315. if (MayHaveSideEffectOnNode(pnode1, pnode2))
  8316. {
  8317. SaveOpndValue(pnode1, funcInfo);
  8318. }
  8319. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8320. if (pnode1->nop == knopComputedName && computedPropertyLocation != Js::Constants::NoRegister)
  8321. {
  8322. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Prop, computedPropertyLocation, pnode1->location);
  8323. }
  8324. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, computedPropertyLocation);
  8325. }
  8326. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8327. {
  8328. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8329. switch (pnode1->nop)
  8330. {
  8331. case knopName:
  8332. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2))
  8333. {
  8334. // Given x op y, y may kill x, so stash x.
  8335. // Note that this only matters if we're loading x prior to the op.
  8336. SaveOpndValue(pnode1, funcInfo);
  8337. }
  8338. break;
  8339. case knopDot:
  8340. if (fLoadLhs)
  8341. {
  8342. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8343. funcInfo->AcquireLoc(pnode1);
  8344. }
  8345. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2))
  8346. {
  8347. // Given x.y op z, z may kill x, so stash x away.
  8348. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8349. }
  8350. break;
  8351. case knopIndex:
  8352. if (fLoadLhs)
  8353. {
  8354. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8355. funcInfo->AcquireLoc(pnode1);
  8356. }
  8357. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2) ||
  8358. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2))
  8359. {
  8360. // Given x[y] op z, y or z may kill x, so stash x away.
  8361. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8362. }
  8363. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2))
  8364. {
  8365. // Given x[y] op z, z may kill y, so stash y away.
  8366. // But make sure that x gets a register before y.
  8367. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8368. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8369. }
  8370. break;
  8371. }
  8372. if (fLoadLhs)
  8373. {
  8374. // Emit code to load the value of the LHS.
  8375. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8376. }
  8377. else
  8378. {
  8379. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8380. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8381. }
  8382. // Evaluate the RHS.
  8383. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8384. }
  8385. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8386. {
  8387. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8388. if (location != Js::Constants::NoRegister)
  8389. {
  8390. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8391. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8392. }
  8393. }
  8394. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8395. {
  8396. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8397. // if necessary.
  8398. if (sym != nullptr &&
  8399. !sym->GetIsModuleExportStorage() &&
  8400. sym->GetNeedDeclaration() &&
  8401. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8402. sym->GetScope()->GetFunc() == funcInfo)
  8403. {
  8404. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8405. }
  8406. }
  8407. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8408. {
  8409. byteCodeGenerator->StartStatement(pnode);
  8410. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8411. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8412. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8413. funcInfo->AcquireLoc(pnode);
  8414. byteCodeGenerator->Writer()->Reg3(opcode,
  8415. pnode->location,
  8416. pnode->AsParseNodeBin()->pnode1->location,
  8417. pnode->AsParseNodeBin()->pnode2->location);
  8418. byteCodeGenerator->EndStatement(pnode);
  8419. }
  8420. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  8421. {
  8422. Assert(pnodeAdd->nop == knopAdd);
  8423. Assert(pnodeAdd->CanFlattenConcatExpr());
  8424. bool doConcatString = false;
  8425. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8426. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8427. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8428. while (true)
  8429. {
  8430. if (!pnode->CanFlattenConcatExpr())
  8431. {
  8432. concatOpnds.Append(pnode);
  8433. }
  8434. else if (pnode->nop == knopStr)
  8435. {
  8436. concatOpnds.Append(pnode);
  8437. // Detect if there are any string larger then the append size limit.
  8438. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8439. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8440. }
  8441. else
  8442. {
  8443. Assert(pnode->nop == knopAdd);
  8444. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8445. pnode = pnode->AsParseNodeBin()->pnode1;
  8446. continue;
  8447. }
  8448. if (pnodeStack.Empty())
  8449. {
  8450. break;
  8451. }
  8452. pnode = pnodeStack.Head();
  8453. pnodeStack.RemoveHead();
  8454. }
  8455. return doConcatString;
  8456. }
  8457. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8458. {
  8459. byteCodeGenerator->StartStatement(pnode);
  8460. if (MayHaveSideEffectOnNode(pnode1, pnode2) || MayHaveSideEffectOnNode(pnode1, pnode3))
  8461. {
  8462. SaveOpndValue(pnode1, funcInfo);
  8463. }
  8464. if (MayHaveSideEffectOnNode(pnode2, pnode3))
  8465. {
  8466. SaveOpndValue(pnode2, funcInfo);
  8467. }
  8468. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8469. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8470. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8471. funcInfo->ReleaseLoc(pnode3);
  8472. funcInfo->ReleaseLoc(pnode2);
  8473. funcInfo->ReleaseLoc(pnode1);
  8474. funcInfo->AcquireLoc(pnode);
  8475. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8476. pnode->location,
  8477. pnode1->location,
  8478. pnode2->location,
  8479. pnode3->location);
  8480. byteCodeGenerator->EndStatement(pnode);
  8481. }
  8482. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8483. {
  8484. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8485. funcInfo->ReleaseLoc(pnode2);
  8486. funcInfo->ReleaseLoc(pnode1);
  8487. funcInfo->AcquireLoc(pnode);
  8488. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8489. pnode->location,
  8490. pnode1->location,
  8491. pnode2->location,
  8492. count);
  8493. }
  8494. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8495. {
  8496. Assert(pnode->nop == knopAdd);
  8497. if (pnode->CanFlattenConcatExpr())
  8498. {
  8499. // We should only have a string concat if the feature is on.
  8500. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8501. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8502. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8503. if (doConcatString)
  8504. {
  8505. uint concatCount = concatOpnds.Count();
  8506. Assert(concatCount >= 2);
  8507. // Don't do concatN if the number is too high
  8508. // CONSIDER: although we could have done multiple ConcatNs
  8509. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8510. {
  8511. #if DBG
  8512. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  8513. #endif
  8514. ParseNode * pnode1 = concatOpnds.Head();
  8515. concatOpnds.RemoveHead();
  8516. ParseNode * pnode2 = concatOpnds.Head();
  8517. concatOpnds.RemoveHead();
  8518. if (concatCount == 3)
  8519. {
  8520. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  8521. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8522. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8523. byteCodeGenerator->Writer()->ByteCodeDataSize());
  8524. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  8525. return;
  8526. }
  8527. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  8528. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8529. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8530. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  8531. byteCodeGenerator->StartStatement(pnode);
  8532. funcInfo->AcquireLoc(pnode);
  8533. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  8534. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  8535. uint i = 2;
  8536. do
  8537. {
  8538. ParseNode * currNode = concatOpnds.Head();
  8539. concatOpnds.RemoveHead();
  8540. ParseNode * currNode2 = concatOpnds.Head();
  8541. concatOpnds.RemoveHead();
  8542. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8543. funcInfo->ReleaseLoc(currNode2);
  8544. funcInfo->ReleaseLoc(currNode);
  8545. byteCodeGenerator->Writer()->Reg3B1(
  8546. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  8547. i += 2;
  8548. } while (concatOpnds.Count() > 1);
  8549. if (!concatOpnds.Empty())
  8550. {
  8551. ParseNode * currNode = concatOpnds.Head();
  8552. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8553. funcInfo->ReleaseLoc(currNode);
  8554. byteCodeGenerator->Writer()->Reg2B1(
  8555. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  8556. i++;
  8557. }
  8558. Assert(concatCount == i);
  8559. byteCodeGenerator->EndStatement(pnode);
  8560. return;
  8561. }
  8562. }
  8563. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  8564. byteCodeGenerator->StartStatement(pnode);
  8565. ParseNode * currNode = concatOpnds.Head();
  8566. concatOpnds.RemoveHead();
  8567. ParseNode * currNode2 = concatOpnds.Head();
  8568. concatOpnds.RemoveHead();
  8569. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8570. funcInfo->ReleaseLoc(currNode2);
  8571. funcInfo->ReleaseLoc(currNode);
  8572. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  8573. byteCodeGenerator->Writer()->Reg3(
  8574. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  8575. while (!concatOpnds.Empty())
  8576. {
  8577. currNode = concatOpnds.Head();
  8578. concatOpnds.RemoveHead();
  8579. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8580. funcInfo->ReleaseLoc(currNode);
  8581. byteCodeGenerator->Writer()->Reg3(
  8582. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  8583. }
  8584. byteCodeGenerator->EndStatement(pnode);
  8585. }
  8586. else
  8587. {
  8588. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  8589. }
  8590. }
  8591. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  8592. {
  8593. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  8594. {
  8595. switch (node->op)
  8596. {
  8597. case Js::OpCode::TryFinallyWithYield:
  8598. this->Writer()->Empty(Js::OpCode::LeaveNull);
  8599. break;
  8600. case Js::OpCode::TryCatch:
  8601. case Js::OpCode::ResumeFinally:
  8602. case Js::OpCode::ResumeCatch:
  8603. this->Writer()->Empty(Js::OpCode::Leave);
  8604. break;
  8605. default:
  8606. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8607. break;
  8608. }
  8609. }
  8610. }
  8611. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8612. {
  8613. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8614. {
  8615. switch (node->op)
  8616. {
  8617. case Js::OpCode::TryCatch:
  8618. this->Writer()->Br(node->op, node->label);
  8619. break;
  8620. case Js::OpCode::TryFinallyWithYield:
  8621. case Js::OpCode::ResumeFinally:
  8622. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8623. break;
  8624. case Js::OpCode::ResumeCatch:
  8625. this->Writer()->Empty(node->op);
  8626. break;
  8627. default:
  8628. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8629. break;
  8630. }
  8631. }
  8632. }
  8633. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator)
  8634. {
  8635. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8636. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8637. if (yieldStarIterator == Js::Constants::NoRegister)
  8638. {
  8639. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8640. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8641. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8642. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8643. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8644. }
  8645. else
  8646. {
  8647. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8648. }
  8649. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8650. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8651. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8652. if (yieldStarIterator == Js::Constants::NoRegister)
  8653. {
  8654. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8655. }
  8656. else
  8657. {
  8658. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8659. }
  8660. }
  8661. void EmitYieldStar(ParseNodeUni* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8662. {
  8663. funcInfo->AcquireLoc(yieldStarNode);
  8664. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8665. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8666. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8667. // Evaluate operand
  8668. Emit(yieldStarNode->pnode1, byteCodeGenerator, funcInfo, false);
  8669. funcInfo->ReleaseLoc(yieldStarNode->pnode1);
  8670. EmitGetIterator(iteratorLocation, yieldStarNode->pnode1->location, byteCodeGenerator, funcInfo);
  8671. // Call the iterator's next()
  8672. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8673. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8674. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8675. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8676. // remember the loopId like the loop statements do.
  8677. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8678. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8679. // branch past the loop if the done property is truthy
  8680. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8681. funcInfo->ReleaseTmpRegister(doneLocation);
  8682. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8683. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8684. byteCodeGenerator->Writer()->Br(loopEntrance);
  8685. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8686. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8687. // Put the iterator result's value in yieldStarNode->location.
  8688. // It will be used as the result value of the yield* operator expression.
  8689. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8690. }
  8691. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8692. {
  8693. if (isSymGlobalAndSingleAssignment)
  8694. {
  8695. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8696. }
  8697. }
  8698. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8699. {
  8700. if (isSymGlobalAndSingleAssignment)
  8701. {
  8702. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8703. }
  8704. }
  8705. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8706. {
  8707. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8708. {
  8709. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8710. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8711. }
  8712. }
  8713. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8714. {
  8715. Assert(objNode->nop == knopObject);
  8716. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  8717. while (memberList != nullptr)
  8718. {
  8719. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  8720. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  8721. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  8722. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8723. {
  8724. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  8725. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8726. }
  8727. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  8728. }
  8729. }
  8730. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8731. {
  8732. Assert(knopDotNode->nop == knopDot);
  8733. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  8734. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  8735. bool isSymGlobalAndSingleAssignment = false;
  8736. if (objectNode->nop == knopName)
  8737. {
  8738. if (ByteCodeGenerator::IsThis(objectNode))
  8739. {
  8740. // Assume 'this' always refer to GlobalObject
  8741. // Cases like "this.a = "
  8742. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  8743. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8744. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8745. }
  8746. else
  8747. {
  8748. Symbol * sym = objectNode->AsParseNodeName()->sym;
  8749. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  8750. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8751. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8752. }
  8753. }
  8754. }
  8755. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8756. {
  8757. // Track the Global Int Constant properties' assignments here.
  8758. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8759. if (nodeType & fnopAsg)
  8760. {
  8761. if (nodeType & fnopBin)
  8762. {
  8763. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  8764. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  8765. Assert(lhs && rhs);
  8766. // Don't track other than integers and objects with member nodes.
  8767. if (rhs->nop == knopObject)
  8768. {
  8769. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8770. }
  8771. else if (rhs->nop != knopInt &&
  8772. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  8773. {
  8774. return;
  8775. }
  8776. if (lhs->nop == knopName)
  8777. {
  8778. // Handle "a = <Integer>" cases here
  8779. Symbol * sym = lhs->AsParseNodeName()->sym;
  8780. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8781. }
  8782. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8783. {
  8784. // Cases like "obj.a = <Integer>"
  8785. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8786. }
  8787. }
  8788. else if (nodeType & fnopUni)
  8789. {
  8790. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  8791. if (lhs->nop == knopName)
  8792. {
  8793. // Cases like "a++"
  8794. Symbol * sym = lhs->AsParseNodeName()->sym;
  8795. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8796. }
  8797. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8798. {
  8799. // Cases like "obj.a++"
  8800. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8801. }
  8802. }
  8803. }
  8804. }
  8805. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, Js::RegSlot bindingNameLocation, bool isTopLevel)
  8806. {
  8807. if (pnode == nullptr)
  8808. {
  8809. return;
  8810. }
  8811. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8812. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8813. // printNop(pnode->nop);
  8814. switch (pnode->nop)
  8815. {
  8816. case knopList:
  8817. EmitList(pnode, byteCodeGenerator, funcInfo);
  8818. break;
  8819. case knopInt:
  8820. // currently, these are loaded at the top
  8821. break;
  8822. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8823. case knopFlt:
  8824. // currently, these are loaded at the top
  8825. break;
  8826. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8827. case knopStr:
  8828. // TODO: protocol for combining string constants
  8829. break;
  8830. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8831. case knopRegExp:
  8832. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  8833. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  8834. break;
  8835. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8836. case knopNull:
  8837. // enregistered
  8838. break;
  8839. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  8840. case knopFalse:
  8841. // enregistered
  8842. break;
  8843. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  8844. case knopTrue:
  8845. // enregistered
  8846. break;
  8847. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  8848. case knopEmpty:
  8849. break;
  8850. // Unary operators.
  8851. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  8852. case knopNot:
  8853. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8854. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8855. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8856. byteCodeGenerator->Writer()->Reg2(
  8857. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  8858. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8859. break;
  8860. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  8861. case knopNeg:
  8862. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8863. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8864. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8865. funcInfo->AcquireLoc(pnode);
  8866. byteCodeGenerator->Writer()->Reg2(
  8867. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  8868. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8869. break;
  8870. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  8871. case knopPos:
  8872. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8873. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8874. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8875. byteCodeGenerator->Writer()->Reg2(
  8876. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  8877. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8878. break;
  8879. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  8880. case knopLogNot:
  8881. {
  8882. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8883. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8884. // For boolean expressions that compute a result, we have to burn a register for the result
  8885. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8886. // full-on renaming in the back end.
  8887. funcInfo->AcquireLoc(pnode);
  8888. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  8889. {
  8890. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  8891. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  8892. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  8893. }
  8894. else
  8895. {
  8896. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8897. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  8898. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  8899. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8900. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8901. }
  8902. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8903. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8904. break;
  8905. }
  8906. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  8907. case knopEllipsis:
  8908. {
  8909. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8910. // Transparently pass the location of the array.
  8911. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  8912. break;
  8913. }
  8914. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  8915. case knopIncPost:
  8916. case knopDecPost:
  8917. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  8918. if (pnode->isUsed || fReturnValue)
  8919. {
  8920. byteCodeGenerator->StartStatement(pnode);
  8921. const Js::OpCode op = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  8922. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  8923. // Grab a register for the expression result.
  8924. funcInfo->AcquireLoc(pnode);
  8925. // Load the initial value, convert it (this is the expression result), and increment it.
  8926. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8927. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode1->location);
  8928. // Use temporary register if lhs cannot be assigned
  8929. Js::RegSlot incDecResult = pnode1->location;
  8930. if (funcInfo->RegIsConst(incDecResult) ||
  8931. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  8932. {
  8933. incDecResult = funcInfo->AcquireTmpRegister();
  8934. }
  8935. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  8936. Assert(oneReg != Js::Constants::NoRegister);
  8937. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  8938. // Store the incremented value.
  8939. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8940. // Release the incremented value and the l-value.
  8941. if (incDecResult != pnode1->location)
  8942. {
  8943. funcInfo->ReleaseTmpRegister(incDecResult);
  8944. }
  8945. funcInfo->ReleaseLoad(pnode1);
  8946. byteCodeGenerator->EndStatement(pnode);
  8947. break;
  8948. }
  8949. else
  8950. {
  8951. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  8952. }
  8953. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  8954. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  8955. case knopIncPre:
  8956. case knopDecPre:
  8957. {
  8958. byteCodeGenerator->StartStatement(pnode);
  8959. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  8960. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  8961. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  8962. // (i.e., is a constant).
  8963. const bool need_result_location =
  8964. pnode->isUsed
  8965. || fReturnValue
  8966. || funcInfo->RegIsConst(pnode1->location)
  8967. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  8968. if (need_result_location)
  8969. {
  8970. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  8971. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8972. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  8973. // Store the incremented value and release the l-value.
  8974. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  8975. }
  8976. else
  8977. {
  8978. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8979. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  8980. // Store the incremented value and release the l-value.
  8981. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  8982. }
  8983. funcInfo->ReleaseLoad(pnode1);
  8984. byteCodeGenerator->EndStatement(pnode);
  8985. break;
  8986. }
  8987. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  8988. case knopTypeof:
  8989. {
  8990. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8991. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  8992. switch (pnodeOpnd->nop)
  8993. {
  8994. case knopDot:
  8995. {
  8996. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  8997. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  8998. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  8999. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9000. funcInfo->AcquireLoc(pnode);
  9001. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  9002. break;
  9003. }
  9004. case knopIndex:
  9005. {
  9006. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9007. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9008. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9009. funcInfo->AcquireLoc(pnode);
  9010. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9011. break;
  9012. }
  9013. case knopName:
  9014. {
  9015. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9016. if (pnodeNameOpnd->IsUserIdentifier())
  9017. {
  9018. funcInfo->AcquireLoc(pnode);
  9019. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9020. break;
  9021. }
  9022. // Special names should fallthrough to default case
  9023. }
  9024. default:
  9025. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9026. funcInfo->ReleaseLoc(pnodeOpnd);
  9027. byteCodeGenerator->Writer()->Reg2(
  9028. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9029. break;
  9030. }
  9031. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9032. break;
  9033. }
  9034. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9035. case knopVoid:
  9036. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9037. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9038. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9039. break;
  9040. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9041. case knopArray:
  9042. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9043. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9044. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9045. break;
  9046. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9047. case knopObject:
  9048. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9049. funcInfo->AcquireLoc(pnode);
  9050. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9051. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9052. break;
  9053. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9054. case knopComputedName:
  9055. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9056. if (pnode->location == Js::Constants::NoRegister)
  9057. {
  9058. // The name is some expression with no home location. We can just re-use the register.
  9059. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9060. }
  9061. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9062. {
  9063. // The name had to be protected from side-effects of the RHS.
  9064. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9065. }
  9066. break;
  9067. // Binary and Ternary Operators
  9068. case knopAdd:
  9069. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9070. break;
  9071. case knopSub:
  9072. case knopMul:
  9073. case knopExpo:
  9074. case knopDiv:
  9075. case knopMod:
  9076. case knopOr:
  9077. case knopXor:
  9078. case knopAnd:
  9079. case knopLsh:
  9080. case knopRsh:
  9081. case knopRs2:
  9082. case knopIn:
  9083. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9084. break;
  9085. case knopInstOf:
  9086. {
  9087. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9088. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9089. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9090. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9091. funcInfo->AcquireLoc(pnode);
  9092. uint cacheId = funcInfo->NewIsInstInlineCache();
  9093. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9094. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9095. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9096. }
  9097. break;
  9098. case knopEq:
  9099. case knopEqv:
  9100. case knopNEqv:
  9101. case knopNe:
  9102. case knopLt:
  9103. case knopLe:
  9104. case knopGe:
  9105. case knopGt:
  9106. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9107. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9108. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9109. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9110. funcInfo->AcquireLoc(pnode);
  9111. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9112. pnode->AsParseNodeBin()->pnode2->location);
  9113. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9114. break;
  9115. case knopNew:
  9116. {
  9117. EmitNew(pnode, byteCodeGenerator, funcInfo);
  9118. byteCodeGenerator->EndStatement(pnode);
  9119. break;
  9120. }
  9121. case knopDelete:
  9122. {
  9123. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  9124. byteCodeGenerator->StartStatement(pnode);
  9125. switch (pexpr->nop)
  9126. {
  9127. case knopName:
  9128. {
  9129. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  9130. if (pnodeName->IsSpecialName())
  9131. {
  9132. funcInfo->AcquireLoc(pnode);
  9133. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9134. }
  9135. else
  9136. {
  9137. funcInfo->AcquireLoc(pnode);
  9138. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  9139. }
  9140. break;
  9141. }
  9142. case knopDot:
  9143. {
  9144. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  9145. {
  9146. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  9147. funcInfo->AcquireLoc(pnode);
  9148. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  9149. }
  9150. else
  9151. {
  9152. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9153. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9154. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9155. funcInfo->AcquireLoc(pnode);
  9156. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  9157. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  9158. }
  9159. break;
  9160. }
  9161. case knopIndex:
  9162. {
  9163. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9164. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  9165. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9166. funcInfo->AcquireLoc(pnode);
  9167. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  9168. break;
  9169. }
  9170. default:
  9171. {
  9172. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  9173. funcInfo->ReleaseLoc(pexpr);
  9174. byteCodeGenerator->Writer()->Reg2(
  9175. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  9176. break;
  9177. }
  9178. }
  9179. byteCodeGenerator->EndStatement(pnode);
  9180. break;
  9181. }
  9182. case knopCall:
  9183. {
  9184. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  9185. byteCodeGenerator->StartStatement(pnodeCall);
  9186. if (pnodeCall->isSuperCall)
  9187. {
  9188. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue);
  9189. }
  9190. else if (pnodeCall->pnodeTarget->nop == knopImport)
  9191. {
  9192. ParseNodePtr args = pnodeCall->pnodeArgs;
  9193. Assert(CountArguments(args) == 2); // import() takes one argument
  9194. Emit(args, byteCodeGenerator, funcInfo, false);
  9195. funcInfo->ReleaseLoc(args);
  9196. funcInfo->AcquireLoc(pnodeCall);
  9197. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  9198. }
  9199. else
  9200. {
  9201. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  9202. {
  9203. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  9204. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  9205. }
  9206. else
  9207. {
  9208. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  9209. }
  9210. }
  9211. byteCodeGenerator->EndStatement(pnode);
  9212. break;
  9213. }
  9214. case knopIndex:
  9215. {
  9216. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9217. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9218. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9219. Js::RegSlot protoLocation = callObjLocation;
  9220. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9221. {
  9222. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9223. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9224. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9225. }
  9226. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9227. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9228. funcInfo->AcquireLoc(pnode);
  9229. byteCodeGenerator->Writer()->Element(
  9230. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  9231. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9232. break;
  9233. }
  9234. // this is MemberExpression as rvalue
  9235. case knopDot:
  9236. {
  9237. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9238. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9239. funcInfo->AcquireLoc(pnode);
  9240. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9241. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9242. Js::RegSlot protoLocation = callObjLocation;
  9243. if (propertyId == Js::PropertyIds::length)
  9244. {
  9245. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9246. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  9247. }
  9248. else if (pnode->IsCallApplyTargetLoad())
  9249. {
  9250. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9251. {
  9252. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9253. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9254. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9255. }
  9256. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9257. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  9258. }
  9259. else
  9260. {
  9261. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9262. {
  9263. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9264. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9265. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9266. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9267. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  9268. }
  9269. else
  9270. {
  9271. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  9272. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  9273. }
  9274. }
  9275. break;
  9276. }
  9277. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  9278. case knopAsg:
  9279. {
  9280. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9281. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9282. byteCodeGenerator->StartStatement(pnode);
  9283. if (pnode->isUsed || fReturnValue)
  9284. {
  9285. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  9286. // which will copy the assigned value there.
  9287. funcInfo->AcquireLoc(pnode);
  9288. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9289. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9290. }
  9291. else
  9292. {
  9293. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9294. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9295. }
  9296. funcInfo->ReleaseLoc(rhs);
  9297. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  9298. {
  9299. funcInfo->ReleaseReference(lhs);
  9300. }
  9301. byteCodeGenerator->EndStatement(pnode);
  9302. break;
  9303. }
  9304. case knopName:
  9305. funcInfo->AcquireLoc(pnode);
  9306. if (ByteCodeGenerator::IsThis(pnode))
  9307. {
  9308. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  9309. }
  9310. else
  9311. {
  9312. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  9313. }
  9314. break;
  9315. case knopComma:
  9316. {
  9317. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9318. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  9319. // Easier to correct this here than to check every binary op in the parser.
  9320. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  9321. pnode1->isUsed = false;
  9322. if (pnode1->nop == knopComma)
  9323. {
  9324. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  9325. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  9326. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  9327. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  9328. SList<ParseNode *> rhsStack(alloc);
  9329. do
  9330. {
  9331. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  9332. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  9333. pnode1->isUsed = false;
  9334. } while (pnode1->nop == knopComma);
  9335. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9336. if (funcInfo->IsTmpReg(pnode1->location))
  9337. {
  9338. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9339. }
  9340. while (!rhsStack.Empty())
  9341. {
  9342. ParseNode *pnodeRhs = rhsStack.Pop();
  9343. pnodeRhs->isUsed = false;
  9344. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  9345. if (funcInfo->IsTmpReg(pnodeRhs->location))
  9346. {
  9347. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  9348. }
  9349. funcInfo->ReleaseLoc(pnodeRhs);
  9350. }
  9351. }
  9352. else
  9353. {
  9354. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9355. if (funcInfo->IsTmpReg(pnode1->location))
  9356. {
  9357. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9358. }
  9359. }
  9360. funcInfo->ReleaseLoc(pnode1);
  9361. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  9362. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  9363. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9364. funcInfo->AcquireLoc(pnode);
  9365. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  9366. {
  9367. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  9368. }
  9369. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9370. }
  9371. break;
  9372. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  9373. // boolean value short-circuits the operation, and to the value of the right-hand expression
  9374. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  9375. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  9376. case knopLogOr:
  9377. {
  9378. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9379. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9380. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9381. // optimizing the previous version where we had a dest for each level
  9382. funcInfo->AcquireLoc(pnode);
  9383. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9384. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9385. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9386. break;
  9387. }
  9388. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  9389. case knopLogAnd:
  9390. {
  9391. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9392. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9393. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9394. // optimizing the previous version where we had a dest for each level
  9395. funcInfo->AcquireLoc(pnode);
  9396. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9397. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9398. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9399. break;
  9400. }
  9401. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  9402. case knopQmark:
  9403. {
  9404. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9405. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9406. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9407. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9408. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9409. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  9410. // For boolean expressions that compute a result, we have to burn a register for the result
  9411. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9412. // full-on renaming in the back end.
  9413. funcInfo->AcquireLoc(pnode);
  9414. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  9415. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  9416. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  9417. // Record the branch bytecode offset
  9418. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9419. byteCodeGenerator->Writer()->Br(skipLabel);
  9420. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9421. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  9422. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  9423. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  9424. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9425. break;
  9426. }
  9427. case knopAsgAdd:
  9428. case knopAsgSub:
  9429. case knopAsgMul:
  9430. case knopAsgDiv:
  9431. case knopAsgExpo:
  9432. case knopAsgMod:
  9433. case knopAsgAnd:
  9434. case knopAsgXor:
  9435. case knopAsgOr:
  9436. case knopAsgLsh:
  9437. case knopAsgRsh:
  9438. case knopAsgRs2:
  9439. {
  9440. byteCodeGenerator->StartStatement(pnode);
  9441. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9442. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9443. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9444. // (i.e., is a constant).
  9445. const bool need_result_location =
  9446. pnode->isUsed
  9447. || fReturnValue
  9448. || funcInfo->RegIsConst(lhs->location)
  9449. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  9450. if (need_result_location)
  9451. {
  9452. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9453. // Grab a register for the initial value and load it.
  9454. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9455. funcInfo->ReleaseLoc(rhs);
  9456. // Do the arithmetic, store the result, and release the l-value.
  9457. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  9458. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  9459. }
  9460. else
  9461. {
  9462. // Grab a register for the initial value and load it. Might modify lhs->location.
  9463. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9464. funcInfo->ReleaseLoc(rhs);
  9465. // Do the arithmetic, store the result, and release the l-value.
  9466. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  9467. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  9468. }
  9469. funcInfo->ReleaseLoad(lhs);
  9470. byteCodeGenerator->EndStatement(pnode);
  9471. break;
  9472. }
  9473. // General nodes.
  9474. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  9475. case knopTempRef:
  9476. // TODO: check whether mov is necessary
  9477. funcInfo->AcquireLoc(pnode);
  9478. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9479. break;
  9480. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  9481. case knopTemp:
  9482. // Emit initialization code
  9483. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  9484. {
  9485. byteCodeGenerator->StartStatement(pnode);
  9486. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  9487. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  9488. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  9489. byteCodeGenerator->EndStatement(pnode);
  9490. }
  9491. break;
  9492. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9493. case knopVarDecl:
  9494. case knopConstDecl:
  9495. case knopLetDecl:
  9496. {
  9497. // Emit initialization code
  9498. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  9499. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  9500. if (initNode != nullptr || pnode->nop == knopLetDecl)
  9501. {
  9502. Symbol *sym = pnode->AsParseNodeVar()->sym;
  9503. Js::RegSlot rhsLocation;
  9504. byteCodeGenerator->StartStatement(pnode);
  9505. if (initNode != nullptr)
  9506. {
  9507. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9508. rhsLocation = initNode->location;
  9509. if (initNode->nop == knopObject)
  9510. {
  9511. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  9512. }
  9513. else if (initNode->nop == knopInt)
  9514. {
  9515. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9516. }
  9517. }
  9518. else
  9519. {
  9520. Assert(pnode->nop == knopLetDecl);
  9521. rhsLocation = funcInfo->AcquireTmpRegister();
  9522. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9523. }
  9524. if (pnode->nop != knopVarDecl)
  9525. {
  9526. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  9527. sym->SetNeedDeclaration(false);
  9528. }
  9529. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  9530. funcInfo->ReleaseTmpRegister(rhsLocation);
  9531. byteCodeGenerator->EndStatement(pnode);
  9532. }
  9533. break;
  9534. }
  9535. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9536. case knopFncDecl:
  9537. // The "function declarations" were emitted in DefineFunctions()
  9538. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  9539. {
  9540. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  9541. }
  9542. break;
  9543. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9544. case knopClassDecl:
  9545. {
  9546. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  9547. funcInfo->AcquireLoc(pnodeClass);
  9548. Assert(pnodeClass->pnodeConstructor);
  9549. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9550. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9551. // Extends
  9552. if (pnodeClass->pnodeExtends)
  9553. {
  9554. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9555. // defer and nondefer parse modes.
  9556. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9557. }
  9558. // Constructor
  9559. Emit(pnodeClass->pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9560. if (bindingNameLocation != Js::Constants::NoRegister && !pnodeClass->pnodeConstructor->pnodeName)
  9561. {
  9562. Assert(pnodeClass->pnodeConstructor->HasComputedName());
  9563. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, pnodeClass->pnodeConstructor->location, bindingNameLocation);
  9564. }
  9565. if (pnodeClass->pnodeExtends)
  9566. {
  9567. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9568. byteCodeGenerator->Writer()->InitClass(pnodeClass->location, pnodeClass->pnodeExtends->location);
  9569. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9570. }
  9571. else
  9572. {
  9573. byteCodeGenerator->Writer()->InitClass(pnodeClass->location);
  9574. }
  9575. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9576. int cacheId = funcInfo->FindOrAddInlineCacheId(pnodeClass->location, Js::PropertyIds::prototype, false, false);
  9577. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnodeClass->location, cacheId);
  9578. // Static Methods
  9579. EmitClassInitializers(pnodeClass->pnodeStaticMembers, pnodeClass->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9580. // Instance Methods
  9581. EmitClassInitializers(pnodeClass->pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9582. funcInfo->ReleaseTmpRegister(protoLoc);
  9583. // Emit name binding.
  9584. if (pnodeClass->pnodeName)
  9585. {
  9586. Symbol * sym = pnodeClass->pnodeName->sym;
  9587. sym->SetNeedDeclaration(false);
  9588. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9589. }
  9590. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9591. if (pnodeClass->pnodeExtends)
  9592. {
  9593. funcInfo->ReleaseLoc(pnodeClass->pnodeExtends);
  9594. }
  9595. if (pnodeClass->pnodeDeclName)
  9596. {
  9597. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9598. sym->SetNeedDeclaration(false);
  9599. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9600. }
  9601. if (pnodeClass->IsDefaultModuleExport())
  9602. {
  9603. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9604. }
  9605. break;
  9606. }
  9607. case knopStrTemplate:
  9608. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9609. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  9610. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9611. break;
  9612. case knopEndCode:
  9613. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9614. // load undefined for the fallthrough case:
  9615. if (!funcInfo->IsGlobalFunction())
  9616. {
  9617. if (funcInfo->IsClassConstructor())
  9618. {
  9619. // For class constructors, we need to explicitly load 'this' into the return register.
  9620. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9621. }
  9622. else
  9623. {
  9624. // In the global function, implicit return values are copied to the return register, and if
  9625. // necessary the return register is initialized at the top. Don't clobber the value here.
  9626. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9627. }
  9628. }
  9629. // Label for non-fall-through return
  9630. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9631. if (funcInfo->GetHasCachedScope())
  9632. {
  9633. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  9634. }
  9635. byteCodeGenerator->StartStatement(pnode);
  9636. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9637. byteCodeGenerator->EndStatement(pnode);
  9638. break;
  9639. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9640. case knopDebugger:
  9641. byteCodeGenerator->StartStatement(pnode);
  9642. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9643. byteCodeGenerator->EndStatement(pnode);
  9644. break;
  9645. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9646. case knopFor:
  9647. {
  9648. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  9649. if (pnodeFor->pnodeInverted != nullptr)
  9650. {
  9651. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  9652. }
  9653. else
  9654. {
  9655. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9656. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  9657. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  9658. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9659. {
  9660. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9661. }
  9662. EmitLoop(pnodeFor,
  9663. pnodeFor->pnodeCond,
  9664. pnodeFor->pnodeBody,
  9665. pnodeFor->pnodeIncr,
  9666. byteCodeGenerator,
  9667. funcInfo,
  9668. fReturnValue,
  9669. FALSE,
  9670. pnodeFor->pnodeBlock);
  9671. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9672. }
  9673. break;
  9674. }
  9675. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9676. case knopIf:
  9677. {
  9678. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  9679. byteCodeGenerator->StartStatement(pnodeIf);
  9680. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9681. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9682. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9683. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  9684. byteCodeGenerator->EndStatement(pnodeIf);
  9685. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9686. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9687. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  9688. if (pnodeIf->pnodeFalse != nullptr)
  9689. {
  9690. // has else clause
  9691. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9692. // Record the branch bytecode offset
  9693. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9694. // then clause skips else clause
  9695. byteCodeGenerator->Writer()->Br(skipLabel);
  9696. // generate code for else clause
  9697. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9698. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9699. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  9700. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9701. }
  9702. else
  9703. {
  9704. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9705. }
  9706. if (pnodeIf->emitLabels)
  9707. {
  9708. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  9709. }
  9710. break;
  9711. }
  9712. case knopWhile:
  9713. {
  9714. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9715. EmitLoop(pnodeWhile,
  9716. pnodeWhile->pnodeCond,
  9717. pnodeWhile->pnodeBody,
  9718. nullptr,
  9719. byteCodeGenerator,
  9720. funcInfo,
  9721. fReturnValue);
  9722. break;
  9723. }
  9724. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9725. case knopDoWhile:
  9726. {
  9727. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9728. EmitLoop(pnodeWhile,
  9729. pnodeWhile->pnodeCond,
  9730. pnodeWhile->pnodeBody,
  9731. nullptr,
  9732. byteCodeGenerator,
  9733. funcInfo,
  9734. fReturnValue,
  9735. true);
  9736. break;
  9737. }
  9738. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9739. case knopForIn:
  9740. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9741. break;
  9742. case knopForOf:
  9743. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9744. break;
  9745. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9746. case knopReturn:
  9747. {
  9748. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  9749. byteCodeGenerator->StartStatement(pnodeReturn);
  9750. if (pnodeReturn->pnodeExpr != nullptr)
  9751. {
  9752. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  9753. {
  9754. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9755. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9756. }
  9757. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9758. if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9759. {
  9760. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  9761. }
  9762. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9763. }
  9764. else
  9765. {
  9766. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9767. }
  9768. if (funcInfo->IsClassConstructor())
  9769. {
  9770. // return expr; // becomes like below:
  9771. //
  9772. // if (IsObject(expr)) {
  9773. // return expr;
  9774. // } else if (IsBaseClassConstructor) {
  9775. // return this;
  9776. // } else if (!IsUndefined(expr)) {
  9777. // throw TypeError;
  9778. // }
  9779. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9780. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9781. if (funcInfo->IsBaseClassConstructor())
  9782. {
  9783. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  9784. }
  9785. else
  9786. {
  9787. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9788. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9789. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9790. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9791. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9792. }
  9793. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9794. }
  9795. if (pnodeReturn->grfnop & fnopCleanup)
  9796. {
  9797. EmitJumpCleanup(pnodeReturn, nullptr, byteCodeGenerator, funcInfo);
  9798. }
  9799. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9800. byteCodeGenerator->EndStatement(pnodeReturn);
  9801. break;
  9802. }
  9803. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9804. case knopBlock:
  9805. {
  9806. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  9807. if (pnodeBlock->pnodeStmt != nullptr)
  9808. {
  9809. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  9810. if (pnodeBlock->emitLabels)
  9811. {
  9812. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  9813. }
  9814. }
  9815. break;
  9816. }
  9817. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9818. case knopWith:
  9819. {
  9820. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  9821. Assert(pnodeWith->pnodeObj != nullptr);
  9822. byteCodeGenerator->StartStatement(pnodeWith);
  9823. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9824. // is overwritten in the body, the lookups are not affected.
  9825. funcInfo->AcquireLoc(pnodeWith);
  9826. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  9827. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnodeWith->location;
  9828. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  9829. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9830. {
  9831. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewUnscopablesWrapperObject, pnodeWith->location, regVal);
  9832. }
  9833. byteCodeGenerator->EndStatement(pnodeWith);
  9834. #ifdef PERF_HINT
  9835. if (PHASE_TRACE1(Js::PerfHintPhase))
  9836. {
  9837. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9838. }
  9839. #endif
  9840. if (pnodeWith->pnodeBody != nullptr)
  9841. {
  9842. Scope *scope = pnodeWith->scope;
  9843. scope->SetLocation(pnodeWith->location);
  9844. byteCodeGenerator->PushScope(scope);
  9845. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9846. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9847. {
  9848. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9849. }
  9850. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9851. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  9852. byteCodeGenerator->PopScope();
  9853. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  9854. }
  9855. if (pnodeWith->emitLabels)
  9856. {
  9857. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  9858. }
  9859. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9860. {
  9861. funcInfo->ReleaseTmpRegister(regVal);
  9862. }
  9863. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  9864. break;
  9865. }
  9866. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  9867. case knopBreak:
  9868. {
  9869. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9870. Assert(pnodeJump->pnodeTarget->emitLabels);
  9871. byteCodeGenerator->StartStatement(pnodeJump);
  9872. if (pnodeJump->grfnop & fnopCleanup)
  9873. {
  9874. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  9875. }
  9876. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  9877. if (pnodeJump->emitLabels)
  9878. {
  9879. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  9880. }
  9881. byteCodeGenerator->EndStatement(pnodeJump);
  9882. break;
  9883. }
  9884. case knopContinue:
  9885. {
  9886. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9887. Assert(pnodeJump->pnodeTarget->emitLabels);
  9888. byteCodeGenerator->StartStatement(pnodeJump);
  9889. if (pnodeJump->grfnop & fnopCleanup)
  9890. {
  9891. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  9892. }
  9893. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  9894. byteCodeGenerator->EndStatement(pnodeJump);
  9895. break;
  9896. }
  9897. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  9898. case knopSwitch:
  9899. {
  9900. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  9901. BOOL fHasDefault = false;
  9902. Assert(pnodeSwitch->pnodeVal != nullptr);
  9903. byteCodeGenerator->StartStatement(pnodeSwitch);
  9904. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  9905. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  9906. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  9907. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  9908. byteCodeGenerator->EndStatement(pnodeSwitch);
  9909. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  9910. // code so the BE can optimize it.
  9911. ParseNodeCase *pnodeCase;
  9912. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  9913. {
  9914. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  9915. // expression take place regardless.
  9916. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  9917. if (pnodeCase == pnodeSwitch->pnodeDefault)
  9918. {
  9919. fHasDefault = true;
  9920. continue;
  9921. }
  9922. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  9923. byteCodeGenerator->Writer()->BrReg2(
  9924. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  9925. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  9926. }
  9927. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  9928. if (fHasDefault)
  9929. {
  9930. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  9931. }
  9932. else
  9933. {
  9934. if (!pnodeSwitch->emitLabels)
  9935. {
  9936. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  9937. }
  9938. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  9939. }
  9940. // Now emit the case arms to which we jump on matching a case value.
  9941. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  9942. {
  9943. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  9944. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9945. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  9946. }
  9947. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  9948. funcInfo->ReleaseTmpRegister(regVal);
  9949. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  9950. if (!fHasDefault || pnodeSwitch->emitLabels)
  9951. {
  9952. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  9953. }
  9954. break;
  9955. }
  9956. case knopTryCatch:
  9957. {
  9958. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  9959. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  9960. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  9961. Assert(pnodeTry);
  9962. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  9963. Assert(pnodeCatch);
  9964. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  9965. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  9966. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  9967. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  9968. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  9969. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  9970. if (funcInfo->byteCodeFunction->IsCoroutine())
  9971. {
  9972. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9973. }
  9974. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9975. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  9976. if (funcInfo->byteCodeFunction->IsCoroutine())
  9977. {
  9978. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9979. }
  9980. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  9981. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9982. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  9983. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  9984. ParseNode *pnodeObj = pnodeCatch->GetParam();
  9985. Assert(pnodeObj);
  9986. Js::RegSlot location;
  9987. bool acquiredTempLocation = false;
  9988. Js::DebuggerScope *debuggerScope = nullptr;
  9989. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  9990. bool isPattern = pnodeObj->nop == knopParamPattern;
  9991. if (isPattern)
  9992. {
  9993. location = pnodeObj->AsParseNodeParamPattern()->location;
  9994. }
  9995. else
  9996. {
  9997. location = pnodeObj->AsParseNodeName()->sym->GetLocation();
  9998. }
  9999. if (location == Js::Constants::NoRegister)
  10000. {
  10001. location = funcInfo->AcquireLoc(pnodeObj);
  10002. acquiredTempLocation = true;
  10003. }
  10004. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10005. Scope *scope = pnodeCatch->scope;
  10006. byteCodeGenerator->PushScope(scope);
  10007. if (scope->GetMustInstantiate())
  10008. {
  10009. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10010. if (scope->GetIsObject())
  10011. {
  10012. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10013. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10014. }
  10015. else
  10016. {
  10017. int index = Js::DebuggerScope::InvalidScopeIndex;
  10018. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10019. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10020. }
  10021. }
  10022. else
  10023. {
  10024. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10025. }
  10026. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10027. {
  10028. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10029. {
  10030. Assert(scope->GetMustInstantiate());
  10031. if (scope->GetIsObject())
  10032. {
  10033. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10034. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10035. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10036. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10037. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10038. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10039. }
  10040. else
  10041. {
  10042. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10043. if (initializeParam)
  10044. {
  10045. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10046. }
  10047. else
  10048. {
  10049. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10050. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10051. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10052. funcInfo->ReleaseTmpRegister(tmpReg);
  10053. }
  10054. }
  10055. }
  10056. else
  10057. {
  10058. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10059. if (initializeParam)
  10060. {
  10061. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10062. }
  10063. else
  10064. {
  10065. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10066. }
  10067. }
  10068. };
  10069. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10070. if (isPattern)
  10071. {
  10072. Parser::MapBindIdentifier(pnodeObj->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  10073. {
  10074. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10075. if (itemLocation == Js::Constants::NoRegister)
  10076. {
  10077. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10078. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10079. itemLocation = ByteCodeGenerator::ReturnRegister;
  10080. }
  10081. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10082. });
  10083. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10084. // Now emitting bytecode for destructuring pattern
  10085. byteCodeGenerator->StartStatement(pnodeCatch);
  10086. ParseNodePtr pnode1 = pnodeObj->AsParseNodeParamPattern()->pnode1;
  10087. Assert(pnode1->IsPattern());
  10088. if (funcInfo->byteCodeFunction->IsCoroutine())
  10089. {
  10090. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10091. }
  10092. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10093. byteCodeGenerator->EndStatement(pnodeCatch);
  10094. }
  10095. else
  10096. {
  10097. ParamTrackAndInitialization(pnodeObj->AsParseNodeName()->sym, true /*initializeParam*/, location);
  10098. if (scope->GetMustInstantiate())
  10099. {
  10100. pnodeObj->AsParseNodeName()->sym->SetIsGlobalCatch(true);
  10101. }
  10102. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10103. // Allow a debugger to stop on the 'catch (e)'
  10104. byteCodeGenerator->StartStatement(pnodeCatch);
  10105. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10106. byteCodeGenerator->EndStatement(pnodeCatch);
  10107. if (funcInfo->byteCodeFunction->IsCoroutine())
  10108. {
  10109. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10110. }
  10111. }
  10112. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10113. if (funcInfo->byteCodeFunction->IsCoroutine())
  10114. {
  10115. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10116. }
  10117. byteCodeGenerator->PopScope();
  10118. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10119. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10120. if (acquiredTempLocation)
  10121. {
  10122. funcInfo->ReleaseLoc(pnodeObj);
  10123. }
  10124. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10125. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10126. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10127. break;
  10128. }
  10129. case knopTryFinally:
  10130. {
  10131. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10132. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10133. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10134. Assert(pnodeTry);
  10135. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10136. Assert(pnodeFinally);
  10137. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10138. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10139. Js::RegSlot regException = Js::Constants::NoRegister;
  10140. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10141. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10142. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10143. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10144. // For now, if the function is generator we are using the TryFinallyWithYield.
  10145. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  10146. if (funcInfo->byteCodeFunction->IsCoroutine())
  10147. {
  10148. regException = funcInfo->AcquireTmpRegister();
  10149. regOffset = funcInfo->AcquireTmpRegister();
  10150. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10151. tryRecForTry.reg1 = regException;
  10152. tryRecForTry.reg2 = regOffset;
  10153. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10154. }
  10155. else
  10156. {
  10157. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10158. }
  10159. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10160. funcInfo->StartRecordingOutArgs(1);
  10161. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10162. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10163. if (funcInfo->byteCodeFunction->IsCoroutine())
  10164. {
  10165. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10166. }
  10167. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10168. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10169. // Note: although we don't use OpCode::Leave for finally block,
  10170. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10171. // This has to be on offset prior to offset of 1st statement of finally.
  10172. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10173. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10174. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10175. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10176. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  10177. if (funcInfo->byteCodeFunction->IsCoroutine())
  10178. {
  10179. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  10180. }
  10181. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10182. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  10183. if (funcInfo->byteCodeFunction->IsCoroutine())
  10184. {
  10185. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10186. funcInfo->ReleaseTmpRegister(regOffset);
  10187. funcInfo->ReleaseTmpRegister(regException);
  10188. }
  10189. funcInfo->EndRecordingOutArgs(1);
  10190. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10191. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  10192. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  10193. break;
  10194. }
  10195. case knopThrow:
  10196. byteCodeGenerator->StartStatement(pnode);
  10197. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10198. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  10199. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10200. byteCodeGenerator->EndStatement(pnode);
  10201. break;
  10202. case knopYieldLeaf:
  10203. byteCodeGenerator->StartStatement(pnode);
  10204. funcInfo->AcquireLoc(pnode);
  10205. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  10206. byteCodeGenerator->EndStatement(pnode);
  10207. break;
  10208. case knopAwait:
  10209. case knopYield:
  10210. byteCodeGenerator->StartStatement(pnode);
  10211. funcInfo->AcquireLoc(pnode);
  10212. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10213. EmitYield(pnode->AsParseNodeUni()->pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  10214. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10215. byteCodeGenerator->EndStatement(pnode);
  10216. break;
  10217. case knopYieldStar:
  10218. byteCodeGenerator->StartStatement(pnode);
  10219. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  10220. byteCodeGenerator->EndStatement(pnode);
  10221. break;
  10222. case knopExportDefault:
  10223. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10224. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  10225. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  10226. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  10227. break;
  10228. default:
  10229. AssertMsg(0, "emit unhandled pnode op");
  10230. break;
  10231. }
  10232. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  10233. {
  10234. // If this statement may produce the global function's return value, copy its result to the return register.
  10235. // fReturnValue implies global function, which implies that "return" is a parse error.
  10236. Assert(funcInfo->IsGlobalFunction());
  10237. Assert(pnode->nop != knopReturn);
  10238. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  10239. }
  10240. }