ByteCodeEmitter.cpp 494 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "RuntimeByteCodePch.h"
  7. #include "FormalsUtil.h"
  8. #include "Language/AsmJs.h"
  9. #include "ConfigFlagsList.h"
  10. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  12. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  13. void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
  14. void EmitStartupYield(ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  15. void EmitYield(Js::RegSlot resultReg, Js::RegSlot inputReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  16. void EmitAwait(Js::RegSlot resultReg, Js::RegSlot inputReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  17. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  18. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  19. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  20. bool CallTargetIsArray(ParseNode *pnode)
  21. {
  22. return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
  23. }
  24. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  25. if ((isTopLevel)) \
  26. { \
  27. byteCodeGenerator->StartStatement(pnode); \
  28. }
  29. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  30. if ((isTopLevel)) \
  31. { \
  32. byteCodeGenerator->EndStatement(pnode); \
  33. }
  34. DynamicLoadRecord::DynamicLoadRecord() : kind(DynamicLoadKind::Invalid), label(Js::Constants::NoByteCodeOffset), instance(Js::Constants::NoSlot) {}
  35. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE, ByteCodeGenerator *byteCodeGenerator)
  36. {
  37. // Try to determine whether pnodeSE (SE = side effect) may kill the named var represented by pnode.
  38. if (pnode->nop == knopComputedName)
  39. {
  40. pnode = pnode->AsParseNodeUni()->pnode1;
  41. }
  42. if (pnode->nop != knopName)
  43. {
  44. // Only investigating named vars here.
  45. return false;
  46. }
  47. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  48. SList<ParseNode*> pNodeSEStack(alloc);
  49. pNodeSEStack.Push(pnodeSE);
  50. // A pnodeSE can have children that can cause a side effect on pnode. A stack is used to check
  51. // pnodeSE and all potential pnodeSE children that could cause a side effect on pnode. When a
  52. // child pnodeSE can cause a side effect on pnode, immediately return true. Otherwise continue
  53. // checking children of pnodeSE until none exist
  54. while (!pNodeSEStack.Empty())
  55. {
  56. ParseNode *currPnodeSE = pNodeSEStack.Pop();
  57. uint fnop = ParseNode::Grfnop(currPnodeSE->nop);
  58. if (fnop & fnopLeaf)
  59. {
  60. // pnodeSE is a leaf and can't kill anything.
  61. continue;
  62. }
  63. else if (fnop & fnopAsg)
  64. {
  65. // pnodeSE is an assignment (=, ++, +=, etc.)
  66. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  67. // maybe because of code layout or some other subtle effect.
  68. return true;
  69. }
  70. else if (fnop & fnopUni)
  71. {
  72. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  73. if (currPnodeSE->nop == knopTempRef)
  74. {
  75. continue;
  76. }
  77. else if (currPnodeSE->AsParseNodeUni()->pnode1)
  78. {
  79. pNodeSEStack.Push(currPnodeSE->AsParseNodeUni()->pnode1);
  80. }
  81. }
  82. else if (fnop & fnopBin)
  83. {
  84. // currPnodeSE is a binary (or ternary) op, so check sources (if present).
  85. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode1);
  86. if (currPnodeSE->AsParseNodeBin()->pnode2)
  87. {
  88. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode2);
  89. }
  90. }
  91. else if (currPnodeSE->nop == knopQmark)
  92. {
  93. ParseNodeTri * pnodeTriSE = currPnodeSE->AsParseNodeTri();
  94. pNodeSEStack.Push(pnodeTriSE->pnode1);
  95. pNodeSEStack.Push(pnodeTriSE->pnode2);
  96. pNodeSEStack.Push(pnodeTriSE->pnode3);
  97. }
  98. else if (currPnodeSE->nop == knopCall || currPnodeSE->nop == knopNew)
  99. {
  100. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeTarget);
  101. if (currPnodeSE->AsParseNodeCall()->pnodeArgs)
  102. {
  103. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeArgs);
  104. }
  105. }
  106. else if (currPnodeSE->nop == knopList)
  107. {
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. bool IsCallOfConstants(ParseNode *pnode);
  114. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  115. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  116. bool IsArguments(ParseNode *pnode)
  117. {
  118. for (;;)
  119. {
  120. switch (pnode->nop)
  121. {
  122. case knopName:
  123. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  124. case knopCall:
  125. case knopNew:
  126. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  127. {
  128. return true;
  129. }
  130. if (pnode->AsParseNodeCall()->pnodeArgs)
  131. {
  132. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  133. while (pnodeArg->nop == knopList)
  134. {
  135. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  136. return true;
  137. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  138. }
  139. pnode = pnodeArg;
  140. break;
  141. }
  142. return false;
  143. case knopArray:
  144. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  145. {
  146. return false;
  147. }
  148. pnode = pnode->AsParseNodeUni()->pnode1;
  149. break;
  150. case knopQmark:
  151. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  152. {
  153. return true;
  154. }
  155. pnode = pnode->AsParseNodeTri()->pnode3;
  156. break;
  157. //
  158. // Cases where we don't check for "arguments" yet.
  159. // Assume that they might have it. Disable the optimization in such scenarios
  160. //
  161. case knopList:
  162. case knopObject:
  163. case knopVarDecl:
  164. case knopConstDecl:
  165. case knopLetDecl:
  166. case knopFncDecl:
  167. case knopClassDecl:
  168. case knopFor:
  169. case knopIf:
  170. case knopDoWhile:
  171. case knopWhile:
  172. case knopForIn:
  173. case knopForOf:
  174. case knopForAwaitOf:
  175. case knopReturn:
  176. case knopBlock:
  177. case knopBreak:
  178. case knopContinue:
  179. case knopTypeof:
  180. case knopThrow:
  181. case knopWith:
  182. case knopFinally:
  183. case knopTry:
  184. case knopTryCatch:
  185. case knopTryFinally:
  186. case knopArrayPattern:
  187. case knopObjectPattern:
  188. case knopParamPattern:
  189. return true;
  190. default:
  191. {
  192. uint flags = ParseNode::Grfnop(pnode->nop);
  193. if (flags&fnopUni)
  194. {
  195. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  196. Assert(pnodeUni->pnode1);
  197. pnode = pnodeUni->pnode1;
  198. break;
  199. }
  200. else if (flags&fnopBin)
  201. {
  202. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  203. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  204. if (IsArguments(pnodeBin->pnode1))
  205. {
  206. return true;
  207. }
  208. pnode = pnodeBin->pnode2;
  209. break;
  210. }
  211. return false;
  212. }
  213. }
  214. }
  215. }
  216. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  217. void Emit(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, bool isConstructorCall = false, bool isTopLevel = false);
  218. void EmitBinaryOpnds(ParseNode* pnode1, ParseNode* pnode2, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot computedPropertyLocation = Js::Constants::NoRegister);
  219. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  220. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  221. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  222. static const Js::OpCode nopToOp[knopLim] =
  223. {
  224. #define OP(x) Br##x##_A
  225. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  226. #include "ptlist.h"
  227. };
  228. static const Js::OpCode nopToCMOp[knopLim] =
  229. {
  230. #define OP(x) Cm##x##_A
  231. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  232. #include "ptlist.h"
  233. };
  234. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  235. {
  236. switch (op)
  237. {
  238. case Js::OpCode::StLocalSlot:
  239. return Js::OpCode::StLocalSlotChkUndecl;
  240. case Js::OpCode::StParamSlot:
  241. return Js::OpCode::StParamSlotChkUndecl;
  242. case Js::OpCode::StInnerSlot:
  243. return Js::OpCode::StInnerSlotChkUndecl;
  244. case Js::OpCode::StEnvSlot:
  245. return Js::OpCode::StEnvSlotChkUndecl;
  246. case Js::OpCode::StObjSlot:
  247. return Js::OpCode::StObjSlotChkUndecl;
  248. case Js::OpCode::StLocalObjSlot:
  249. return Js::OpCode::StLocalObjSlotChkUndecl;
  250. case Js::OpCode::StParamObjSlot:
  251. return Js::OpCode::StParamObjSlotChkUndecl;
  252. case Js::OpCode::StInnerObjSlot:
  253. return Js::OpCode::StInnerObjSlotChkUndecl;
  254. case Js::OpCode::StEnvObjSlot:
  255. return Js::OpCode::StEnvObjSlotChkUndecl;
  256. default:
  257. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  258. return Js::OpCode::InvalidOpCode;
  259. }
  260. }
  261. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  262. // debuggerScope - The scope to add the variable to.
  263. // symbol - The symbol that represents the register property.
  264. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  265. // flags - The flags to assign to the property.
  266. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  267. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  268. Js::DebuggerScope *debuggerScope,
  269. Symbol *symbol,
  270. FuncInfo *funcInfo,
  271. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  272. bool isFunctionDeclaration /*= false*/)
  273. {
  274. Assert(debuggerScope);
  275. Assert(symbol);
  276. Assert(funcInfo);
  277. Js::RegSlot location = symbol->GetLocation();
  278. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  279. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  280. {
  281. // We have to get the appropriate scope and add property over there.
  282. // Make sure the scope is created whether we're in debug mode or not, because we
  283. // need the empty scopes present during reparsing for debug mode.
  284. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  285. }
  286. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  287. {
  288. // Only track the property if we're in debug mode since it's only needed by the debugger.
  289. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  290. this->Writer()->AddPropertyToDebuggerScope(
  291. correctDebuggerScope,
  292. location,
  293. propertyId,
  294. /*shouldConsumeRegister*/ true,
  295. flags,
  296. isFunctionDeclaration);
  297. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  298. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  299. symbol->SetIsTrackedForDebugger(true);
  300. }
  301. }
  302. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  303. Js::DebuggerScope *debuggerScope,
  304. Symbol *symbol,
  305. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  306. bool isFunctionDeclaration /*= false*/)
  307. {
  308. Assert(debuggerScope);
  309. Assert(symbol);
  310. // Only need to track activation object properties in debug mode.
  311. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  312. {
  313. Js::RegSlot location = symbol->GetLocation();
  314. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  315. this->Writer()->AddPropertyToDebuggerScope(
  316. debuggerScope,
  317. location,
  318. propertyId,
  319. /*shouldConsumeRegister*/ false,
  320. flags,
  321. isFunctionDeclaration);
  322. symbol->SetIsTrackedForDebugger(true);
  323. }
  324. }
  325. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  326. Js::DebuggerScope *debuggerScope,
  327. Symbol* symbol,
  328. Js::PropertyId propertyId,
  329. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  330. bool isFunctionDeclaration /*= false*/)
  331. {
  332. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  333. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  334. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  335. Assert(debuggerScope);
  336. Assert(symbol);
  337. if (!symbol->GetIsTrackedForDebugger())
  338. {
  339. Js::RegSlot location = symbol->GetScopeSlot();
  340. Assert(location != Js::Constants::NoRegister);
  341. Assert(propertyId != Js::Constants::NoProperty);
  342. this->Writer()->AddPropertyToDebuggerScope(
  343. debuggerScope,
  344. location,
  345. propertyId,
  346. /*shouldConsumeRegister*/ false,
  347. flags,
  348. isFunctionDeclaration);
  349. symbol->SetIsTrackedForDebugger(true);
  350. }
  351. }
  352. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  353. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  354. {
  355. Assert(functionDeclarationSymbol);
  356. Assert(funcInfoParent);
  357. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  358. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  359. // which is done in other Track* functions that we call.
  360. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  361. {
  362. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  363. {
  364. this->TrackActivationObjectPropertyForDebugger(
  365. this->Writer()->GetCurrentDebuggerScope(),
  366. functionDeclarationSymbol,
  367. Js::DebuggerScopePropertyFlags_None,
  368. true /*isFunctionDeclaration*/);
  369. }
  370. else
  371. {
  372. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  373. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  374. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  375. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  376. functionDeclarationSymbol->EnsurePosition(this);
  377. this->TrackSlotArrayPropertyForDebugger(
  378. this->Writer()->GetCurrentDebuggerScope(),
  379. functionDeclarationSymbol,
  380. functionDeclarationSymbol->GetPosition(),
  381. Js::DebuggerScopePropertyFlags_None,
  382. true /*isFunctionDeclaration*/);
  383. }
  384. }
  385. else
  386. {
  387. this->TrackRegisterPropertyForDebugger(
  388. this->Writer()->GetCurrentDebuggerScope(),
  389. functionDeclarationSymbol,
  390. funcInfoParent,
  391. Js::DebuggerScopePropertyFlags_None,
  392. true /*isFunctionDeclaration*/);
  393. }
  394. }
  395. // Updates the byte code offset of the property with the passed in location and ID.
  396. // Used to track let/const variables that are in the dead zone debugger side.
  397. // location - The activation object, scope slot index, or register location for the property.
  398. // propertyId - The ID of the property to update.
  399. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  400. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  401. {
  402. Assert(this->Writer());
  403. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  404. Assert(currentDebuggerScope);
  405. if (currentDebuggerScope != nullptr)
  406. {
  407. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  408. currentDebuggerScope,
  409. location,
  410. propertyId,
  411. shouldConsumeRegister);
  412. }
  413. }
  414. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  415. {
  416. if (funcInfo->GetHasCachedScope())
  417. {
  418. this->LoadCachedHeapArguments(funcInfo);
  419. }
  420. else
  421. {
  422. this->LoadUncachedHeapArguments(funcInfo);
  423. }
  424. }
  425. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  426. {
  427. Assert(funcInfo);
  428. Assert(propIds);
  429. Assert(byteCodeGenerator);
  430. bool hadDuplicates = false;
  431. Js::ArgSlot i = 0;
  432. auto processArg = [&](ParseNode *pnode)
  433. {
  434. if (pnode->IsVarLetOrConst())
  435. {
  436. Assert(i < propIds->count);
  437. Symbol *sym = pnode->AsParseNodeVar()->sym;
  438. Assert(sym);
  439. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  440. //
  441. // Check if the function has any same name parameters
  442. // For the same name param, only the last one will be passed the correct propertyid
  443. // For remaining dup param names, pass Constants::NoProperty
  444. //
  445. for (Js::ArgSlot j = 0; j < i; j++)
  446. {
  447. if (propIds->elements[j] == symPos)
  448. {
  449. // Found a dup parameter name
  450. propIds->elements[j] = Js::Constants::NoProperty;
  451. hadDuplicates = true;
  452. break;
  453. }
  454. }
  455. propIds->elements[i] = symPos;
  456. }
  457. else
  458. {
  459. propIds->elements[i] = Js::Constants::NoProperty;
  460. }
  461. ++i;
  462. };
  463. MapFormals(funcInfo->root, processArg);
  464. propIds->hadDuplicates = hadDuplicates;
  465. }
  466. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  467. {
  468. Assert(funcInfo->GetHasHeapArguments());
  469. Scope *scope = funcInfo->GetBodyScope();
  470. Assert(scope);
  471. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  472. Assert(argSym && argSym->IsArguments());
  473. Js::RegSlot argumentsLoc = argSym->GetLocation();
  474. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  475. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  476. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  477. if (count == 0)
  478. {
  479. // If no formals to function (only "this"), then no need to create the scope object.
  480. // Leave both the arguments location and the propertyIds location as null.
  481. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  482. }
  483. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  484. {
  485. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  486. }
  487. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  488. {
  489. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  490. // at the expected location.
  491. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  492. GetFormalArgsArray(this, funcInfo, propIds);
  493. }
  494. this->m_writer.Reg1(opcode, argumentsLoc);
  495. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  496. }
  497. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  498. {
  499. Assert(funcInfo->GetHasHeapArguments());
  500. Scope *scope = funcInfo->GetBodyScope();
  501. Assert(scope);
  502. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  503. Assert(argSym && argSym->IsArguments());
  504. Js::RegSlot argumentsLoc = argSym->GetLocation();
  505. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  506. this->m_writer.Reg1(op, argumentsLoc);
  507. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  508. }
  509. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  510. {
  511. Assert(stringNodeList);
  512. uint index = 0;
  513. Js::Var str;
  514. IdentPtr pid;
  515. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  516. while (stringNodeList->nop == knopList)
  517. {
  518. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  519. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  520. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  521. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  522. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  523. index++;
  524. }
  525. Assert(stringNodeList->nop == knopStr);
  526. pid = stringNodeList->AsParseNodeStr()->pid;
  527. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  528. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  529. return pArr;
  530. }
  531. // For now, this just assigns field ids for the current script.
  532. // Later, we will combine this information with the global field id map.
  533. // This temporary code will not work if a global member is accessed both with and without a LHS.
  534. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  535. {
  536. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  537. {
  538. this->AssignPropertyId(sym, functionInfo);
  539. });
  540. }
  541. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  542. {
  543. Assert(pnodeBlock->nop == knopBlock);
  544. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  545. {
  546. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  547. // the debugger scope will not be created.
  548. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  549. FuncInfo *funcInfo = this->TopFuncInfo();
  550. Symbol *sym = pnode->AsParseNodeVar()->sym;
  551. Scope *scope = sym->GetScope();
  552. if (sym->GetIsGlobal())
  553. {
  554. Js::PropertyId propertyId = sym->EnsurePosition(this);
  555. if (this->flags & fscrEval)
  556. {
  557. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  558. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  559. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  560. }
  561. else
  562. {
  563. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  564. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  565. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  566. }
  567. }
  568. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  569. {
  570. if (scope->GetIsObject())
  571. {
  572. Js::RegSlot scopeLocation = scope->GetLocation();
  573. Js::PropertyId propertyId = sym->EnsurePosition(this);
  574. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  575. {
  576. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  577. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  578. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  579. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  580. }
  581. else
  582. {
  583. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  584. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  585. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  586. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  587. }
  588. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  589. }
  590. else
  591. {
  592. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  593. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  594. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  595. funcInfo->ReleaseTmpRegister(tmpReg);
  596. // Slot array properties are tracked in non-debug mode as well because they need to stay
  597. // around for heap enumeration and escaping during attach/detach.
  598. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  599. }
  600. }
  601. else if (!sym->GetIsModuleExportStorage())
  602. {
  603. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  604. {
  605. // let/const declared in a switch is the only case of a variable that must be checked for
  606. // use-before-declaration dynamically within its own function.
  607. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  608. }
  609. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  610. // will live only in slots, so tell the debugger to find them there.
  611. if (sym->NeedsSlotAlloc(this, funcInfo))
  612. {
  613. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  614. }
  615. else
  616. {
  617. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  618. }
  619. }
  620. };
  621. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  622. }
  623. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  624. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  625. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  626. {
  627. Assert(pnode);
  628. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  629. {
  630. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  631. // don't add a block to the chain if it has no let/const variables at all.
  632. return nullptr;
  633. }
  634. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  635. }
  636. // Records the end of the current scope, but only if the current block has block scoped content.
  637. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  638. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  639. {
  640. Assert(pnodeBlock);
  641. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  642. {
  643. return;
  644. }
  645. this->Writer()->RecordEndScopeObject();
  646. }
  647. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  648. {
  649. Js::DebuggerScope* debuggerScope = nullptr;
  650. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  651. {
  652. Scope *scope = pnodeBlock->scope;
  653. byteCodeGenerator->PushScope(scope);
  654. Js::RegSlot scopeLocation = scope->GetLocation();
  655. if (scope->GetMustInstantiate())
  656. {
  657. Assert(scopeLocation == Js::Constants::NoRegister);
  658. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  659. if (scope->GetIsObject())
  660. {
  661. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  662. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  663. }
  664. else
  665. {
  666. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  667. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  668. // TODO: Handle heap enumeration
  669. int scopeSlotCount = scope->GetScopeSlotCount();
  670. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  671. }
  672. }
  673. else
  674. {
  675. // In the direct register access case, there is no block scope emitted but we can still track
  676. // the start and end offset of the block. The location registers for let/const variables will still be
  677. // captured along with this range in InitBlockScopedContent().
  678. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  679. }
  680. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  681. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  682. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  683. ParseNodePtr pnodeScope;
  684. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  685. {
  686. switch (pnodeScope->nop)
  687. {
  688. case knopFncDecl:
  689. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  690. {
  691. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  692. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  693. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  694. // So we'll supply a temp that we allocate and release here.
  695. if (frameDisplayLoc == Js::Constants::NoRegister)
  696. {
  697. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  698. {
  699. frameDisplayLoc = funcInfo->frameDisplayRegister;
  700. }
  701. else
  702. {
  703. frameDisplayLoc = funcInfo->GetEnvRegister();
  704. }
  705. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  706. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  707. }
  708. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  709. }
  710. // If this is the global eval block scope, the function is actually assigned to the global
  711. // so we don't need to keep the registers.
  712. if (isGlobalEvalBlockScope)
  713. {
  714. funcInfo->ReleaseLoc(pnodeScope);
  715. pnodeScope->location = Js::Constants::NoRegister;
  716. }
  717. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  718. break;
  719. case knopBlock:
  720. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  721. break;
  722. case knopCatch:
  723. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  724. break;
  725. case knopWith:
  726. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  727. break;
  728. }
  729. }
  730. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  731. {
  732. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  733. }
  734. }
  735. else
  736. {
  737. Scope *scope = pnodeBlock->scope;
  738. if (scope)
  739. {
  740. if (scope->GetMustInstantiate())
  741. {
  742. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  743. }
  744. else
  745. {
  746. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  747. }
  748. }
  749. else
  750. {
  751. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  752. }
  753. }
  754. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  755. }
  756. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  757. {
  758. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  759. {
  760. Scope *scope = pnodeBlock->scope;
  761. Assert(scope);
  762. Assert(scope == byteCodeGenerator->GetCurrentScope());
  763. byteCodeGenerator->PopScope();
  764. }
  765. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  766. }
  767. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  768. {
  769. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  770. {
  771. // Only let variables have observable behavior when there are per iteration
  772. // bindings. const variables do not since they are immutable. Therefore,
  773. // (and the spec agrees), only create new scope clones if the loop variable
  774. // is a let declaration.
  775. bool isConst = false;
  776. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  777. // Exploit the fact that a for loop sxBlock can only have let and const
  778. // declarations, and can only have one or the other, regardless of how
  779. // many syms there might be. Thus only check the first sym.
  780. isConst = sym->GetDecl()->nop == knopConstDecl;
  781. return true;
  782. });
  783. if (!isConst)
  784. {
  785. Scope *scope = pnodeBlock->scope;
  786. Assert(scope == byteCodeGenerator->GetCurrentScope());
  787. if (scope->GetMustInstantiate())
  788. {
  789. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  790. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  791. }
  792. }
  793. }
  794. }
  795. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  796. {
  797. Assert(pnodeBlock->nop == knopBlock);
  798. ParseNode *pnode = pnodeBlock->pnodeStmt;
  799. if (pnode == nullptr)
  800. {
  801. return;
  802. }
  803. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  804. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  805. while (pnode->nop == knopList)
  806. {
  807. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  808. if (stmt == pnodeLastValStmt)
  809. {
  810. // This is the last guaranteed return value, so any potential return values have to be
  811. // copied to the return register from this point forward.
  812. pnodeLastValStmt = nullptr;
  813. }
  814. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  815. pnode = pnode->AsParseNodeBin()->pnode2;
  816. }
  817. if (pnode == pnodeLastValStmt)
  818. {
  819. pnodeLastValStmt = nullptr;
  820. }
  821. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  822. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  823. }
  824. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  825. {
  826. if (emitFunc->IsTmpReg(pnode->location))
  827. {
  828. pnode->location = Js::Constants::NoRegister;
  829. }
  830. }
  831. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  832. {
  833. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  834. {
  835. // Function declarations (not function-declaration RHS's) are already fully processed.
  836. // Skip them here so the temp registers don't get messed up.
  837. return;
  838. }
  839. if (stmt->nop == knopName || stmt->nop == knopDot)
  840. {
  841. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  842. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  843. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  844. StartStatement(stmt);
  845. Writer()->Empty(Js::OpCode::Nop);
  846. EndStatement(stmt);
  847. }
  848. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, true/*isTopLevel*/);
  849. if (funcInfo->IsTmpReg(stmt->location))
  850. {
  851. funcInfo->ReleaseLoc(stmt);
  852. }
  853. }
  854. // ByteCodeGenerator::DefineFunctions
  855. //
  856. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  857. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  858. // to make sure that sources of the stores have been defined.
  859. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  860. {
  861. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  862. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  863. if (funcInfoParent->GetHasCachedScope())
  864. {
  865. this->DefineCachedFunctions(funcInfoParent);
  866. }
  867. else
  868. {
  869. this->DefineUncachedFunctions(funcInfoParent);
  870. }
  871. }
  872. // Iterate over all child functions in a function's parameter and body scopes.
  873. template<typename Fn>
  874. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  875. {
  876. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  877. {
  878. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  879. {
  880. switch (pnode->nop)
  881. {
  882. case knopFncDecl:
  883. fn(pnode);
  884. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  885. break;
  886. case knopBlock:
  887. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  888. break;
  889. case knopCatch:
  890. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  891. break;
  892. case knopWith:
  893. pnode = pnode->AsParseNodeWith()->pnodeNext;
  894. break;
  895. default:
  896. AssertMsg(false, "Unexpected opcode in tree of scopes");
  897. return;
  898. }
  899. }
  900. };
  901. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  902. }
  903. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  904. {
  905. ParseNode *pnodeParent = funcInfoParent->root;
  906. uint slotCount = 0;
  907. auto countFncSlots = [&](ParseNode *pnodeFnc)
  908. {
  909. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  910. {
  911. slotCount++;
  912. }
  913. };
  914. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  915. if (slotCount == 0)
  916. {
  917. return;
  918. }
  919. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  920. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  921. if (extraBytesActual > INT_MAX)
  922. {
  923. Js::Throw::OutOfMemory();
  924. }
  925. int extraBytes = (int)extraBytesActual;
  926. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  927. // slotCount is guaranteed to be non-zero here.
  928. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  929. slotCount = 0;
  930. auto fillEntries = [&](ParseNode *pnodeFnc)
  931. {
  932. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  933. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration() || pnodeFnc->AsParseNodeFnc()->IsDefaultModuleExport()))
  934. {
  935. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  936. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  937. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  938. entry->scopeSlot = sym->GetScopeSlot();
  939. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  940. slotCount++;
  941. }
  942. };
  943. MapContainerScopeFunctions(pnodeParent, fillEntries);
  944. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  945. info,
  946. sizeof(Js::FuncInfoArray) + extraBytes,
  947. sizeof(Js::FuncInfoArray) + extraBytes);
  948. slotCount = 0;
  949. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  950. {
  951. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  952. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  953. {
  954. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  955. // Only happens if the sym is null (e.g., function x.y(){}).
  956. if (sym == nullptr)
  957. {
  958. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  959. }
  960. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  961. {
  962. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  963. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  964. }
  965. // The "x = function() {...}" case is being generated on the fly, during emission,
  966. // so the caller expects to be able to release this register.
  967. funcInfoParent->ReleaseLoc(pnodeFnc);
  968. pnodeFnc->location = Js::Constants::NoRegister;
  969. slotCount++;
  970. }
  971. };
  972. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  973. AdeletePlus(alloc, extraBytes, info);
  974. }
  975. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  976. {
  977. ParseNode *pnodeParent = funcInfoParent->root;
  978. auto defineCheck = [&](ParseNode *pnodeFnc)
  979. {
  980. Assert(pnodeFnc->nop == knopFncDecl);
  981. //
  982. // Don't define the function upfront in following cases
  983. // 1. x = function() {...};
  984. // Don't define the function for all modes.
  985. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  986. // rather than the scope entry to save a register (and possibly save the whole definition).
  987. //
  988. // 2. x = function f() {...};
  989. // f is not visible in the enclosing scope.
  990. // Such function expressions should be emitted only at the assignment point, as can be used only
  991. // after the assignment. Might save register.
  992. //
  993. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration() || pnodeFnc->AsParseNodeFnc()->IsDefaultModuleExport())
  994. {
  995. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  996. // The "x = function() {...}" case is being generated on the fly, during emission,
  997. // so the caller expects to be able to release this register.
  998. funcInfoParent->ReleaseLoc(pnodeFnc);
  999. pnodeFnc->location = Js::Constants::NoRegister;
  1000. }
  1001. };
  1002. MapContainerScopeFunctions(pnodeParent, defineCheck);
  1003. }
  1004. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  1005. {
  1006. // Assign the location holding the func object reference to the given name.
  1007. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  1008. Symbol *sym = pnodeFnc->pnodeName->sym;
  1009. if (sym != nullptr && !sym->GetIsFuncExpr())
  1010. {
  1011. if (sym->GetIsModuleExportStorage())
  1012. {
  1013. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1014. }
  1015. else if (sym->GetIsGlobal())
  1016. {
  1017. Js::PropertyId propertyId = sym->GetPosition();
  1018. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1019. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1020. {
  1021. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1022. }
  1023. }
  1024. else
  1025. {
  1026. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1027. {
  1028. if (!sym->GetHasNonCommittedReference() ||
  1029. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1030. {
  1031. // No point in trying to optimize if there are no references before we have to commit to slot.
  1032. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1033. sym->SetIsCommittedToSlot();
  1034. }
  1035. }
  1036. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1037. {
  1038. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1039. }
  1040. else
  1041. {
  1042. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1043. }
  1044. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1045. if (fncScopeSym)
  1046. {
  1047. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1048. {
  1049. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1050. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1051. }
  1052. else
  1053. {
  1054. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1061. {
  1062. Assert(pnodeFnc->nop == knopFncDecl);
  1063. funcInfoParent->AcquireLoc(pnodeFnc);
  1064. if (regEnv == Js::Constants::NoRegister)
  1065. {
  1066. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1067. if (frameDisplayTemp != Js::Constants::NoRegister)
  1068. {
  1069. // We allocated a temp to hold a local frame display value. Use that.
  1070. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1071. regEnv = frameDisplayTemp;
  1072. }
  1073. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1074. {
  1075. // This function has built a frame display, so pass it down.
  1076. regEnv = funcInfoParent->frameDisplayRegister;
  1077. }
  1078. else
  1079. {
  1080. // This function has no captured locals but inherits a closure environment, so pass it down.
  1081. regEnv = funcInfoParent->GetEnvRegister();
  1082. }
  1083. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1084. }
  1085. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1086. // "We need a closure for the nested function");
  1087. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1088. // 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
  1089. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1090. {
  1091. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1092. }
  1093. else
  1094. {
  1095. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1096. }
  1097. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1098. {
  1099. // A function declared at global scope in eval is untrackable,
  1100. // so make sure the caller's cached scope is invalidated.
  1101. this->funcEscapes = true;
  1102. }
  1103. else
  1104. {
  1105. if (pnodeFnc->IsDeclaration())
  1106. {
  1107. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1108. if (funcSymbol)
  1109. {
  1110. // In the case where a let/const declaration is the same symbol name
  1111. // as the function declaration (shadowing case), the let/const var and
  1112. // the function declaration symbol are the same and share the same flags
  1113. // (particularly, sym->GetIsBlockVar() for this code path).
  1114. //
  1115. // For example:
  1116. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1117. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1118. //
  1119. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1120. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1121. //
  1122. // In order to tell if the function is actually part
  1123. // of a block scope, we compare against the function scope here.
  1124. // Note that having a function with the same name as a let/const declaration
  1125. // is a redeclaration error, but we're pushing the fix for this out since it's
  1126. // a bit involved.
  1127. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1128. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1129. // Track all vars/lets/consts register slot function declarations.
  1130. if (ShouldTrackDebuggerMetadata()
  1131. // If this is a let binding function declaration at global level, we want to
  1132. // be sure to track the register location as well.
  1133. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1134. {
  1135. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1136. {
  1137. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1138. }
  1139. }
  1140. if (isFunctionDeclarationInBlock)
  1141. {
  1142. // We only track inner let bindings for the debugger side.
  1143. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1144. }
  1145. }
  1146. }
  1147. }
  1148. if (pnodeFnc->IsDefaultModuleExport())
  1149. {
  1150. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1151. }
  1152. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1153. {
  1154. return regEnv;
  1155. }
  1156. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1157. return regEnv;
  1158. }
  1159. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1160. {
  1161. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1162. // by an existing initialization.
  1163. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1164. ParseNode *pnode;
  1165. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1166. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1167. // Just assign one on the fly and re-use it for all initializations.
  1168. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1169. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1170. {
  1171. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1172. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1173. {
  1174. if (sym->IsSpecialSymbol())
  1175. {
  1176. // Special symbols have already had their initial values stored into their registers.
  1177. // In default-argument case we've stored those values into their slot locations, as well.
  1178. // We must do that because a default parameter may access a special symbol through a scope slot.
  1179. // In the non-default-argument case, though, we didn't yet store the values into the
  1180. // slots so let's do that now.
  1181. if (!funcInfo->root->HasNonSimpleParameterList())
  1182. {
  1183. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1184. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1185. {
  1186. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1187. }
  1188. }
  1189. continue;
  1190. }
  1191. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1192. {
  1193. // The init node was bound to the catch object, because it's inside a catch and has the
  1194. // same name as the catch object. But we want to define a user var at function scope,
  1195. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1196. // This also applies to a var declaration in the same scope as a let declaration.
  1197. #if DBG
  1198. if (sym->IsArguments())
  1199. {
  1200. // There is a block scoped var named arguments
  1201. Assert(!funcInfo->GetHasArguments());
  1202. continue;
  1203. }
  1204. else if (!sym->GetIsCatch())
  1205. {
  1206. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1207. Assert(funcInfo->bodyScope != sym->GetScope());
  1208. }
  1209. #endif
  1210. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1211. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1212. }
  1213. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1214. {
  1215. if (fGlobal)
  1216. {
  1217. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1218. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1219. // But we first need to make sure we're not trashing built-ins.
  1220. if (this->flags & fscrEval)
  1221. {
  1222. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1223. {
  1224. // Check/Init the property of the frame object
  1225. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1226. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1227. }
  1228. else
  1229. {
  1230. // The check and the init involve the first element in the scope chain.
  1231. this->m_writer.ElementScopedU(
  1232. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1233. }
  1234. }
  1235. else
  1236. {
  1237. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1238. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1239. }
  1240. }
  1241. else if (!sym->IsArguments())
  1242. {
  1243. if (sym->NeedsSlotAlloc(this, funcInfo))
  1244. {
  1245. if (!sym->GetHasNonCommittedReference() ||
  1246. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1247. {
  1248. // No point in trying to optimize if there are no references before we have to commit to slot.
  1249. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1250. sym->SetIsCommittedToSlot();
  1251. }
  1252. }
  1253. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1254. // is delayed) or a property of an object.
  1255. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1256. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1257. {
  1258. Js::RegSlot reg = sym->GetLocation();
  1259. if (reg == Js::Constants::NoRegister)
  1260. {
  1261. Assert(sym->IsInSlot(this, funcInfo));
  1262. reg = funcInfo->AcquireTmpRegister();
  1263. }
  1264. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1265. this->EmitLocalPropInit(reg, sym, funcInfo);
  1266. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1267. {
  1268. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1269. }
  1270. funcInfo->ReleaseTmpRegister(reg);
  1271. }
  1272. }
  1273. else if (ShouldTrackDebuggerMetadata())
  1274. {
  1275. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1276. {
  1277. Js::RegSlot reg = sym->GetLocation();
  1278. if (reg != Js::Constants::NoRegister)
  1279. {
  1280. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1281. }
  1282. }
  1283. }
  1284. sym->SetHasInit(TRUE);
  1285. }
  1286. }
  1287. }
  1288. if (tmpReg != Js::Constants::NoRegister)
  1289. {
  1290. funcInfo->ReleaseTmpRegister(tmpReg);
  1291. }
  1292. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1293. {
  1294. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1295. }
  1296. }
  1297. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1298. {
  1299. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1300. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1301. // This protects us from, for instance, trying to restore garbage on bailout.
  1302. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1303. // garbage on exit from jitted loop bodies.
  1304. while (pnode)
  1305. {
  1306. switch (pnode->nop)
  1307. {
  1308. case knopFncDecl:
  1309. {
  1310. // If this is a block-scoped function, initialize it.
  1311. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1312. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1313. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1314. {
  1315. Symbol *sym = pnodeName->sym;
  1316. Assert(sym);
  1317. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1318. sym->GetScope()->IsBlockScope(funcInfo) &&
  1319. sym->GetScope()->GetFunc() == funcInfo)
  1320. {
  1321. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1322. }
  1323. }
  1324. // No need to recurse to the nested scopes, as they belong to a nested function.
  1325. pnode = pnodeFnc->pnodeNext;
  1326. break;
  1327. }
  1328. case knopBlock:
  1329. {
  1330. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1331. Scope *scope = pnodeBlock->scope;
  1332. if (scope)
  1333. {
  1334. if (scope->IsBlockScope(funcInfo))
  1335. {
  1336. Js::RegSlot scopeLoc = scope->GetLocation();
  1337. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1338. {
  1339. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1340. }
  1341. }
  1342. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1343. {
  1344. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1345. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1346. {
  1347. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1348. }
  1349. };
  1350. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1351. }
  1352. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1353. pnode = pnodeBlock->pnodeNext;
  1354. break;
  1355. }
  1356. case knopCatch:
  1357. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1358. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1359. break;
  1360. case knopWith:
  1361. {
  1362. Js::RegSlot withLoc = pnode->location;
  1363. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1364. "We should put with objects at known stack locations in debug mode");
  1365. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1366. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1367. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1368. break;
  1369. }
  1370. default:
  1371. Assert(false);
  1372. return;
  1373. }
  1374. }
  1375. }
  1376. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1377. {
  1378. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1379. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1380. {
  1381. return;
  1382. }
  1383. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1384. uint slotCount = currentScope->GetScopeSlotCount();
  1385. uint cachedFuncCount = 0;
  1386. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1387. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1388. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1389. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1390. // Create and fill the array of local property ID's.
  1391. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1392. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1393. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1394. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1395. {
  1396. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1397. }
  1398. if (funcInfo->GetHasArguments())
  1399. {
  1400. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1401. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1402. Js::PropertyId slot = 0;
  1403. auto initArg = [&](ParseNode *pnode)
  1404. {
  1405. if (pnode->IsVarLetOrConst())
  1406. {
  1407. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1408. Assert(sym);
  1409. if (sym->GetScopeSlot() == slot)
  1410. {
  1411. // This is the last appearance of the formal, so record the ID.
  1412. Symbol::SaveToPropIdArray(sym, propIds, this);
  1413. }
  1414. else
  1415. {
  1416. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1417. // since this slot can't be accessed by name.
  1418. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1419. propIds->elements[slot] = Js::Constants::NoProperty;
  1420. }
  1421. }
  1422. else
  1423. {
  1424. // This is for patterns
  1425. propIds->elements[slot] = Js::Constants::NoProperty;
  1426. }
  1427. slot++;
  1428. };
  1429. MapFormalsWithoutRest(pnodeFnc, initArg);
  1430. ParseNodePtr rest = pnodeFnc->pnodeRest;
  1431. if (rest != nullptr && rest->IsVarLetOrConst())
  1432. {
  1433. // If the rest is in the slot - we need to keep that slot.
  1434. Symbol *sym = rest->AsParseNodeVar()->sym;
  1435. if (sym->IsInSlot(this, funcInfo))
  1436. {
  1437. Symbol::SaveToPropIdArray(sym, propIds, this);
  1438. }
  1439. }
  1440. }
  1441. else
  1442. {
  1443. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1444. {
  1445. if (pnode->IsVarLetOrConst())
  1446. {
  1447. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1448. }
  1449. });
  1450. }
  1451. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1452. {
  1453. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1454. {
  1455. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1456. if (pnodeName != nullptr)
  1457. {
  1458. while (pnodeName->nop == knopList)
  1459. {
  1460. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1461. {
  1462. Symbol *sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1463. if (sym)
  1464. {
  1465. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1466. }
  1467. }
  1468. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1469. }
  1470. if (pnodeName->nop == knopVarDecl)
  1471. {
  1472. Symbol *sym = pnodeName->AsParseNodeVar()->sym;
  1473. if (sym)
  1474. {
  1475. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1476. cachedFuncCount++;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. };
  1482. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1483. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1484. {
  1485. ParseNode *pnode;
  1486. Symbol *sym;
  1487. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1488. {
  1489. sym = pnode->AsParseNodeVar()->sym;
  1490. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1491. {
  1492. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1493. {
  1494. sym = currentScope->FindLocalSymbol(sym->GetName());
  1495. }
  1496. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1497. }
  1498. }
  1499. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1500. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1501. {
  1502. sym = pnode->AsParseNodeVar()->sym;
  1503. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1504. }
  1505. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1506. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1507. {
  1508. sym = pnode->AsParseNodeVar()->sym;
  1509. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1510. }
  1511. }
  1512. else
  1513. {
  1514. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1515. }
  1516. // Write the first func slot and first var slot into the auxiliary data
  1517. Js::PropertyId *slots = propIds->elements + slotCount;
  1518. slots[0] = cachedFuncCount;
  1519. slots[1] = firstFuncSlot;
  1520. slots[2] = firstVarSlot;
  1521. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1522. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1523. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1524. }
  1525. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1526. {
  1527. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1528. {
  1529. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1530. }
  1531. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1532. {
  1533. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1534. byteCodeFunction->SetHasScopeObject(true);
  1535. }
  1536. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1537. {
  1538. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1539. }
  1540. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1541. {
  1542. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1543. }
  1544. }
  1545. void ByteCodeGenerator::FinalizeRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1546. {
  1547. if (funcInfo->NeedEnvRegister())
  1548. {
  1549. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1550. funcInfo->AssignEnvRegister(constReg);
  1551. }
  1552. // Set the function body's constant count before emitting anything so that the byte code writer
  1553. // can distinguish constants from variables.
  1554. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1555. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1556. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1557. {
  1558. // Give permanent registers to the inner scopes in debug mode.
  1559. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1560. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1561. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1562. // EmitOneFunction.
  1563. uint innerScopeCount = funcInfo->InnerScopeCount();
  1564. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1565. if (innerScopeCount)
  1566. {
  1567. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1568. for (uint i = 1; i < innerScopeCount; i++)
  1569. {
  1570. funcInfo->NextVarRegister();
  1571. }
  1572. }
  1573. }
  1574. // NOTE: The FunctionBody expects the yield reg to be the final non-temp.
  1575. if (byteCodeFunction->IsCoroutine())
  1576. {
  1577. if (funcInfo->root->IsAsync())
  1578. {
  1579. funcInfo->AssignAwaitRegister();
  1580. }
  1581. funcInfo->AssignYieldRegister();
  1582. }
  1583. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1584. funcInfo->SetFirstTmpReg(firstTmpReg);
  1585. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1586. }
  1587. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1588. {
  1589. // Record slots info for ScopeSlots/ScopeObject.
  1590. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1591. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1592. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1593. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1594. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1595. {
  1596. return;
  1597. }
  1598. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1599. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1600. {
  1601. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1602. }
  1603. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1604. if (scopeSlotCount)
  1605. {
  1606. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1607. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1608. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1609. "The slot array size is different between debug and non-debug mode");
  1610. #if DEBUG
  1611. for (UINT i = 0; i < scopeSlotCount; i++)
  1612. {
  1613. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1614. }
  1615. #endif
  1616. auto setPropertyIdForScopeSlotArray =
  1617. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1618. (Js::PropertyId slot, Js::PropertyId propId)
  1619. {
  1620. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1621. {
  1622. Js::Throw::FatalInternalError();
  1623. }
  1624. propertyIdsForScopeSlotArray[slot] = propId;
  1625. };
  1626. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1627. {
  1628. if (sym->NeedsSlotAlloc(this, funcInfo))
  1629. {
  1630. // All properties should get correct propertyId here.
  1631. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1632. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1633. }
  1634. };
  1635. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1636. #if DEBUG
  1637. for (UINT i = 0; i < scopeSlotCount; i++)
  1638. {
  1639. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1640. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1641. }
  1642. #endif
  1643. }
  1644. }
  1645. // temporarily load all constants and special registers in a single block
  1646. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1647. {
  1648. Symbol *sym;
  1649. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1650. byteCodeFunction->CreateConstantTable();
  1651. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1652. {
  1653. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1654. }
  1655. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1656. {
  1657. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1658. }
  1659. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1660. {
  1661. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1662. }
  1663. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1664. {
  1665. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1666. }
  1667. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1668. {
  1669. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1670. if (!funcInfo->GetApplyEnclosesArgs())
  1671. {
  1672. this->EmitScopeObjectInit(funcInfo);
  1673. }
  1674. #if DBG
  1675. uint count = 0;
  1676. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1677. {
  1678. if (sym->NeedsSlotAlloc(this, funcInfo))
  1679. {
  1680. // All properties should get correct propertyId here.
  1681. count++;
  1682. }
  1683. });
  1684. if (funcInfo->GetParamScope() != nullptr)
  1685. {
  1686. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1687. {
  1688. if (sym->NeedsSlotAlloc(this, funcInfo))
  1689. {
  1690. // All properties should get correct propertyId here.
  1691. count++;
  1692. }
  1693. });
  1694. }
  1695. // A reparse should result in the same size of the activation object.
  1696. // Exclude functions which were created from the ByteCodeCache.
  1697. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1698. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1699. "The activation object size is different between debug and non-debug mode");
  1700. byteCodeFunction->scopeObjectSize = count;
  1701. #endif
  1702. }
  1703. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1704. {
  1705. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1706. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1707. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1708. {
  1709. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1710. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1711. }
  1712. }
  1713. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1714. {
  1715. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1716. byteCodeFunction->SetEnvDepth((uint16)-1);
  1717. }
  1718. bool thisLoadedFromParams = false;
  1719. if (funcInfo->NeedEnvRegister())
  1720. {
  1721. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1722. if (funcInfo->GetIsTopLevelEventHandler())
  1723. {
  1724. if (funcInfo->GetThisSymbol())
  1725. {
  1726. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1727. }
  1728. // The environment is the namespace hierarchy starting with "this".
  1729. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1730. thisLoadedFromParams = true;
  1731. this->InvalidateCachedOuterScopes(funcInfo);
  1732. }
  1733. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1734. {
  1735. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1736. if (funcInfo->GetIsStrictMode())
  1737. {
  1738. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1739. }
  1740. else
  1741. {
  1742. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1743. }
  1744. }
  1745. else
  1746. {
  1747. // environment may be required to load "this"
  1748. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1749. this->InvalidateCachedOuterScopes(funcInfo);
  1750. }
  1751. }
  1752. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1753. {
  1754. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1755. }
  1756. this->RecordAllIntConstants(funcInfo);
  1757. this->RecordAllStrConstants(funcInfo);
  1758. this->RecordAllBigIntConstants(funcInfo);
  1759. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1760. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1761. {
  1762. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1763. });
  1764. // WARNING !!!
  1765. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1766. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1767. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1768. if (funcInfo->GetHasArguments())
  1769. {
  1770. sym = funcInfo->GetArgumentsSymbol();
  1771. Assert(sym);
  1772. Assert(funcInfo->GetHasHeapArguments());
  1773. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1774. {
  1775. this->LoadHeapArguments(funcInfo);
  1776. }
  1777. }
  1778. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1779. {
  1780. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1781. if (count != 0)
  1782. {
  1783. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1784. GetFormalArgsArray(this, funcInfo, propIds);
  1785. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1786. }
  1787. }
  1788. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1789. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1790. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1791. if (funcInfo->IsClassConstructor())
  1792. {
  1793. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1794. }
  1795. // new.target may be used to construct the 'this' register so make sure to load it first
  1796. if (funcInfo->GetNewTargetSymbol())
  1797. {
  1798. this->LoadNewTargetObject(funcInfo);
  1799. }
  1800. if (funcInfo->GetThisSymbol())
  1801. {
  1802. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1803. }
  1804. else if (ShouldLoadConstThis(funcInfo))
  1805. {
  1806. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1807. }
  1808. if (funcInfo->GetSuperSymbol())
  1809. {
  1810. this->LoadSuperObject(funcInfo);
  1811. }
  1812. if (funcInfo->GetSuperConstructorSymbol())
  1813. {
  1814. this->LoadSuperConstructorObject(funcInfo);
  1815. }
  1816. if (funcInfo->GetImportMetaSymbol())
  1817. {
  1818. this->LoadImportMetaObject(funcInfo);
  1819. }
  1820. //
  1821. // If the function is a function expression with a name,
  1822. // load the function object at runtime to its activation object.
  1823. //
  1824. sym = funcInfo->root->GetFuncSymbol();
  1825. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1826. if (funcExprWithName)
  1827. {
  1828. if (funcInfo->GetFuncExprNameReference() ||
  1829. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1830. {
  1831. //
  1832. // x = function f(...) { ... }
  1833. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1834. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1835. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1836. // scope's register namespace. So use a tmp register.
  1837. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1838. // from it's register namespace, which LdFuncExpr can use.
  1839. //
  1840. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1841. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1842. if (sym->IsInSlot(this, funcInfo))
  1843. {
  1844. Js::RegSlot scopeLocation;
  1845. AnalysisAssert(funcInfo->funcExprScope);
  1846. if (funcInfo->funcExprScope->GetIsObject())
  1847. {
  1848. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1849. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1850. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1851. }
  1852. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1853. {
  1854. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1855. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1856. }
  1857. else
  1858. {
  1859. Assert(sym->HasScopeSlot());
  1860. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1861. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1862. }
  1863. }
  1864. else if (ShouldTrackDebuggerMetadata())
  1865. {
  1866. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1867. }
  1868. }
  1869. }
  1870. }
  1871. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1872. {
  1873. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1874. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1875. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1876. uint32 envIndex = 0;
  1877. while (scope && scope->GetFunc() == funcInfo)
  1878. {
  1879. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1880. scope = scope->GetEnclosingScope();
  1881. }
  1882. for (; scope; scope = scope->GetEnclosingScope())
  1883. {
  1884. FuncInfo *func = scope->GetFunc();
  1885. if (scope == func->GetBodyScope())
  1886. {
  1887. if (func->Escapes() && func->GetHasCachedScope())
  1888. {
  1889. AssertOrFailFast(scope->GetIsObject());
  1890. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1891. }
  1892. }
  1893. if (scope->GetMustInstantiate())
  1894. {
  1895. envIndex++;
  1896. }
  1897. }
  1898. }
  1899. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1900. {
  1901. Symbol* thisSym = funcInfo->GetThisSymbol();
  1902. Assert(thisSym);
  1903. Assert(!funcInfo->IsLambda());
  1904. if (funcInfo->IsClassConstructor())
  1905. {
  1906. // Derived class constructors initialize 'this' to be Undecl
  1907. // - we'll check this value during a super call and during 'this' access
  1908. //
  1909. // Base class constructors initialize 'this' to a new object using new.target
  1910. if (funcInfo->IsBaseClassConstructor())
  1911. {
  1912. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1913. Assert(newTargetSym);
  1914. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1915. }
  1916. else
  1917. {
  1918. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1919. }
  1920. }
  1921. else if (!funcInfo->IsGlobalFunction())
  1922. {
  1923. //
  1924. // thisLoadedFromParams would be true for the event Handler case,
  1925. // "this" would have been loaded from parameters to put in the environment
  1926. //
  1927. if (funcInfo->GetIsStrictMode())
  1928. {
  1929. m_writer.ArgIn0(thisSym->GetLocation());
  1930. }
  1931. else if (!thisLoadedFromParams)
  1932. {
  1933. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1934. m_writer.ArgIn0(tmpReg);
  1935. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1936. funcInfo->ReleaseTmpRegister(tmpReg);
  1937. }
  1938. else
  1939. {
  1940. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1941. }
  1942. }
  1943. else
  1944. {
  1945. Assert(funcInfo->IsGlobalFunction());
  1946. Js::RegSlot root = funcInfo->nullConstantRegister;
  1947. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1948. }
  1949. }
  1950. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1951. {
  1952. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1953. Assert(newTargetSym);
  1954. if (funcInfo->IsClassConstructor())
  1955. {
  1956. Assert(!funcInfo->IsLambda());
  1957. m_writer.ArgIn0(newTargetSym->GetLocation());
  1958. }
  1959. else if (funcInfo->IsGlobalFunction())
  1960. {
  1961. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1962. }
  1963. else
  1964. {
  1965. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1966. }
  1967. }
  1968. void ByteCodeGenerator::LoadImportMetaObject(FuncInfo* funcInfo)
  1969. {
  1970. Symbol* importMetaSym = funcInfo->GetImportMetaSymbol();
  1971. Assert(importMetaSym);
  1972. m_writer.Reg1Unsigned1(Js::OpCode::LdImportMeta, importMetaSym->GetLocation(), this->GetModuleID());
  1973. }
  1974. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1975. {
  1976. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1977. Assert(superConstructorSym);
  1978. Assert(!funcInfo->IsLambda());
  1979. if (funcInfo->IsDerivedClassConstructor())
  1980. {
  1981. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1982. }
  1983. else
  1984. {
  1985. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1986. }
  1987. }
  1988. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1989. {
  1990. Symbol* superSym = funcInfo->GetSuperSymbol();
  1991. Assert(superSym);
  1992. Assert(!funcInfo->IsLambda());
  1993. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1994. }
  1995. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue, BOOL fEvaluateComponents)
  1996. {
  1997. FuncInfo* nonLambdaFunc = funcInfo;
  1998. bool isResultUsed = pnodeSuperCall->isUsed;
  1999. if (funcInfo->IsLambda())
  2000. {
  2001. nonLambdaFunc = this->FindEnclosingNonLambda();
  2002. }
  2003. if (nonLambdaFunc->IsBaseClassConstructor())
  2004. {
  2005. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  2006. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  2007. return;
  2008. }
  2009. pnodeSuperCall->isUsed = true;
  2010. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  2011. // and the result of the super() expression itself
  2012. funcInfo->AcquireLoc(pnodeSuperCall);
  2013. // 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)
  2014. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  2015. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  2016. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  2017. Assert(pnodeSuperCall->isSuperCall);
  2018. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  2019. //
  2020. // if (super is class constructor) {
  2021. // _this = new.target;
  2022. // } else {
  2023. // _this = NewScObjFull(new.target);
  2024. // }
  2025. //
  2026. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2027. // if (temp is object) {
  2028. // _this = temp;
  2029. // }
  2030. //
  2031. // if (UndeclBlockVar === this) {
  2032. // this = _this;
  2033. // } else {
  2034. // throw ReferenceError;
  2035. // }
  2036. //
  2037. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2038. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2039. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2040. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2041. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2042. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2043. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2044. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2045. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2046. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2047. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2048. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2049. this->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2050. this->Writer()->MarkLabel(makeCallLabel);
  2051. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, fEvaluateComponents, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2052. // We have to use another temp for the this value before assigning to this register.
  2053. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2054. // Ex:
  2055. // _this = new.target;
  2056. // temp = super.call(_this);
  2057. // if (temp is object) {
  2058. // _this = temp; // creates a new sym for _this as it was previously used
  2059. // }
  2060. // this = _this; // tries to loads a value from the old sym (which is dead)
  2061. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2062. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2063. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2064. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2065. this->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueForThis, pnodeSuperCall->location);
  2066. this->Writer()->MarkLabel(doneLabel);
  2067. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2068. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2069. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2070. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2071. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2072. this->Writer()->MarkLabel(skipLabel);
  2073. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2074. if (isResultUsed)
  2075. {
  2076. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2077. }
  2078. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2079. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->pnodeThis->location, valueForThis);
  2080. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2081. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2082. funcInfo->ReleaseTmpRegister(valueForThis);
  2083. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2084. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2085. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2086. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2087. }
  2088. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2089. {
  2090. Symbol* thisSym = funcInfo->GetThisSymbol();
  2091. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2092. {
  2093. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2094. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2095. }
  2096. }
  2097. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2098. {
  2099. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2100. {
  2101. if (lhsLocation != fromRegister)
  2102. {
  2103. m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, fromRegister);
  2104. }
  2105. }
  2106. else
  2107. {
  2108. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2109. }
  2110. }
  2111. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2112. {
  2113. if (pnodeFormal->IsVarLetOrConst())
  2114. {
  2115. // Get the param from its argument position into its assigned register.
  2116. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2117. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2118. if (formal->GetLocation() + 1 == pos)
  2119. {
  2120. // Transfer to the frame object, etc., if necessary.
  2121. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2122. }
  2123. }
  2124. }
  2125. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2126. {
  2127. if (ShouldTrackDebuggerMetadata())
  2128. {
  2129. // Add formals to the debugger propertyidcontainer for reg slots
  2130. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2131. {
  2132. if (pnodeFormal->IsVarLetOrConst())
  2133. {
  2134. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2135. if (!formal->IsInSlot(this, funcInfo))
  2136. {
  2137. Assert(!formal->GetHasInit());
  2138. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2139. }
  2140. }
  2141. };
  2142. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2143. }
  2144. // Transfer formal parameters to their home locations on the local frame.
  2145. if (funcInfo->GetHasArguments())
  2146. {
  2147. ParseNodePtr rest = funcInfo->root->pnodeRest;
  2148. if (rest != nullptr && rest->IsVarLetOrConst())
  2149. {
  2150. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2151. Symbol* sym = rest->AsParseNodeVar()->sym;
  2152. EmitLoadFormalIntoRegister(rest, sym->GetLocation() + 1, funcInfo);
  2153. }
  2154. // The arguments object creation helper does this work for us.
  2155. return;
  2156. }
  2157. Js::ArgSlot pos = 1;
  2158. auto loadFormal = [&](ParseNode *pnodeFormal)
  2159. {
  2160. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2161. pos++;
  2162. };
  2163. MapFormals(funcInfo->root, loadFormal);
  2164. }
  2165. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2166. {
  2167. funcInfo->singleExit = m_writer.DefineLabel();
  2168. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2169. while (iter.Next())
  2170. {
  2171. ParseNodeStmt * node = iter.Data();
  2172. node->breakLabel = m_writer.DefineLabel();
  2173. node->continueLabel = m_writer.DefineLabel();
  2174. node->emitLabels = true;
  2175. }
  2176. }
  2177. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2178. {
  2179. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2180. // return value.
  2181. ParseNode *pnode = funcInfo->root->pnodeBody;
  2182. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2183. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2184. {
  2185. // We're not guaranteed to compute any values, so fix up the return register at the top
  2186. // in case.
  2187. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2188. }
  2189. while (pnode->nop == knopList)
  2190. {
  2191. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2192. if (stmt == pnodeLastVal)
  2193. {
  2194. pnodeLastVal = nullptr;
  2195. }
  2196. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2197. {
  2198. EmitTopLevelStatement(stmt, funcInfo, true);
  2199. }
  2200. else
  2201. {
  2202. // Haven't hit the post-dominating return value yet,
  2203. // so don't bother with the return register.
  2204. EmitTopLevelStatement(stmt, funcInfo, false);
  2205. }
  2206. pnode = pnode->AsParseNodeBin()->pnode2;
  2207. }
  2208. EmitTopLevelStatement(pnode, funcInfo, false);
  2209. }
  2210. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2211. {
  2212. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2213. // get copied to the return register.
  2214. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2215. ParseNode *pnode = pnodeBody;
  2216. while (pnode->nop == knopList)
  2217. {
  2218. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2219. if (stmt->CapturesSyms())
  2220. {
  2221. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2222. SList<Symbol*> *list = map->Item(stmt);
  2223. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2224. {
  2225. if (!sym->GetIsCommittedToSlot())
  2226. {
  2227. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2228. sym->SetIsCommittedToSlot();
  2229. ParseNode *decl = sym->GetDecl();
  2230. Assert(decl);
  2231. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2232. {
  2233. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2234. sym->GetName().GetBuffer());
  2235. Output::Flush();
  2236. }
  2237. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2238. // what is this doing? Why are we assigning sym to itself?
  2239. bool old = sym->GetNeedDeclaration();
  2240. sym->SetNeedDeclaration(false);
  2241. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2242. sym->SetNeedDeclaration(old);
  2243. }
  2244. }
  2245. NEXT_SLIST_ENTRY;
  2246. }
  2247. EmitTopLevelStatement(stmt, funcInfo, false);
  2248. pnode = pnode->AsParseNodeBin()->pnode2;
  2249. }
  2250. Assert(!pnode->CapturesSyms());
  2251. EmitTopLevelStatement(pnode, funcInfo, false);
  2252. }
  2253. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2254. {
  2255. // Indicate that the binding phase is over.
  2256. this->isBinding = false;
  2257. this->trackEnvDepth = true;
  2258. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2259. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2260. // Use the temp allocator in bytecode write temp buffer.
  2261. m_writer.InitData(this->alloc, initSize);
  2262. #ifdef LOG_BYTECODE_AST_RATIO
  2263. // log the max Ast size
  2264. Output::Print(_u("Max Ast size: %d"), initSize);
  2265. #endif
  2266. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2267. if (this->parentScopeInfo)
  2268. {
  2269. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2270. // Start emitting with the nested scope (i.e., the deferred function).
  2271. this->EmitScopeList(pnodeProg->pnodeScopes);
  2272. }
  2273. else
  2274. {
  2275. this->EmitScopeList(pnodeProg);
  2276. }
  2277. }
  2278. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2279. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2280. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2281. {
  2282. Js::DebuggerScope *debuggerScope = nullptr;
  2283. auto processArg = [&](ParseNode *pnodeArg) {
  2284. if (pnodeArg->IsVarLetOrConst())
  2285. {
  2286. if (debuggerScope == nullptr)
  2287. {
  2288. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2289. debuggerScope->SetBegin(beginOffset);
  2290. }
  2291. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2292. }
  2293. };
  2294. MapFormals(pnodeFnc, processArg);
  2295. MapFormalsFromPattern(pnodeFnc, processArg);
  2296. if (debuggerScope != nullptr)
  2297. {
  2298. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2299. {
  2300. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2301. }
  2302. RecordEndScopeObject(pnodeFnc);
  2303. }
  2304. }
  2305. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2306. {
  2307. if (sym)
  2308. {
  2309. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2310. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2311. Js::RegSlot location = sym->GetLocation();
  2312. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2313. {
  2314. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2315. location = funcBody->MapRegSlot(location);
  2316. }
  2317. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2318. }
  2319. }
  2320. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2321. {
  2322. uint beginOffset = m_writer.GetCurrentOffset();
  2323. MapFormals(pnodeFnc, [&](ParseNode *pnodeArg)
  2324. {
  2325. if (pnodeArg->nop == knopParamPattern)
  2326. {
  2327. this->StartStatement(pnodeArg);
  2328. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2329. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2330. if (pnode1->IsPattern())
  2331. {
  2332. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2333. }
  2334. else
  2335. {
  2336. Assert(pnode1->nop == knopAsg);
  2337. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2338. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2339. pnodeArg->AsParseNodeParamPattern()->location,
  2340. pnode1->AsParseNodeBin()->pnode2,
  2341. false /*isNonPatternAssignmentTarget*/,
  2342. this,
  2343. funcInfo);
  2344. }
  2345. this->EndStatement(pnodeArg);
  2346. return;
  2347. }
  2348. else if (pnodeArg->IsVarLetOrConst())
  2349. {
  2350. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2351. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2352. {
  2353. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2354. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2355. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2356. return;
  2357. }
  2358. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2359. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2360. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2361. this->StartStatement(pnodeArg);
  2362. // Let us use strict not equal to differentiate between null and undefined
  2363. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2364. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2365. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2366. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2367. {
  2368. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2369. m_writer.Br(endLabel);
  2370. }
  2371. else
  2372. {
  2373. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2374. }
  2375. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2376. m_writer.MarkLabel(noDefaultLabel);
  2377. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2378. {
  2379. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2380. m_writer.MarkLabel(endLabel);
  2381. }
  2382. this->EndStatement(pnodeArg);
  2383. }
  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_callApplyCallSiteCount = 0;
  2543. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2544. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2545. this->inPrologue = true;
  2546. Scope* paramScope = funcInfo->GetParamScope();
  2547. Scope* bodyScope = funcInfo->GetBodyScope();
  2548. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2549. LoadAllConstants(funcInfo);
  2550. HomeArguments(funcInfo);
  2551. if (funcInfo->root->IsAsync())
  2552. {
  2553. Writer()->Reg1(Js::OpCode::NewAwaitObject, funcInfo->awaitRegister);
  2554. }
  2555. if (!funcInfo->IsBodyAndParamScopeMerged())
  2556. {
  2557. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2558. // Pop the body scope before emitting the default args
  2559. PopScope();
  2560. Assert(this->GetCurrentScope() == paramScope);
  2561. }
  2562. if (funcInfo->root->pnodeRest != nullptr)
  2563. {
  2564. byteCodeFunction->SetHasRestParameter();
  2565. }
  2566. if (funcInfo->IsGlobalFunction())
  2567. {
  2568. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2569. }
  2570. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2571. DefineLabels(funcInfo);
  2572. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2573. // argument expressions reference those special names.
  2574. if (pnodeFnc->HasNonSimpleParameterList())
  2575. {
  2576. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2577. // need to walk over the var list.
  2578. if (funcInfo->IsBodyAndParamScopeMerged())
  2579. {
  2580. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2581. {
  2582. #if DBG
  2583. bool reachedEndOfSpecialSymbols = false;
  2584. #endif
  2585. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2586. if (sym != nullptr && sym->IsSpecialSymbol())
  2587. {
  2588. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2589. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2590. {
  2591. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2592. }
  2593. }
  2594. else
  2595. {
  2596. #if DBG
  2597. reachedEndOfSpecialSymbols = true;
  2598. #else
  2599. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2600. // so we can quit walking at the first non-special one we see.
  2601. break;
  2602. #endif
  2603. }
  2604. #if DBG
  2605. if (reachedEndOfSpecialSymbols)
  2606. {
  2607. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2608. }
  2609. #endif
  2610. }
  2611. }
  2612. else
  2613. {
  2614. paramScope->ForEachSymbol([&](Symbol* sym) {
  2615. if (sym && sym->IsSpecialSymbol())
  2616. {
  2617. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2618. }
  2619. });
  2620. }
  2621. }
  2622. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2623. {
  2624. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2625. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2626. EmitDefaultArgs(funcInfo, pnodeFnc);
  2627. if (!funcInfo->IsBodyAndParamScopeMerged())
  2628. {
  2629. Assert(this->GetCurrentScope() == paramScope);
  2630. // Push the body scope
  2631. PushScope(bodyScope);
  2632. funcInfo->SetCurrentChildScope(bodyScope);
  2633. // Mark the beginning of the body scope so that new scope slots can be created.
  2634. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2635. }
  2636. }
  2637. DefineUserVars(funcInfo);
  2638. // Emit all scope-wide function definitions before emitting function bodies
  2639. // so that calls may reference functions they precede lexically.
  2640. // Note, global eval scope is a fake local scope and is handled as if it were
  2641. // a lexical block instead of a true global scope, so do not define the functions
  2642. // here. They will be defined during BeginEmitBlock.
  2643. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2644. {
  2645. // This only handles function declarations, which param scope cannot have any.
  2646. DefineFunctions(funcInfo);
  2647. }
  2648. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2649. // (that is when the function is called). So insert an extra yield we can execute up to, to do this.
  2650. // In a Module we execute until this yield to hoist functions accross modules.
  2651. if (pnodeFnc->IsGenerator() && (pnodeFnc->HasNonSimpleParameterList() || pnodeFnc->IsModule()))
  2652. {
  2653. EmitStartupYield(this, funcInfo);
  2654. }
  2655. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2656. {
  2657. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2658. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2659. }
  2660. else
  2661. {
  2662. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2663. }
  2664. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2665. {
  2666. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2667. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2668. }
  2669. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2670. if (!funcInfo->IsBodyAndParamScopeMerged())
  2671. {
  2672. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2673. // We have to do this after the rest param is marked as false for need declaration.
  2674. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2675. paramScope->ForEachSymbol([&](Symbol* param) {
  2676. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2677. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2678. // is expected to stay inside the function expression scope
  2679. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2680. {
  2681. if (!varSym->GetNeedDeclaration())
  2682. {
  2683. if (param->IsInSlot(this, funcInfo))
  2684. {
  2685. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2686. // Walking the scope chain is not possible at this time.
  2687. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2688. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2689. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2690. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2691. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2692. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2693. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2694. funcInfo->ReleaseTmpRegister(tempReg);
  2695. }
  2696. else if (param->GetLocation() != Js::Constants::NoRegister)
  2697. {
  2698. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2699. }
  2700. else
  2701. {
  2702. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2703. }
  2704. }
  2705. else
  2706. {
  2707. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2708. // re-declaration error.
  2709. Assert(param->IsArguments());
  2710. }
  2711. }
  2712. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2713. {
  2714. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2715. {
  2716. formalsUpperBound = param->GetLocation();
  2717. }
  2718. }
  2719. });
  2720. }
  2721. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2722. {
  2723. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2724. }
  2725. if (pnodeFnc->pnodeBodyScope != nullptr)
  2726. {
  2727. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2728. }
  2729. this->inPrologue = false;
  2730. if (funcInfo->IsGlobalFunction())
  2731. {
  2732. EmitGlobalBody(funcInfo);
  2733. }
  2734. else
  2735. {
  2736. EmitFunctionBody(funcInfo);
  2737. }
  2738. if (pnodeFnc->pnodeBodyScope != nullptr)
  2739. {
  2740. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2741. }
  2742. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2743. if (!this->IsInDebugMode())
  2744. {
  2745. // Release the temp registers that we reserved for inner scopes above.
  2746. if (innerScopeCount)
  2747. {
  2748. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2749. for (uint i = 0; i < innerScopeCount; i++)
  2750. {
  2751. funcInfo->ReleaseTmpRegister(tmpReg);
  2752. tmpReg--;
  2753. }
  2754. }
  2755. }
  2756. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2757. Assert(funcInfo->curTmpReg == firstTmpReg);
  2758. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2759. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2760. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2761. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2762. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2763. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2764. #if DBG_DUMP
  2765. if (PHASE_STATS1(Js::ByteCodePhase))
  2766. {
  2767. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2768. m_writer.ByteCodeDataSize(),
  2769. m_writer.AuxiliaryDataSize(),
  2770. m_writer.AuxiliaryContextDataSize(),
  2771. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2772. funcInfo->name);
  2773. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2774. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2775. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2776. }
  2777. #endif
  2778. this->MapCacheIdsToPropertyIds(funcInfo);
  2779. this->MapReferencedPropertyIds(funcInfo);
  2780. Assert(this->TopFuncInfo() == funcInfo);
  2781. PopFuncInfo(_u("EmitOneFunction"));
  2782. m_writer.SetCallSiteCount(m_callSiteId);
  2783. m_writer.SetCallApplyCallsiteCount(m_callApplyCallSiteCount);
  2784. #if ENABLE_NATIVE_CODEGEN
  2785. if (funcInfo->callSiteToCallApplyCallSiteMap)
  2786. {
  2787. this->MapCallSiteToCallApplyCallSiteMap(funcInfo);
  2788. }
  2789. #endif
  2790. #ifdef LOG_BYTECODE_AST_RATIO
  2791. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2792. #else
  2793. m_writer.End();
  2794. #endif
  2795. }
  2796. catch (...)
  2797. {
  2798. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2799. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2800. byteCodeFunction->ResetByteCodeGenState();
  2801. m_writer.Reset();
  2802. throw;
  2803. }
  2804. #ifdef PERF_HINT
  2805. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2806. {
  2807. if (byteCodeFunction->GetHasTry())
  2808. {
  2809. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2810. }
  2811. if (funcInfo->GetCallsEval())
  2812. {
  2813. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2814. }
  2815. else if (funcInfo->GetChildCallsEval())
  2816. {
  2817. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2818. }
  2819. }
  2820. #endif
  2821. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2822. {
  2823. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2824. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2825. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2826. {
  2827. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2828. {
  2829. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2830. }
  2831. return true;
  2832. });
  2833. }
  2834. byteCodeFunction->SetInitialDefaultEntryPoint();
  2835. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2836. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2837. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2838. {
  2839. if (m_utf8SourceInfo->GetIsLibraryCode())
  2840. {
  2841. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2842. }
  2843. else
  2844. {
  2845. Js::Throw::FatalInternalError();
  2846. }
  2847. }
  2848. #endif
  2849. #if DBG_DUMP
  2850. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2851. {
  2852. pnodeFnc->Dump();
  2853. }
  2854. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2855. {
  2856. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2857. }
  2858. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2859. {
  2860. byteCodeFunction->DumpScopes();
  2861. }
  2862. #endif
  2863. #if ENABLE_NATIVE_CODEGEN
  2864. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2865. && !this->forceNoNative
  2866. && !this->scriptContext->GetConfig()->IsNoNative())
  2867. {
  2868. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2869. }
  2870. #endif
  2871. }
  2872. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2873. {
  2874. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2875. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2876. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2877. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2878. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2879. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2880. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2881. if (totalFieldAccessInlineCacheCount == 0)
  2882. {
  2883. return;
  2884. }
  2885. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2886. {
  2887. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2888. {
  2889. if (inlineCacheList)
  2890. {
  2891. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2892. {
  2893. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2894. if (cacheUnit.loadCacheId != -1)
  2895. {
  2896. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2897. }
  2898. if (cacheUnit.loadMethodCacheId != -1)
  2899. {
  2900. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2901. }
  2902. if (cacheUnit.storeCacheId != -1)
  2903. {
  2904. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2905. }
  2906. });
  2907. }
  2908. });
  2909. });
  2910. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2911. {
  2912. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2913. });
  2914. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2915. {
  2916. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2917. });
  2918. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2919. {
  2920. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2921. });
  2922. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2923. while (valueOfIter.Next())
  2924. {
  2925. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2926. }
  2927. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2928. while (toStringIter.Next())
  2929. {
  2930. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2931. }
  2932. #if DBG
  2933. functionBody->VerifyCacheIdToPropertyIdMap();
  2934. #endif
  2935. }
  2936. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2937. {
  2938. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2939. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2940. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2941. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2942. {
  2943. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2944. });
  2945. #if DBG
  2946. functionBody->VerifyReferencedPropertyIdMap();
  2947. #endif
  2948. }
  2949. #if ENABLE_NATIVE_CODEGEN
  2950. void ByteCodeGenerator::MapCallSiteToCallApplyCallSiteMap(FuncInfo * funcInfo)
  2951. {
  2952. Js::FunctionBody * functionBody = funcInfo->GetParsedFunctionBody();
  2953. if (functionBody->CreateCallSiteToCallApplyCallSiteArray())
  2954. {
  2955. funcInfo->callSiteToCallApplyCallSiteMap->Map([functionBody](Js::ProfileId callSiteId, Js::ProfileId callApplyCallSiteId)
  2956. {
  2957. functionBody->GetCallSiteToCallApplyCallSiteArray()[callSiteId] = callApplyCallSiteId;
  2958. });
  2959. }
  2960. }
  2961. #endif
  2962. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2963. {
  2964. while (pnode)
  2965. {
  2966. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2967. {
  2968. break;
  2969. }
  2970. switch (pnode->nop)
  2971. {
  2972. case knopFncDecl:
  2973. #ifdef ASMJS_PLAT
  2974. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2975. {
  2976. Js::ExclusiveContext context(this, GetScriptContext());
  2977. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2978. {
  2979. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2980. break;
  2981. }
  2982. else if (CONFIG_FLAG(AsmJsStopOnError))
  2983. {
  2984. exit(JSERR_AsmJsCompileError);
  2985. }
  2986. else
  2987. {
  2988. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2989. throw Js::AsmJsParseException();
  2990. }
  2991. }
  2992. #endif
  2993. // FALLTHROUGH
  2994. case knopProg:
  2995. if (pnode->AsParseNodeFnc()->funcInfo)
  2996. {
  2997. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  2998. Scope* paramScope = funcInfo->GetParamScope();
  2999. if (!funcInfo->IsBodyAndParamScopeMerged())
  3000. {
  3001. funcInfo->SetCurrentChildScope(paramScope);
  3002. }
  3003. else
  3004. {
  3005. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  3006. }
  3007. this->StartEmitFunction(pnode->AsParseNodeFnc());
  3008. if (!funcInfo->IsBodyAndParamScopeMerged())
  3009. {
  3010. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  3011. }
  3012. else
  3013. {
  3014. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  3015. }
  3016. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3017. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3018. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3019. funcInfo->SetCurrentChildScope(nullptr);
  3020. }
  3021. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3022. break;
  3023. case knopBlock:
  3024. {
  3025. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3026. this->StartEmitBlock(pnodeBlock);
  3027. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3028. this->EndEmitBlock(pnodeBlock);
  3029. pnode = pnodeBlock->pnodeNext;
  3030. break;
  3031. }
  3032. case knopCatch:
  3033. {
  3034. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3035. this->StartEmitCatch(pnodeCatch);
  3036. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3037. this->EndEmitCatch(pnodeCatch);
  3038. pnode = pnodeCatch->pnodeNext;
  3039. break;
  3040. }
  3041. case knopWith:
  3042. this->StartEmitWith(pnode);
  3043. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3044. this->EndEmitWith(pnode);
  3045. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3046. break;
  3047. default:
  3048. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3049. break;
  3050. }
  3051. }
  3052. }
  3053. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3054. {
  3055. if (pnodeFnc->pnodeName)
  3056. {
  3057. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3058. Symbol *sym = pnodeFnc->pnodeName->sym;
  3059. // If this function is shadowing the arguments symbol in body then skip it.
  3060. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3061. if (sym && !sym->IsArguments())
  3062. {
  3063. sym->EnsureScopeSlot(this, funcInfo);
  3064. }
  3065. }
  3066. }
  3067. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3068. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3069. {
  3070. if (pnodeFnc->pnodeName)
  3071. {
  3072. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3073. Symbol *sym = pnodeFnc->pnodeName->sym;
  3074. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3075. {
  3076. sym->EnsureScopeSlot(this, funcInfo);
  3077. }
  3078. }
  3079. }
  3080. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3081. {
  3082. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3083. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3084. Scope * const bodyScope = funcInfo->GetBodyScope();
  3085. Scope * const paramScope = funcInfo->GetParamScope();
  3086. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3087. {
  3088. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3089. {
  3090. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3091. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3092. }
  3093. if (funcInfo->GetCallsEval())
  3094. {
  3095. funcInfo->byteCodeFunction->SetDontInline(true);
  3096. }
  3097. Scope * const funcExprScope = funcInfo->funcExprScope;
  3098. if (funcExprScope)
  3099. {
  3100. if (funcInfo->GetCallsEval())
  3101. {
  3102. Assert(funcExprScope->GetIsObject());
  3103. }
  3104. if (funcExprScope->GetIsObject())
  3105. {
  3106. funcExprScope->SetCapturesAll(true);
  3107. funcExprScope->SetMustInstantiate(true);
  3108. PushScope(funcExprScope);
  3109. }
  3110. else
  3111. {
  3112. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3113. if (funcInfo->IsBodyAndParamScopeMerged())
  3114. {
  3115. funcInfo->bodyScope->AddSymbol(sym);
  3116. }
  3117. else
  3118. {
  3119. funcInfo->paramScope->AddSymbol(sym);
  3120. }
  3121. sym->EnsureScopeSlot(this, funcInfo);
  3122. if (sym->GetHasNonLocalReference())
  3123. {
  3124. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3125. }
  3126. }
  3127. }
  3128. if (pnodeFnc->nop != knopProg)
  3129. {
  3130. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3131. {
  3132. Assert(bodyScope->GetIsObject());
  3133. }
  3134. if (bodyScope->GetIsObject())
  3135. {
  3136. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3137. }
  3138. else
  3139. {
  3140. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3141. }
  3142. if (!funcInfo->IsBodyAndParamScopeMerged())
  3143. {
  3144. if (paramScope->GetIsObject())
  3145. {
  3146. paramScope->SetLocation(funcInfo->frameObjRegister);
  3147. }
  3148. else
  3149. {
  3150. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3151. }
  3152. }
  3153. if (bodyScope->GetIsObject())
  3154. {
  3155. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3156. funcInfo->SetHasCachedScope(
  3157. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3158. !funcInfo->Escapes() &&
  3159. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3160. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3161. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3162. !pnodeFnc->HasDefaultArguments() &&
  3163. !pnodeFnc->HasDestructuredParams() &&
  3164. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3165. #if ENABLE_TTD
  3166. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3167. #endif
  3168. && !funcInfo->byteCodeFunction->IsCoroutine()
  3169. );
  3170. if (funcInfo->GetHasCachedScope())
  3171. {
  3172. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3173. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3174. if (funcSym && funcSym->GetIsFuncExpr())
  3175. {
  3176. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3177. {
  3178. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3179. }
  3180. else
  3181. {
  3182. funcInfo->funcObjRegister = funcSym->GetLocation();
  3183. }
  3184. }
  3185. else
  3186. {
  3187. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3188. }
  3189. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3190. }
  3191. ParseNode *pnode;
  3192. Symbol *sym;
  3193. if (funcInfo->GetHasArguments())
  3194. {
  3195. // Process function's formal parameters
  3196. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3197. {
  3198. if (pnode->IsVarLetOrConst())
  3199. {
  3200. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3201. }
  3202. });
  3203. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3204. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3205. // doesn't require scope slot for "arguments" because inner functions can't access
  3206. // outer function's arguments directly.
  3207. sym = funcInfo->GetArgumentsSymbol();
  3208. Assert(sym);
  3209. if (sym->NeedsSlotAlloc(this, funcInfo))
  3210. {
  3211. sym->EnsureScopeSlot(this, funcInfo);
  3212. }
  3213. }
  3214. sym = funcInfo->root->GetFuncSymbol();
  3215. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3216. {
  3217. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3218. {
  3219. sym->SetScopeSlot(0);
  3220. }
  3221. else if (funcInfo->GetFuncExprNameReference())
  3222. {
  3223. sym->EnsureScopeSlot(this, funcInfo);
  3224. }
  3225. }
  3226. if (!funcInfo->GetHasArguments())
  3227. {
  3228. Symbol *formal;
  3229. Js::ArgSlot pos = 1;
  3230. auto moveArgToReg = [&](ParseNode *pnode)
  3231. {
  3232. if (pnode->IsVarLetOrConst())
  3233. {
  3234. formal = pnode->AsParseNodeVar()->sym;
  3235. // Get the param from its argument position into its assigned register.
  3236. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3237. if (formal->GetLocation() + 1 == pos)
  3238. {
  3239. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3240. }
  3241. }
  3242. pos++;
  3243. };
  3244. MapFormals(pnodeFnc, moveArgToReg);
  3245. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3246. }
  3247. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3248. {
  3249. sym = pnode->AsParseNodeVar()->sym;
  3250. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3251. {
  3252. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3253. {
  3254. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3255. }
  3256. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3257. {
  3258. sym->EnsureScopeSlot(this, funcInfo);
  3259. }
  3260. }
  3261. }
  3262. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3263. {
  3264. for (pnode = pnodeScope; pnode;)
  3265. {
  3266. switch (pnode->nop)
  3267. {
  3268. case knopFncDecl:
  3269. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3270. {
  3271. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3272. }
  3273. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3274. break;
  3275. case knopBlock:
  3276. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3277. break;
  3278. case knopCatch:
  3279. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3280. break;
  3281. case knopWith:
  3282. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3283. break;
  3284. }
  3285. }
  3286. };
  3287. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3288. if (pnodeFnc->pnodeBody)
  3289. {
  3290. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3291. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3292. }
  3293. }
  3294. else
  3295. {
  3296. ParseNode *pnode;
  3297. Symbol *sym;
  3298. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3299. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3300. {
  3301. sym = pnode->AsParseNodeVar()->sym;
  3302. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3303. {
  3304. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3305. {
  3306. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3307. }
  3308. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3309. {
  3310. sym->EnsureScopeSlot(this, funcInfo);
  3311. }
  3312. }
  3313. }
  3314. auto ensureScopeSlot = [&](ParseNode *pnode)
  3315. {
  3316. if (pnode->IsVarLetOrConst())
  3317. {
  3318. sym = pnode->AsParseNodeVar()->sym;
  3319. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3320. {
  3321. sym->EnsureScopeSlot(this, funcInfo);
  3322. }
  3323. }
  3324. };
  3325. // Process function's formal parameters
  3326. MapFormals(pnodeFnc, ensureScopeSlot);
  3327. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3328. if (funcInfo->GetHasArguments())
  3329. {
  3330. sym = funcInfo->GetArgumentsSymbol();
  3331. Assert(sym);
  3332. // There is no eval so the arguments may be captured in a lambda.
  3333. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3334. sym->EnsureScopeSlot(this, funcInfo);
  3335. }
  3336. if (pnodeFnc->pnodeBody)
  3337. {
  3338. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3339. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3340. }
  3341. }
  3342. // 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.
  3343. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3344. {
  3345. bodyScope->SetMustInstantiate(true);
  3346. }
  3347. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3348. {
  3349. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3350. if (pnodeFnc->IsBodyAndParamScopeMerged() && paramScope && paramScope->GetHasNestedParamFunc())
  3351. {
  3352. paramScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3353. }
  3354. }
  3355. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3356. {
  3357. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3358. {
  3359. paramScope->SetMustInstantiate(true);
  3360. }
  3361. else
  3362. {
  3363. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3364. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3365. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3366. }
  3367. }
  3368. }
  3369. else
  3370. {
  3371. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3372. if (newScopeForEval)
  3373. {
  3374. Assert(bodyScope->GetIsObject());
  3375. }
  3376. }
  3377. }
  3378. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3379. if (!funcInfo->IsBodyAndParamScopeMerged())
  3380. {
  3381. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3382. Assert(paramBlock->blockType == Parameter);
  3383. PushScope(paramScope);
  3384. // While emitting the functions we have to stop when we see the body scope block.
  3385. // Otherwise functions defined in the body scope will not be able to get the right references.
  3386. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3387. Assert(this->GetCurrentScope() == paramScope);
  3388. }
  3389. PushScope(bodyScope);
  3390. }
  3391. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3392. {
  3393. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3394. {
  3395. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3396. }
  3397. else
  3398. {
  3399. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3400. if (opcode == Js::OpCode::LdModuleSlot)
  3401. {
  3402. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3403. }
  3404. }
  3405. }
  3406. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3407. {
  3408. Assert(sym->GetIsModuleExportStorage());
  3409. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3410. {
  3411. return true;
  3412. }
  3413. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3414. library->EnsureModuleRecordList();
  3415. uint moduleIndex = this->GetModuleID();
  3416. uint moduleSlotIndex;
  3417. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3418. if (sym->GetIsModuleImport())
  3419. {
  3420. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3421. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3422. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3423. {
  3424. return false;
  3425. }
  3426. AnalysisAssert(moduleNameRecord != nullptr);
  3427. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3428. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3429. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3430. moduleIndex = resolvedModuleRecord->GetModuleId();
  3431. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3432. }
  3433. else
  3434. {
  3435. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3436. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3437. }
  3438. sym->SetModuleIndex(moduleIndex);
  3439. sym->SetScopeSlot(moduleSlotIndex);
  3440. return true;
  3441. }
  3442. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3443. {
  3444. // We are assigning pnode to the default export of the current module.
  3445. uint moduleIndex = this->GetModuleID();
  3446. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3447. library->EnsureModuleRecordList();
  3448. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3449. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3450. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3451. }
  3452. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3453. {
  3454. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3455. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3456. {
  3457. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3458. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3459. {
  3460. sym->EnsureScopeSlot(this, funcInfo);
  3461. this->ProcessCapturedSym(sym);
  3462. }
  3463. });
  3464. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3465. }
  3466. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3467. {
  3468. while (pnode)
  3469. {
  3470. switch (pnode->nop)
  3471. {
  3472. case knopFncDecl:
  3473. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3474. {
  3475. this->CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3476. }
  3477. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3478. break;
  3479. case knopBlock:
  3480. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3481. break;
  3482. case knopCatch:
  3483. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3484. break;
  3485. case knopWith:
  3486. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3487. break;
  3488. }
  3489. }
  3490. }
  3491. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3492. {
  3493. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3494. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3495. PopScope(); // function body
  3496. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3497. Scope* paramScope = funcInfo->paramScope;
  3498. if (!funcInfo->IsBodyAndParamScopeMerged())
  3499. {
  3500. Assert(this->GetCurrentScope() == paramScope);
  3501. PopScope(); // Pop the param scope
  3502. }
  3503. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3504. {
  3505. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3506. // TODO: Refactor Start and EndEmitFunction for clarity.
  3507. Scope *scope = funcInfo->funcExprScope;
  3508. if (scope && scope->GetMustInstantiate())
  3509. {
  3510. Assert(currentScope == scope);
  3511. PopScope();
  3512. }
  3513. }
  3514. Assert(funcInfo == this->TopFuncInfo());
  3515. PopFuncInfo(_u("EndEmitFunction"));
  3516. }
  3517. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3518. {
  3519. Assert(pnodeCatch->nop == knopCatch);
  3520. Scope *scope = pnodeCatch->scope;
  3521. FuncInfo *funcInfo = scope->GetFunc();
  3522. // 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).
  3523. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3524. {
  3525. scope->SetIsObject();
  3526. }
  3527. if (pnodeCatch->HasPatternParam())
  3528. {
  3529. ParseNode *pnode1 = pnodeCatch->GetParam()->AsParseNodeParamPattern()->pnode1;
  3530. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3531. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3532. Parser::MapBindIdentifier(pnode1, [&](ParseNodePtr item)
  3533. {
  3534. Symbol *sym = item->AsParseNodeVar()->sym;
  3535. if (funcInfo->IsGlobalFunction())
  3536. {
  3537. sym->SetIsGlobalCatch(true);
  3538. }
  3539. if (sym->NeedsScopeObject())
  3540. {
  3541. scope->SetIsObject();
  3542. }
  3543. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3544. if (sym->NeedsSlotAlloc(this, funcInfo))
  3545. {
  3546. sym->EnsureScopeSlot(this, funcInfo);
  3547. }
  3548. });
  3549. }
  3550. else if (pnodeCatch->HasParam())
  3551. {
  3552. Symbol *sym = pnodeCatch->GetParam()->AsParseNodeName()->sym;
  3553. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3554. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3555. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3556. if (funcInfo->IsGlobalFunction())
  3557. {
  3558. sym->SetIsGlobalCatch(true);
  3559. }
  3560. if (sym->NeedsScopeObject())
  3561. {
  3562. scope->SetIsObject();
  3563. }
  3564. if (scope->GetMustInstantiate())
  3565. {
  3566. if (sym->IsInSlot(this, funcInfo))
  3567. {
  3568. // Since there is only one symbol we are pushing to slot.
  3569. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3570. this->ProcessCapturedSym(sym);
  3571. sym->EnsureScopeSlot(this, funcInfo);
  3572. }
  3573. }
  3574. }
  3575. PushScope(scope);
  3576. }
  3577. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3578. {
  3579. Assert(pnodeCatch->nop == knopCatch);
  3580. Assert(currentScope == pnodeCatch->scope);
  3581. PopScope();
  3582. }
  3583. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3584. {
  3585. if (!BlockHasOwnScope(pnodeBlock, this))
  3586. {
  3587. return;
  3588. }
  3589. Assert(pnodeBlock->nop == knopBlock);
  3590. PushBlock(pnodeBlock);
  3591. Scope *scope = pnodeBlock->scope;
  3592. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3593. {
  3594. Assert(scope->GetIsObject());
  3595. }
  3596. // TODO: Consider nested deferred parsing.
  3597. if (scope->GetMustInstantiate())
  3598. {
  3599. FuncInfo *funcInfo = scope->GetFunc();
  3600. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3601. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3602. PushScope(scope);
  3603. }
  3604. }
  3605. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3606. {
  3607. if (!BlockHasOwnScope(pnodeBlock, this))
  3608. {
  3609. return;
  3610. }
  3611. Assert(pnodeBlock->nop == knopBlock);
  3612. Scope *scope = pnodeBlock->scope;
  3613. if (scope && scope->GetMustInstantiate())
  3614. {
  3615. Assert(currentScope == pnodeBlock->scope);
  3616. PopScope();
  3617. }
  3618. PopBlock();
  3619. }
  3620. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3621. {
  3622. Assert(pnodeWith->nop == knopWith);
  3623. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3624. AssertOrFailFast(scope->GetIsObject());
  3625. PushScope(scope);
  3626. }
  3627. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3628. {
  3629. Assert(pnodeWith->nop == knopWith);
  3630. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3631. PopScope();
  3632. }
  3633. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3634. {
  3635. Scope *currScope = this->currentScope;
  3636. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3637. if (currScope == funcScope)
  3638. {
  3639. return evalEnv;
  3640. }
  3641. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3642. if (acquireTempLoc)
  3643. {
  3644. tempLoc = funcInfo->AcquireTmpRegister();
  3645. }
  3646. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3647. // but the list must first be reversed so that innermost scopes appear first in the list.
  3648. while (currScope != funcScope)
  3649. {
  3650. Scope *innerScope;
  3651. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3652. ;
  3653. if (innerScope->GetMustInstantiate())
  3654. {
  3655. if (!innerScope->HasInnerScopeIndex())
  3656. {
  3657. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3658. {
  3659. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3660. }
  3661. else
  3662. {
  3663. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3664. }
  3665. }
  3666. else
  3667. {
  3668. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3669. {
  3670. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3671. }
  3672. else
  3673. {
  3674. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3675. }
  3676. }
  3677. evalEnv = tempLoc;
  3678. }
  3679. funcScope = innerScope;
  3680. }
  3681. if (acquireTempLoc)
  3682. {
  3683. funcInfo->ReleaseTmpRegister(tempLoc);
  3684. }
  3685. return evalEnv;
  3686. }
  3687. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3688. {
  3689. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3690. Js::RegSlot thisLocation = *pThisLocation;
  3691. Js::RegSlot instLocation = *pInstLocation;
  3692. Js::PropertyId envIndex = -1;
  3693. Scope *scope = nullptr;
  3694. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3695. Assert(symScope);
  3696. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3697. {
  3698. *pInstLocation = Js::Constants::NoRegister;
  3699. return;
  3700. }
  3701. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  3702. for (;;)
  3703. {
  3704. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3705. if (scope == this->globalScope)
  3706. {
  3707. break;
  3708. }
  3709. if (scope != symScope)
  3710. {
  3711. // We're not sure where the function is (eval/with/etc).
  3712. // So we're going to need registers to hold the instance where we (dynamically) find
  3713. // the function, and possibly to hold the "this" pointer we will pass to it.
  3714. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3715. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3716. if (instLocation == Js::Constants::NoRegister)
  3717. {
  3718. instLocation = funcInfo->AcquireTmpRegister();
  3719. }
  3720. }
  3721. if (envIndex == -1)
  3722. {
  3723. Assert(funcInfo == scope->GetFunc());
  3724. scopeLocation = scope->GetLocation();
  3725. }
  3726. if (scope == symScope)
  3727. {
  3728. break;
  3729. }
  3730. // Found a scope to which the property may have been added.
  3731. Assert(scope && scope->GetIsDynamic());
  3732. AssertOrFailFast(scope->GetIsObject());
  3733. // Record dynamic scopes, in order. Define a label for each one. Remember whether we've seen a 'with'.
  3734. // For each dynamic scope, emit BrOnHas[Env,Local]Property $Ln, where n is the scope's position in the list
  3735. // Then emit code for default access (i.e., static binding). If no 'with', do not create a temp for 'this', just use 'undefined'.
  3736. // End static portion with 'Br $Ldone'.
  3737. // Then, for each item in list, emit:
  3738. // $Ln:
  3739. // copy dynamic scope to 'instance' temp, using 'reuse_loc' form of the opcode
  3740. // do the same for 'this' temp', only if we've seen a 'with'
  3741. // if not the last item in the list, Br $Ldone
  3742. DynamicLoadRecord rec;
  3743. rec.label = this->m_writer.DefineLabel();
  3744. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3745. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  3746. if (scope->GetScopeType() != ScopeType_With)
  3747. {
  3748. if (envIndex == -1)
  3749. {
  3750. // The local body scope. Branch cannot bail on implicit calls.
  3751. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  3752. rec.kind = DynamicLoadKind::Local;
  3753. }
  3754. else
  3755. {
  3756. // Function body scope in an enclosing function that calls eval.
  3757. // Emit a branch opcode that does not require bail on implicit calls.
  3758. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  3759. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  3760. rec.kind = DynamicLoadKind::Env;
  3761. rec.index = frameDisplayIndex;
  3762. }
  3763. }
  3764. else
  3765. {
  3766. if (thisLocation == Js::Constants::NoRegister)
  3767. {
  3768. thisLocation = funcInfo->AcquireTmpRegister();
  3769. }
  3770. if (envIndex == -1)
  3771. {
  3772. // With object declared in this function. HasProperty may have implicit calls.
  3773. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  3774. rec.kind = DynamicLoadKind::LocalWith;
  3775. rec.instance = scopeLocation;
  3776. }
  3777. else
  3778. {
  3779. // With object declared in an enclosing function. HasProperty may have implicit calls.
  3780. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  3781. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  3782. rec.kind = DynamicLoadKind::EnvWith;
  3783. rec.index = frameDisplayIndex;
  3784. }
  3785. }
  3786. recList.Add(rec);
  3787. }
  3788. if (sym == nullptr || sym->GetIsGlobal())
  3789. {
  3790. if (this->flags & (fscrEval | fscrImplicitThis))
  3791. {
  3792. // Load of a symbol with unknown scope from within eval.
  3793. // Get it from the closure environment.
  3794. if (instLocation == Js::Constants::NoRegister)
  3795. {
  3796. instLocation = funcInfo->AcquireTmpRegister();
  3797. }
  3798. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3799. if (thisLocation == Js::Constants::NoRegister)
  3800. {
  3801. thisLocation = funcInfo->AcquireTmpRegister();
  3802. }
  3803. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3804. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3805. }
  3806. else
  3807. {
  3808. if (instLocation == Js::Constants::NoRegister)
  3809. {
  3810. instLocation = ByteCodeGenerator::RootObjectRegister;
  3811. }
  3812. else
  3813. {
  3814. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3815. }
  3816. if (thisLocation == Js::Constants::NoRegister)
  3817. {
  3818. thisLocation = funcInfo->undefinedConstantRegister;
  3819. }
  3820. else
  3821. {
  3822. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3823. }
  3824. }
  3825. }
  3826. else if (instLocation != Js::Constants::NoRegister)
  3827. {
  3828. if (envIndex != -1)
  3829. {
  3830. AssertOrFailFast(scope->GetIsObject());
  3831. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3832. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3833. }
  3834. else if (scope->HasInnerScopeIndex())
  3835. {
  3836. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3837. }
  3838. else if (symScope == funcInfo->GetParamScope())
  3839. {
  3840. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3841. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3842. }
  3843. else if (symScope != funcInfo->GetBodyScope())
  3844. {
  3845. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3846. }
  3847. else
  3848. {
  3849. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3850. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3851. }
  3852. if (thisLocation != Js::Constants::NoRegister)
  3853. {
  3854. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3855. }
  3856. else
  3857. {
  3858. thisLocation = funcInfo->undefinedConstantRegister;
  3859. }
  3860. }
  3861. if (!recList.Empty())
  3862. {
  3863. Assert(instLocation != Js::Constants::NoRegister);
  3864. Assert(thisLocation != Js::Constants::NoRegister);
  3865. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  3866. this->m_writer.Br(doneLabel);
  3867. for (int i = 0;; i++)
  3868. {
  3869. this->m_writer.MarkLabel(recList.Item(i).label);
  3870. switch(recList.Item(i).kind)
  3871. {
  3872. case DynamicLoadKind::Local:
  3873. this->m_writer.Reg1(Js::OpCode::LdLocalObj_ReuseLoc, instLocation);
  3874. if (thisLocation != funcInfo->undefinedConstantRegister)
  3875. {
  3876. Assert(thisLocation != instLocation);
  3877. this->m_writer.Reg2(Js::OpCode::Ld_A_ReuseLoc, thisLocation, funcInfo->undefinedConstantRegister);
  3878. }
  3879. break;
  3880. case DynamicLoadKind::Env:
  3881. this->m_writer.SlotI1(Js::OpCode::LdEnvObj_ReuseLoc, instLocation, recList.Item(i).index);
  3882. if (thisLocation != funcInfo->undefinedConstantRegister)
  3883. {
  3884. Assert(thisLocation != instLocation);
  3885. this->m_writer.Reg2(Js::OpCode::Ld_A_ReuseLoc, thisLocation, funcInfo->undefinedConstantRegister);
  3886. }
  3887. break;
  3888. case DynamicLoadKind::LocalWith:
  3889. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, instLocation, recList.Item(i).instance);
  3890. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, thisLocation, recList.Item(i).instance);
  3891. break;
  3892. case DynamicLoadKind::EnvWith:
  3893. {
  3894. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3895. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg, recList.Item(i).index);
  3896. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, instLocation, tmpReg);
  3897. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, thisLocation, tmpReg);
  3898. funcInfo->ReleaseTmpRegister(tmpReg);
  3899. break;
  3900. }
  3901. default:
  3902. AssertOrFailFast(UNREACHED);
  3903. }
  3904. if (i == recList.Count() - 1)
  3905. {
  3906. break;
  3907. }
  3908. this->m_writer.Br(doneLabel);
  3909. }
  3910. this->m_writer.MarkLabel(doneLabel);
  3911. }
  3912. *pThisLocation = thisLocation;
  3913. *pInstLocation = instLocation;
  3914. }
  3915. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3916. {
  3917. // Note: declared variables and assignments in the global function go to the root object directly.
  3918. if (this->flags & fscrEval)
  3919. {
  3920. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3921. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3922. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3923. // into one operation). See WOOB 1121763 and 1120973.
  3924. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3925. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3926. }
  3927. else
  3928. {
  3929. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3930. }
  3931. }
  3932. void
  3933. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3934. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3935. {
  3936. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3937. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3938. }
  3939. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3940. {
  3941. Scope *scope = sym->GetScope();
  3942. // Check consistency of sym->IsInSlot.
  3943. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3944. // Arrived at the scope in which the property was defined.
  3945. if (sym->NeedsSlotAlloc(this, funcInfo))
  3946. {
  3947. // The property is in memory rather than register. We'll have to load it from the slots.
  3948. if (scope->GetIsObject())
  3949. {
  3950. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3951. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3952. Js::RegSlot objReg;
  3953. if (scope->HasInnerScopeIndex())
  3954. {
  3955. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3956. }
  3957. else
  3958. {
  3959. objReg = scope->GetLocation();
  3960. }
  3961. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3962. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3963. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3964. {
  3965. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3966. }
  3967. else if (scope->HasInnerScopeIndex())
  3968. {
  3969. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3970. }
  3971. else
  3972. {
  3973. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3974. }
  3975. }
  3976. else
  3977. {
  3978. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3979. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3980. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3981. // Now store the property to its slot.
  3982. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3983. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3984. {
  3985. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3986. }
  3987. else
  3988. {
  3989. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3990. }
  3991. }
  3992. }
  3993. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3994. {
  3995. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3996. }
  3997. }
  3998. Js::OpCode
  3999. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  4000. {
  4001. Js::OpCode op;
  4002. if (envIndex != -1)
  4003. {
  4004. if (scope->GetIsObject())
  4005. {
  4006. op = Js::OpCode::StEnvObjSlot;
  4007. }
  4008. else
  4009. {
  4010. op = Js::OpCode::StEnvSlot;
  4011. }
  4012. }
  4013. else if (scopeLocation != Js::Constants::NoRegister &&
  4014. scopeLocation == funcInfo->frameSlotsRegister)
  4015. {
  4016. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4017. {
  4018. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4019. // We should use the param scope's bytecode now.
  4020. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4021. op = Js::OpCode::StParamSlot;
  4022. }
  4023. else
  4024. {
  4025. op = Js::OpCode::StLocalSlot;
  4026. }
  4027. }
  4028. else if (scopeLocation != Js::Constants::NoRegister &&
  4029. scopeLocation == funcInfo->frameObjRegister)
  4030. {
  4031. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4032. {
  4033. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4034. // We should use the param scope's bytecode now.
  4035. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4036. op = Js::OpCode::StParamObjSlot;
  4037. }
  4038. else
  4039. {
  4040. op = Js::OpCode::StLocalObjSlot;
  4041. }
  4042. }
  4043. else
  4044. {
  4045. Assert(scope->HasInnerScopeIndex());
  4046. if (scope->GetIsObject())
  4047. {
  4048. op = Js::OpCode::StInnerObjSlot;
  4049. }
  4050. else
  4051. {
  4052. op = Js::OpCode::StInnerSlot;
  4053. }
  4054. }
  4055. if (chkBlockVar)
  4056. {
  4057. op = this->ToChkUndeclOp(op);
  4058. }
  4059. return op;
  4060. }
  4061. Js::OpCode
  4062. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4063. {
  4064. Js::OpCode op;
  4065. if (scopeLocation != Js::Constants::NoRegister &&
  4066. scopeLocation == funcInfo->frameObjRegister)
  4067. {
  4068. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4069. }
  4070. else if (scope->HasInnerScopeIndex())
  4071. {
  4072. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4073. }
  4074. else
  4075. {
  4076. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4077. }
  4078. return op;
  4079. }
  4080. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4081. {
  4082. Js::PropertyId envIndex = -1;
  4083. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4084. Assert(symScope);
  4085. // isFncDeclVar denotes that the symbol being stored to here is the var
  4086. // binding of a function declaration and we know we want to store directly
  4087. // to it, skipping over any dynamic scopes that may lie in between.
  4088. Scope *scope = nullptr;
  4089. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4090. Js::OpCode op;
  4091. if (sym && sym->GetIsModuleExportStorage())
  4092. {
  4093. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4094. {
  4095. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4096. }
  4097. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4098. return;
  4099. }
  4100. if (isFncDeclVar)
  4101. {
  4102. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4103. // of the parent function, so we need to calculate envIndex in lieu of the while
  4104. // loop below.
  4105. do
  4106. {
  4107. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4108. } while (scope != symScope);
  4109. Assert(scope == symScope);
  4110. scopeLocation = scope->GetLocation();
  4111. }
  4112. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4113. while (!isFncDeclVar)
  4114. {
  4115. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4116. if (scope == this->globalScope)
  4117. {
  4118. break;
  4119. }
  4120. if (envIndex == -1)
  4121. {
  4122. Assert(funcInfo == scope->GetFunc());
  4123. scopeLocation = scope->GetLocation();
  4124. }
  4125. if (scope == symScope)
  4126. {
  4127. break;
  4128. }
  4129. // Found a scope to which the property may have been added.
  4130. Assert(scope && scope->GetIsDynamic());
  4131. AssertOrFailFast(scope->GetIsObject());
  4132. DynamicLoadRecord rec;
  4133. rec.label = this->m_writer.DefineLabel();
  4134. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4135. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4136. if (scope->GetScopeType() != ScopeType_With)
  4137. {
  4138. if (envIndex == -1)
  4139. {
  4140. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4141. rec.kind = DynamicLoadKind::Local;
  4142. rec.instance = scopeLocation;
  4143. }
  4144. else
  4145. {
  4146. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4147. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4148. rec.kind = DynamicLoadKind::Env;
  4149. rec.index = frameDisplayIndex;
  4150. }
  4151. }
  4152. else
  4153. {
  4154. if (envIndex == -1)
  4155. {
  4156. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4157. rec.kind = DynamicLoadKind::LocalWith;
  4158. rec.instance = scopeLocation;
  4159. }
  4160. else
  4161. {
  4162. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4163. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4164. rec.kind = DynamicLoadKind::EnvWith;
  4165. rec.index = frameDisplayIndex;
  4166. }
  4167. }
  4168. recList.Add(rec);
  4169. }
  4170. // Arrived at the scope in which the property was defined.
  4171. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4172. {
  4173. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4174. // Intentionally continue on to do normal EmitPropStore behavior so
  4175. // that the bytecode ends up well-formed for the backend. This is
  4176. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4177. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4178. // of their load and then they skip emitting their own bytecode.
  4179. // Potayto potahto.
  4180. }
  4181. if (sym == nullptr || sym->GetIsGlobal())
  4182. {
  4183. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4184. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4185. if (this->flags & fscrEval)
  4186. {
  4187. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4188. {
  4189. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4190. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4191. }
  4192. else
  4193. {
  4194. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4195. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4196. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4197. }
  4198. }
  4199. else if (this->flags & fscrImplicitThis)
  4200. {
  4201. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4202. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4203. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4204. }
  4205. else
  4206. {
  4207. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false, forceStrictModeForClassComputedPropertyName), rhsLocation, propertyId, false, true, funcInfo);
  4208. }
  4209. }
  4210. else if (sym->GetIsFuncExpr())
  4211. {
  4212. // Store to function expr variable.
  4213. // strict mode: we need to throw type error
  4214. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4215. {
  4216. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4217. // It doesn't matter which register we use, as long as it's valid for this function.
  4218. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4219. }
  4220. }
  4221. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4222. {
  4223. if (!isConstDecl && sym->GetIsConst())
  4224. {
  4225. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4226. // we have to catch it at runtime.
  4227. this->m_writer.W1(
  4228. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4229. }
  4230. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4231. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4232. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4233. // The property is in memory rather than register. We'll have to load it from the slots.
  4234. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4235. if (envIndex != -1)
  4236. {
  4237. this->m_writer.SlotI2(op, rhsLocation,
  4238. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4239. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4240. }
  4241. else if (scopeLocation != Js::Constants::NoRegister &&
  4242. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4243. {
  4244. this->m_writer.SlotI1(op, rhsLocation,
  4245. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4246. }
  4247. else
  4248. {
  4249. Assert(scope->HasInnerScopeIndex());
  4250. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4251. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4252. }
  4253. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4254. {
  4255. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4256. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4257. }
  4258. }
  4259. else
  4260. {
  4261. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4262. {
  4263. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4264. // we have to catch it at runtime.
  4265. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4266. }
  4267. if (rhsLocation != sym->GetLocation())
  4268. {
  4269. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4270. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4271. {
  4272. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4273. }
  4274. }
  4275. }
  4276. if (!recList.Empty())
  4277. {
  4278. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4279. this->m_writer.Br(doneLabel);
  4280. for (int i = 0;; i++)
  4281. {
  4282. uint cacheId;
  4283. Js::RegSlot instLocation;
  4284. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4285. this->m_writer.MarkLabel(recList.Item(i).label);
  4286. switch(recList.Item(i).kind)
  4287. {
  4288. case DynamicLoadKind::Local:
  4289. cacheId = funcInfo->FindOrAddInlineCacheId(recList.Item(i).instance, propertyId, false, true);
  4290. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation, cacheId);
  4291. break;
  4292. case DynamicLoadKind::Env:
  4293. instLocation = funcInfo->AcquireTmpRegister();
  4294. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4295. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4296. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4297. funcInfo->ReleaseTmpRegister(instLocation);
  4298. break;
  4299. case DynamicLoadKind::LocalWith:
  4300. instLocation = funcInfo->AcquireTmpRegister();
  4301. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4302. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4303. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4304. funcInfo->ReleaseTmpRegister(instLocation);
  4305. break;
  4306. case DynamicLoadKind::EnvWith:
  4307. instLocation = funcInfo->AcquireTmpRegister();
  4308. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4309. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4310. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4311. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4312. funcInfo->ReleaseTmpRegister(instLocation);
  4313. break;
  4314. default:
  4315. AssertOrFailFast(UNREACHED);
  4316. }
  4317. if (i == recList.Count() - 1)
  4318. {
  4319. break;
  4320. }
  4321. this->m_writer.Br(doneLabel);
  4322. }
  4323. this->m_writer.MarkLabel(doneLabel);
  4324. }
  4325. }
  4326. Js::OpCode
  4327. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4328. {
  4329. Js::OpCode op;
  4330. if (envIndex != -1)
  4331. {
  4332. if (scope->GetIsObject())
  4333. {
  4334. op = Js::OpCode::LdEnvObjSlot;
  4335. }
  4336. else
  4337. {
  4338. op = Js::OpCode::LdEnvSlot;
  4339. }
  4340. }
  4341. else if (scopeLocation != Js::Constants::NoRegister &&
  4342. scopeLocation == funcInfo->frameSlotsRegister)
  4343. {
  4344. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4345. {
  4346. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4347. // We should use the param scope's bytecode now.
  4348. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4349. op = Js::OpCode::LdParamSlot;
  4350. }
  4351. else
  4352. {
  4353. op = Js::OpCode::LdLocalSlot;
  4354. }
  4355. }
  4356. else if (scopeLocation != Js::Constants::NoRegister &&
  4357. scopeLocation == funcInfo->frameObjRegister)
  4358. {
  4359. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4360. {
  4361. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4362. // We should use the param scope's bytecode now.
  4363. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4364. op = Js::OpCode::LdParamObjSlot;
  4365. }
  4366. else
  4367. {
  4368. op = Js::OpCode::LdLocalObjSlot;
  4369. }
  4370. }
  4371. else if (scope->HasInnerScopeIndex())
  4372. {
  4373. if (scope->GetIsObject())
  4374. {
  4375. op = Js::OpCode::LdInnerObjSlot;
  4376. }
  4377. else
  4378. {
  4379. op = Js::OpCode::LdInnerSlot;
  4380. }
  4381. }
  4382. else
  4383. {
  4384. AssertOrFailFast(scope->GetIsObject());
  4385. op = Js::OpCode::LdObjSlot;
  4386. }
  4387. return op;
  4388. }
  4389. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4390. {
  4391. #if DBG
  4392. // We should load a const 'this' binding if the following holds
  4393. // - The function has a 'this' name node
  4394. // - We are in a global or global lambda function
  4395. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4396. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4397. {
  4398. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4399. && !funcInfo->GetThisSymbol()
  4400. && !(this->flags & fscrEval));
  4401. }
  4402. #endif
  4403. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4404. }
  4405. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4406. {
  4407. Symbol* sym = pnodeSpecialName->sym;
  4408. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4409. {
  4410. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4411. }
  4412. else
  4413. {
  4414. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4415. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4416. {
  4417. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4418. }
  4419. }
  4420. }
  4421. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4422. {
  4423. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4424. {
  4425. if (init)
  4426. {
  4427. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4428. }
  4429. else
  4430. {
  4431. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4432. }
  4433. }
  4434. }
  4435. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4436. {
  4437. // If sym belongs to a parent frame, get it from the closure environment.
  4438. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4439. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4440. // Otherwise, just copy the value to the lhsLocation.
  4441. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4442. Js::PropertyId envIndex = -1;
  4443. Scope *scope = nullptr;
  4444. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4445. Assert(symScope);
  4446. if (sym && sym->GetIsModuleExportStorage())
  4447. {
  4448. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4449. return;
  4450. }
  4451. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4452. for (;;)
  4453. {
  4454. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4455. if (scope == this->globalScope)
  4456. {
  4457. break;
  4458. }
  4459. scopeLocation = scope->GetLocation();
  4460. if (scope == symScope)
  4461. {
  4462. break;
  4463. }
  4464. // Found a scope to which the property may have been added.
  4465. Assert(scope && scope->GetIsDynamic());
  4466. AssertOrFailFast(scope->GetIsObject());
  4467. DynamicLoadRecord rec;
  4468. rec.label = this->m_writer.DefineLabel();
  4469. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4470. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4471. if (scope->GetScopeType() != ScopeType_With)
  4472. {
  4473. if (envIndex == -1)
  4474. {
  4475. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4476. rec.kind = DynamicLoadKind::Local;
  4477. rec.instance = scopeLocation;
  4478. }
  4479. else
  4480. {
  4481. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4482. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4483. rec.kind = DynamicLoadKind::Env;
  4484. rec.index = frameDisplayIndex;
  4485. }
  4486. }
  4487. else
  4488. {
  4489. if (envIndex == -1)
  4490. {
  4491. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4492. rec.kind = DynamicLoadKind::LocalWith;
  4493. rec.instance = scopeLocation;
  4494. }
  4495. else
  4496. {
  4497. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4498. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4499. rec.kind = DynamicLoadKind::EnvWith;
  4500. rec.index = frameDisplayIndex;
  4501. }
  4502. }
  4503. recList.Add(rec);
  4504. }
  4505. // Arrived at the scope in which the property was defined.
  4506. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4507. {
  4508. // Ensure this symbol has a slot if it needs one.
  4509. if (sym->IsInSlot(this, funcInfo))
  4510. {
  4511. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4512. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4513. }
  4514. if (skipUseBeforeDeclarationCheck)
  4515. {
  4516. if (lhsLocation != Js::Constants::NoRegister)
  4517. {
  4518. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4519. }
  4520. }
  4521. else
  4522. {
  4523. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4524. }
  4525. }
  4526. else if (sym == nullptr || sym->GetIsGlobal())
  4527. {
  4528. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4529. if (this->flags & fscrEval)
  4530. {
  4531. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4532. {
  4533. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4534. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4535. }
  4536. else
  4537. {
  4538. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4539. // Load of a symbol with unknown scope from within eval
  4540. // Get it from the closure environment.
  4541. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4542. }
  4543. }
  4544. else if (this->flags & fscrImplicitThis)
  4545. {
  4546. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4547. // Load of a symbol with unknown scope from within event handler.
  4548. // Get it from the closure environment.
  4549. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4550. }
  4551. else
  4552. {
  4553. // Special case non-writable built-ins
  4554. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4555. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4556. // next time we run. May want to catch that in the JIT.
  4557. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4558. // These properties are non-writable
  4559. switch (propertyId)
  4560. {
  4561. case Js::PropertyIds::NaN:
  4562. opcode = Js::OpCode::LdNaN;
  4563. break;
  4564. case Js::PropertyIds::Infinity:
  4565. opcode = Js::OpCode::LdInfinity;
  4566. break;
  4567. case Js::PropertyIds::undefined:
  4568. opcode = Js::OpCode::LdUndef;
  4569. break;
  4570. case Js::PropertyIds::__chakraLibrary:
  4571. if (CONFIG_FLAG(LdChakraLib) || CONFIG_FLAG(TestChakraLib))
  4572. {
  4573. opcode = Js::OpCode::LdChakraLib;
  4574. }
  4575. break;
  4576. }
  4577. if (opcode == Js::OpCode::LdRootFld)
  4578. {
  4579. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4580. }
  4581. else
  4582. {
  4583. this->Writer()->Reg1(opcode, lhsLocation);
  4584. }
  4585. }
  4586. }
  4587. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4588. {
  4589. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4590. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4591. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4592. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4593. Js::OpCode op;
  4594. // Now get the property from its slot.
  4595. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4596. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4597. if (envIndex != -1)
  4598. {
  4599. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4600. }
  4601. else if (scopeLocation != Js::Constants::NoRegister &&
  4602. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4603. {
  4604. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4605. }
  4606. else if (scope->HasInnerScopeIndex())
  4607. {
  4608. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4609. }
  4610. else
  4611. {
  4612. AssertOrFailFast(scope->GetIsObject());
  4613. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4614. }
  4615. if (chkBlockVar)
  4616. {
  4617. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4618. }
  4619. }
  4620. else
  4621. {
  4622. if (lhsLocation != sym->GetLocation())
  4623. {
  4624. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4625. }
  4626. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4627. {
  4628. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4629. }
  4630. }
  4631. if (!recList.Empty())
  4632. {
  4633. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4634. this->m_writer.Br(doneLabel);
  4635. for (int i = 0;; i++)
  4636. {
  4637. uint cacheId;
  4638. Js::RegSlot instLocation;
  4639. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4640. this->m_writer.MarkLabel(recList.Item(i).label);
  4641. switch(recList.Item(i).kind)
  4642. {
  4643. case DynamicLoadKind::Local:
  4644. cacheId = funcInfo->FindOrAddInlineCacheId(recList.Item(i).instance, propertyId, false, false);
  4645. this->m_writer.ElementP(Js::OpCode::LdLocalFld_ReuseLoc, lhsLocation, cacheId);
  4646. break;
  4647. case DynamicLoadKind::Env:
  4648. instLocation = funcInfo->AcquireTmpRegister();
  4649. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4650. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4651. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4652. funcInfo->ReleaseTmpRegister(instLocation);
  4653. break;
  4654. case DynamicLoadKind::LocalWith:
  4655. instLocation = funcInfo->AcquireTmpRegister();
  4656. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4657. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4658. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4659. funcInfo->ReleaseTmpRegister(instLocation);
  4660. break;
  4661. case DynamicLoadKind::EnvWith:
  4662. instLocation = funcInfo->AcquireTmpRegister();
  4663. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4664. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4665. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4666. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4667. funcInfo->ReleaseTmpRegister(instLocation);
  4668. break;
  4669. default:
  4670. AssertOrFailFast(UNREACHED);
  4671. }
  4672. if (i == recList.Count() - 1)
  4673. {
  4674. break;
  4675. }
  4676. this->m_writer.Br(doneLabel);
  4677. }
  4678. this->m_writer.MarkLabel(doneLabel);
  4679. }
  4680. }
  4681. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4682. {
  4683. bool tdz = sym->GetIsBlockVar()
  4684. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4685. return tdz || sym->GetIsNonSimpleParameter();
  4686. }
  4687. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4688. {
  4689. // If sym belongs to a parent frame, delete it from the closure environment.
  4690. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4691. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4692. // Otherwise, just return false.
  4693. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4694. Js::PropertyId envIndex = -1;
  4695. Scope *scope = nullptr;
  4696. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4697. Assert(symScope);
  4698. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4699. for (;;)
  4700. {
  4701. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4702. if (scope == this->globalScope)
  4703. {
  4704. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4705. }
  4706. else if (envIndex == -1)
  4707. {
  4708. Assert(funcInfo == scope->GetFunc());
  4709. scopeLocation = scope->GetLocation();
  4710. }
  4711. if (scope == symScope)
  4712. {
  4713. break;
  4714. }
  4715. // Found a scope to which the property may have been added.
  4716. Assert(scope && scope->GetIsDynamic());
  4717. AssertOrFailFast(scope->GetIsObject());
  4718. DynamicLoadRecord rec;
  4719. rec.label = this->m_writer.DefineLabel();
  4720. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4721. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4722. if (scope->GetScopeType() != ScopeType_With)
  4723. {
  4724. if (envIndex == -1)
  4725. {
  4726. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4727. rec.kind = DynamicLoadKind::Local;
  4728. rec.instance = scopeLocation;
  4729. }
  4730. else
  4731. {
  4732. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4733. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4734. rec.kind = DynamicLoadKind::Env;
  4735. rec.index = frameDisplayIndex;
  4736. }
  4737. }
  4738. else
  4739. {
  4740. if (envIndex == -1)
  4741. {
  4742. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4743. rec.kind = DynamicLoadKind::LocalWith;
  4744. rec.instance = scopeLocation;
  4745. }
  4746. else
  4747. {
  4748. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4749. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4750. rec.kind = DynamicLoadKind::EnvWith;
  4751. rec.index = frameDisplayIndex;
  4752. }
  4753. }
  4754. recList.Add(rec);
  4755. }
  4756. // Arrived at the scope in which the property was defined.
  4757. if (sym == nullptr || sym->GetIsGlobal())
  4758. {
  4759. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4760. if (this->flags & (fscrEval | fscrImplicitThis))
  4761. {
  4762. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4763. funcInfo->FindOrAddReferencedPropertyId(propertyId), forceStrictModeForClassComputedPropertyName);
  4764. }
  4765. else
  4766. {
  4767. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4768. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4769. }
  4770. }
  4771. else
  4772. {
  4773. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4774. sym->EnsureScopeSlot(this, funcInfo);
  4775. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4776. }
  4777. if (!recList.Empty())
  4778. {
  4779. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4780. this->m_writer.Br(doneLabel);
  4781. for (int i = 0;; i++)
  4782. {
  4783. Js::RegSlot instLocation;
  4784. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4785. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4786. this->m_writer.MarkLabel(recList.Item(i).label);
  4787. switch(recList.Item(i).kind)
  4788. {
  4789. case DynamicLoadKind::Local:
  4790. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld_ReuseLoc, lhsLocation, propertyIndex);
  4791. break;
  4792. case DynamicLoadKind::Env:
  4793. instLocation = funcInfo->AcquireTmpRegister();
  4794. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4795. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4796. funcInfo->ReleaseTmpRegister(instLocation);
  4797. break;
  4798. case DynamicLoadKind::LocalWith:
  4799. instLocation = funcInfo->AcquireTmpRegister();
  4800. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4801. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4802. funcInfo->ReleaseTmpRegister(instLocation);
  4803. break;
  4804. case DynamicLoadKind::EnvWith:
  4805. instLocation = funcInfo->AcquireTmpRegister();
  4806. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4807. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4808. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4809. funcInfo->ReleaseTmpRegister(instLocation);
  4810. break;
  4811. default:
  4812. AssertOrFailFast(UNREACHED);
  4813. }
  4814. if (i == recList.Count() - 1)
  4815. {
  4816. break;
  4817. }
  4818. this->m_writer.Br(doneLabel);
  4819. }
  4820. this->m_writer.MarkLabel(doneLabel);
  4821. }
  4822. }
  4823. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp, bool reuseLoc)
  4824. {
  4825. uint cacheId;
  4826. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4827. switch (ldFldOp)
  4828. {
  4829. case Js::OpCode::LdRootFldForTypeOf:
  4830. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4831. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4832. break;
  4833. case Js::OpCode::LdLocalFld:
  4834. case Js::OpCode::ScopedLdFldForTypeOf:
  4835. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4836. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4837. break;
  4838. default:
  4839. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4840. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4841. break;
  4842. }
  4843. this->Writer()->Reg2(reuseLoc ? Js::OpCode::Typeof_ReuseLoc : Js::OpCode::Typeof, value, tmpReg);
  4844. funcInfo->ReleaseTmpRegister(tmpReg);
  4845. }
  4846. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4847. {
  4848. // If sym belongs to a parent frame, delete it from the closure environment.
  4849. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4850. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4851. // Otherwise, just return false
  4852. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4853. Js::PropertyId envIndex = -1;
  4854. Scope *scope = nullptr;
  4855. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4856. Assert(symScope);
  4857. if (sym && sym->GetIsModuleExportStorage())
  4858. {
  4859. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4860. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4861. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4862. funcInfo->ReleaseTmpRegister(tmpLocation);
  4863. return;
  4864. }
  4865. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4866. for (;;)
  4867. {
  4868. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4869. if (scope == this->globalScope)
  4870. {
  4871. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4872. }
  4873. else if (envIndex == -1)
  4874. {
  4875. Assert(funcInfo == scope->GetFunc());
  4876. scopeLocation = scope->GetLocation();
  4877. }
  4878. if (scope == symScope)
  4879. {
  4880. break;
  4881. }
  4882. // Found a scope to which the property may have been added.
  4883. Assert(scope && scope->GetIsDynamic());
  4884. AssertOrFailFast(scope->GetIsObject());
  4885. DynamicLoadRecord rec;
  4886. rec.label = this->m_writer.DefineLabel();
  4887. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4888. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4889. if (scope->GetScopeType() != ScopeType_With)
  4890. {
  4891. if (envIndex == -1)
  4892. {
  4893. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4894. rec.kind = DynamicLoadKind::Local;
  4895. rec.instance = scopeLocation;
  4896. }
  4897. else
  4898. {
  4899. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4900. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4901. rec.kind = DynamicLoadKind::Env;
  4902. rec.index = frameDisplayIndex;
  4903. }
  4904. }
  4905. else
  4906. {
  4907. if (envIndex == -1)
  4908. {
  4909. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4910. rec.kind = DynamicLoadKind::LocalWith;
  4911. rec.instance = scopeLocation;
  4912. }
  4913. else
  4914. {
  4915. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4916. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4917. rec.kind = DynamicLoadKind::EnvWith;
  4918. rec.index = frameDisplayIndex;
  4919. }
  4920. }
  4921. recList.Add(rec);
  4922. }
  4923. // Arrived at the scope in which the property was defined.
  4924. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4925. {
  4926. // Ensure this symbol has a slot if it needs one.
  4927. if (sym->IsInSlot(this, funcInfo))
  4928. {
  4929. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4930. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4931. }
  4932. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4933. }
  4934. else if (sym == nullptr || sym->GetIsGlobal())
  4935. {
  4936. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4937. if (this->flags & fscrEval)
  4938. {
  4939. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4940. {
  4941. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4942. }
  4943. else
  4944. {
  4945. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4946. }
  4947. }
  4948. else if (this->flags & fscrImplicitThis)
  4949. {
  4950. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4951. }
  4952. else
  4953. {
  4954. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4955. }
  4956. }
  4957. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4958. {
  4959. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4960. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4961. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4962. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4963. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4964. Js::OpCode op;
  4965. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4966. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4967. if (envIndex != -1)
  4968. {
  4969. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4970. }
  4971. else if (scopeLocation != Js::Constants::NoRegister &&
  4972. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4973. {
  4974. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4975. }
  4976. else if (scope->HasInnerScopeIndex())
  4977. {
  4978. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4979. }
  4980. else
  4981. {
  4982. AssertOrFailFast(scope->GetIsObject());
  4983. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4984. }
  4985. if (chkBlockVar)
  4986. {
  4987. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4988. }
  4989. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4990. funcInfo->ReleaseTmpRegister(tmpLocation);
  4991. }
  4992. else
  4993. {
  4994. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4995. }
  4996. if (!recList.Empty())
  4997. {
  4998. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4999. this->m_writer.Br(doneLabel);
  5000. for (int i = 0;; i++)
  5001. {
  5002. Js::RegSlot instLocation;
  5003. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  5004. this->m_writer.MarkLabel(recList.Item(i).label);
  5005. switch(recList.Item(i).kind)
  5006. {
  5007. case DynamicLoadKind::Local:
  5008. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, recList.Item(i).instance, Js::OpCode::LdLocalFld, true);
  5009. break;
  5010. case DynamicLoadKind::Env:
  5011. instLocation = funcInfo->AcquireTmpRegister();
  5012. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  5013. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5014. funcInfo->ReleaseTmpRegister(instLocation);
  5015. break;
  5016. case DynamicLoadKind::LocalWith:
  5017. instLocation = funcInfo->AcquireTmpRegister();
  5018. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  5019. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5020. funcInfo->ReleaseTmpRegister(instLocation);
  5021. break;
  5022. case DynamicLoadKind::EnvWith:
  5023. instLocation = funcInfo->AcquireTmpRegister();
  5024. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  5025. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  5026. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5027. funcInfo->ReleaseTmpRegister(instLocation);
  5028. break;
  5029. default:
  5030. AssertOrFailFast(UNREACHED);
  5031. }
  5032. if (i == recList.Count() - 1)
  5033. {
  5034. break;
  5035. }
  5036. this->m_writer.Br(doneLabel);
  5037. }
  5038. this->m_writer.MarkLabel(doneLabel);
  5039. }
  5040. }
  5041. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  5042. {
  5043. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  5044. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  5045. // remain local to the eval code.
  5046. Assert(pnodeBlock->nop == knopBlock);
  5047. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  5048. if (!(this->flags & fscrEvalCode))
  5049. {
  5050. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  5051. {
  5052. FuncInfo *funcInfo = this->TopFuncInfo();
  5053. Symbol *sym = pnode->AsParseNodeVar()->sym;
  5054. Assert(sym->GetIsGlobal());
  5055. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5056. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5057. });
  5058. }
  5059. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo, bool isFncDecl = false)
  5060. {
  5061. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5062. // Global function declarations must pass #sec-candeclareglobalfunction
  5063. // which is enforced by EnsureCanDeclGloFunc
  5064. if (isFncDecl)
  5065. {
  5066. this->m_writer.ElementRootU(Js::OpCode::EnsureCanDeclGloFunc, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5067. }
  5068. if (this->flags & fscrEval)
  5069. {
  5070. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  5071. {
  5072. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  5073. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5074. }
  5075. }
  5076. else
  5077. {
  5078. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5079. }
  5080. };
  5081. // scan for function declarations
  5082. // these behave like "var" declarations
  5083. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  5084. {
  5085. switch (pnode->nop) {
  5086. case knopFncDecl:
  5087. if (pnode->AsParseNodeFnc()->IsDeclaration())
  5088. {
  5089. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo, true);
  5090. }
  5091. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  5092. break;
  5093. case knopBlock:
  5094. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  5095. break;
  5096. case knopCatch:
  5097. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  5098. break;
  5099. case knopWith:
  5100. pnode = pnode->AsParseNodeWith()->pnodeNext;
  5101. break;
  5102. default:
  5103. Assert(UNREACHED);
  5104. }
  5105. }
  5106. // scan for var declarations
  5107. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  5108. {
  5109. Symbol* sym = pnode->AsParseNodeVar()->sym;
  5110. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  5111. continue;
  5112. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  5113. {
  5114. // The init node was bound to the catch object, because it's inside a catch and has the
  5115. // same name as the catch object. But we want to define a user var at function scope,
  5116. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  5117. // This also applies to a var declaration in the same scope as a let declaration.
  5118. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  5119. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  5120. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  5121. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  5122. }
  5123. Assert(sym->GetIsGlobal());
  5124. if (sym->GetSymbolType() == STVariable)
  5125. {
  5126. emitRedeclCheck(sym, funcInfo);
  5127. }
  5128. }
  5129. }
  5130. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  5131. {
  5132. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5133. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5134. {
  5135. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5136. });
  5137. }
  5138. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5139. {
  5140. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5141. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5142. {
  5143. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  5144. });
  5145. }
  5146. void ByteCodeGenerator::RecordAllBigIntConstants(FuncInfo * funcInfo)
  5147. {
  5148. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5149. funcInfo->bigintToRegister.Map([byteCodeFunction](ParseNode* pnode, Js::RegSlot location)
  5150. {
  5151. IdentPtr pid = pnode->AsParseNodeBigInt()->pid;
  5152. byteCodeFunction->RecordBigIntConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pnode->AsParseNodeBigInt()->isNegative);
  5153. });
  5154. }
  5155. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5156. {
  5157. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5158. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5159. {
  5160. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5161. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5162. rawArray->Freeze();
  5163. Js::RecyclableObject* callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5164. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5165. callsiteObject->Freeze();
  5166. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5167. });
  5168. }
  5169. bool IsApplyArgs(ParseNodeCall* callNode)
  5170. {
  5171. ParseNode* target = callNode->pnodeTarget;
  5172. ParseNode* args = callNode->pnodeArgs;
  5173. if ((target != nullptr) && (target->nop == knopDot))
  5174. {
  5175. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5176. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5177. {
  5178. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5179. if (nameNode != nullptr)
  5180. {
  5181. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5182. if (nameIsApply && args != nullptr && args->nop == knopList)
  5183. {
  5184. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5185. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5186. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5187. {
  5188. return arg2->AsParseNodeName()->sym->IsArguments();
  5189. }
  5190. }
  5191. }
  5192. }
  5193. }
  5194. return false;
  5195. }
  5196. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5197. {
  5198. if ((pnode == nullptr) || (!applyCheck->matches))
  5199. {
  5200. return;
  5201. }
  5202. if (pnode->nop == knopCall)
  5203. {
  5204. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5205. {
  5206. if (!applyCheck->insideApplyCall)
  5207. {
  5208. applyCheck->matches = false;
  5209. }
  5210. applyCheck->insideApplyCall = false;
  5211. }
  5212. }
  5213. }
  5214. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5215. {
  5216. if ((pnode == nullptr) || (!applyCheck->matches))
  5217. {
  5218. return;
  5219. }
  5220. switch (pnode->nop)
  5221. {
  5222. case knopName:
  5223. {
  5224. Symbol* sym = pnode->AsParseNodeName()->sym;
  5225. if (sym != nullptr)
  5226. {
  5227. if (sym->IsArguments())
  5228. {
  5229. if (!applyCheck->insideApplyCall)
  5230. {
  5231. applyCheck->matches = false;
  5232. }
  5233. }
  5234. }
  5235. break;
  5236. }
  5237. case knopCall:
  5238. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5239. {
  5240. // no nested apply calls
  5241. if (applyCheck->insideApplyCall)
  5242. {
  5243. applyCheck->matches = false;
  5244. }
  5245. else
  5246. {
  5247. applyCheck->insideApplyCall = true;
  5248. applyCheck->sawApply = true;
  5249. pnode->AsParseNodeCall()->isApplyCall = true;
  5250. }
  5251. }
  5252. break;
  5253. }
  5254. }
  5255. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5256. {
  5257. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5258. // side-effects in the argument list. We need to know this so that the call target
  5259. // operands can be preserved if necessary.
  5260. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5261. // but we can be more precise if we need to be.
  5262. if (pSideEffect)
  5263. {
  5264. *pSideEffect = FALSE;
  5265. }
  5266. unsigned int argCount = 1;
  5267. if (pnode != nullptr)
  5268. {
  5269. while (pnode->nop == knopList)
  5270. {
  5271. argCount++;
  5272. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5273. {
  5274. *pSideEffect = TRUE;
  5275. }
  5276. pnode = pnode->AsParseNodeBin()->pnode2;
  5277. }
  5278. argCount++;
  5279. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5280. {
  5281. *pSideEffect = TRUE;
  5282. }
  5283. }
  5284. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5285. return argCount;
  5286. }
  5287. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5288. {
  5289. // Save a local name to a register other than its home location.
  5290. // This guards against side-effects in cases like x.foo(x = bar()).
  5291. Symbol *sym = nullptr;
  5292. if (pnode->nop == knopName)
  5293. {
  5294. sym = pnode->AsParseNodeName()->sym;
  5295. }
  5296. else if (pnode->nop == knopComputedName)
  5297. {
  5298. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5299. if (pnode1->nop == knopName)
  5300. {
  5301. sym = pnode1->AsParseNodeName()->sym;
  5302. }
  5303. }
  5304. if (sym == nullptr)
  5305. {
  5306. return;
  5307. }
  5308. // If the target is a local being kept in its home location,
  5309. // protect the target's value in the event the home location is overwritten.
  5310. if (pnode->location != Js::Constants::NoRegister &&
  5311. sym->GetScope()->GetFunc() == funcInfo &&
  5312. pnode->location == sym->GetLocation())
  5313. {
  5314. pnode->location = funcInfo->AcquireTmpRegister();
  5315. }
  5316. }
  5317. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5318. {
  5319. Assert(TopFuncInfo() != nullptr);
  5320. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5321. }
  5322. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5323. {
  5324. m_writer.EndStatement(node);
  5325. }
  5326. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5327. {
  5328. Assert(TopFuncInfo() != nullptr);
  5329. m_writer.StartSubexpression(node);
  5330. }
  5331. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5332. {
  5333. m_writer.EndSubexpression(node);
  5334. }
  5335. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5336. {
  5337. // Generate code for the LHS of an assignment.
  5338. switch (pnode->nop)
  5339. {
  5340. case knopDot:
  5341. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5342. break;
  5343. case knopIndex:
  5344. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5345. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5346. break;
  5347. case knopName:
  5348. break;
  5349. case knopArrayPattern:
  5350. case knopObjectPattern:
  5351. break;
  5352. case knopCall:
  5353. case knopNew:
  5354. // Emit the operands of a call that will be used as a LHS.
  5355. // These have to be emitted before the RHS, but they have to persist until
  5356. // the end of the expression.
  5357. // Emit the call target operands first.
  5358. // The call target does not need to be emitted for a super call - EmitSuperCall will do this.
  5359. if (!pnode->AsParseNodeCall()->isSuperCall)
  5360. {
  5361. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5362. {
  5363. case knopDot:
  5364. case knopIndex:
  5365. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5366. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5367. break;
  5368. case knopName:
  5369. {
  5370. Symbol* sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5371. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5372. {
  5373. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5374. }
  5375. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5376. {
  5377. // Can't get the value from the assigned register, so load it here.
  5378. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5379. }
  5380. else
  5381. {
  5382. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5383. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5384. // must manually check here.
  5385. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5386. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5387. }
  5388. break;
  5389. }
  5390. default:
  5391. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5392. break;
  5393. }
  5394. }
  5395. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5396. if (pnode->AsParseNodeCall()->pnodeArgs)
  5397. {
  5398. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5399. while (pnodeArg->nop == knopList)
  5400. {
  5401. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5402. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5403. }
  5404. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5405. }
  5406. break;
  5407. default:
  5408. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5409. break;
  5410. }
  5411. }
  5412. void EmitGetIterator(Js::RegSlot iteratorReg, Js::RegSlot iterableReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5413. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, bool isAsync = false);
  5414. void EmitFunctionCall(
  5415. Js::RegSlot resultReg,
  5416. Js::RegSlot funcReg,
  5417. Js::RegSlot thisReg,
  5418. Js::RegSlot argReg,
  5419. ByteCodeGenerator* byteCodeGenerator,
  5420. FuncInfo* funcInfo)
  5421. {
  5422. Js::ArgSlot argCount = argReg == Js::Constants::NoRegister ? 1 : 2;
  5423. funcInfo->StartRecordingOutArgs(argCount);
  5424. Js::ProfileId callSite = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  5425. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  5426. byteCodeGenerator->Writer()->ArgOut<true>(0, thisReg, callSite, false);
  5427. if (argReg != Js::Constants::NoRegister)
  5428. byteCodeGenerator->Writer()->ArgOut<true>(1, argReg, callSite, false);
  5429. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, resultReg, funcReg, argCount, callSite);
  5430. }
  5431. void EmitFunctionCall(
  5432. Js::RegSlot resultReg,
  5433. Js::RegSlot funcReg,
  5434. Js::RegSlot thisReg,
  5435. ByteCodeGenerator* byteCodeGenerator,
  5436. FuncInfo* funcInfo)
  5437. {
  5438. Js::RegSlot argReg = Js::Constants::NoRegister;
  5439. EmitFunctionCall(resultReg, funcReg, thisReg, argReg, byteCodeGenerator, funcInfo);
  5440. }
  5441. void EmitThrowOnNotObject(Js::RegSlot varReg, ByteCodeGenerator* byteCodeGenerator)
  5442. {
  5443. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5444. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, varReg);
  5445. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  5446. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5447. }
  5448. void EmitGetOptionalObjectMethod(
  5449. Js::RegSlot methodReg,
  5450. Js::RegSlot objectReg,
  5451. Js::PropertyId propertyId,
  5452. Js::ByteCodeLabel noMethodLabel,
  5453. ByteCodeGenerator* byteCodeGenerator,
  5454. FuncInfo* funcInfo)
  5455. {
  5456. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5457. objectReg,
  5458. propertyId,
  5459. /* isLoadMethod */ true,
  5460. /* isStore */ false);
  5461. byteCodeGenerator->Writer()->PatchableProperty(
  5462. Js::OpCode::LdFld,
  5463. methodReg,
  5464. objectReg,
  5465. cacheId,
  5466. /* isCtor */ false,
  5467. /* registerCacheIdForCall */ true);
  5468. byteCodeGenerator->Writer()->BrReg2(
  5469. Js::OpCode::BrEq_A,
  5470. noMethodLabel,
  5471. methodReg,
  5472. funcInfo->undefinedConstantRegister);
  5473. }
  5474. void EmitGetObjectMethod(
  5475. Js::RegSlot methodReg,
  5476. Js::RegSlot objectReg,
  5477. Js::PropertyId propertyId,
  5478. ByteCodeGenerator* byteCodeGenerator,
  5479. FuncInfo* funcInfo)
  5480. {
  5481. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5482. objectReg,
  5483. propertyId,
  5484. /* isLoadMethod */ true,
  5485. /* isStore */ false);
  5486. byteCodeGenerator->Writer()->PatchableProperty(
  5487. Js::OpCode::LdMethodFld,
  5488. methodReg,
  5489. objectReg,
  5490. cacheId,
  5491. /* isCtor */ false,
  5492. /* registerCacheIdForCall */ true);
  5493. }
  5494. void EmitGetObjectProperty(
  5495. Js::RegSlot resultReg,
  5496. Js::RegSlot objectReg,
  5497. Js::PropertyId propertyId,
  5498. ByteCodeGenerator* byteCodeGenerator,
  5499. FuncInfo* funcInfo)
  5500. {
  5501. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5502. objectReg,
  5503. propertyId,
  5504. /* isLoadMethod */ false,
  5505. /* isStore */ false);
  5506. byteCodeGenerator->Writer()->PatchableProperty(
  5507. Js::OpCode::LdFld,
  5508. resultReg,
  5509. objectReg,
  5510. cacheId,
  5511. /* isCtor */ false,
  5512. /* registerCacheIdForCall */ false);
  5513. }
  5514. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5515. {
  5516. switch (elem->nop)
  5517. {
  5518. case knopVarDecl:
  5519. case knopLetDecl:
  5520. case knopConstDecl:
  5521. // We manually need to set NeedDeclaration since the node won't be visited.
  5522. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5523. break;
  5524. default:
  5525. EmitReference(elem, byteCodeGenerator, funcInfo);
  5526. }
  5527. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5528. funcInfo->ReleaseReference(elem);
  5529. }
  5530. void EmitDestructuredRestArray(
  5531. ParseNode* elem,
  5532. Js::RegSlot iteratorLocation,
  5533. Js::RegSlot nextMethodReg,
  5534. Js::RegSlot shouldCallReturnFunctionLocation,
  5535. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5536. ByteCodeGenerator* byteCodeGenerator,
  5537. FuncInfo* funcInfo)
  5538. {
  5539. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5540. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5541. if (isAssignmentTarget)
  5542. {
  5543. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5544. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5545. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5546. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5547. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5548. }
  5549. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5550. Js::OpCode::NewScArray,
  5551. restArrayLocation,
  5552. ByteCodeGenerator::DefaultArraySize);
  5553. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5554. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5555. // convey this is live on the back edge.
  5556. // As a workaround, we have a persistent var reg that is used for the loop counter
  5557. Js::RegSlot counterLocation = elem->location;
  5558. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5559. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5560. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5561. // loopTop:
  5562. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5563. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5564. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5565. EmitFunctionCall(
  5566. itemLocation,
  5567. nextMethodReg,
  5568. iteratorLocation,
  5569. byteCodeGenerator,
  5570. funcInfo);
  5571. EmitThrowOnNotObject(itemLocation, byteCodeGenerator);
  5572. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5573. EmitGetObjectProperty(
  5574. doneLocation,
  5575. itemLocation,
  5576. Js::PropertyIds::done,
  5577. byteCodeGenerator,
  5578. funcInfo);
  5579. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5580. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5581. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5582. EmitGetObjectProperty(
  5583. valueLocation,
  5584. itemLocation,
  5585. Js::PropertyIds::value,
  5586. byteCodeGenerator,
  5587. funcInfo);
  5588. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5589. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5590. byteCodeGenerator->Writer()->Element(
  5591. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5592. valueLocation, restArrayLocation, counterLocation);
  5593. funcInfo->ReleaseTmpRegister(valueLocation);
  5594. funcInfo->ReleaseTmpRegister(doneLocation);
  5595. funcInfo->ReleaseTmpRegister(itemLocation);
  5596. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5597. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5598. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5599. byteCodeGenerator->Writer()->Br(loopTop);
  5600. // iteratorDone:
  5601. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5602. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5603. if (isAssignmentTarget)
  5604. {
  5605. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5606. funcInfo->ReleaseReference(restElem);
  5607. }
  5608. else
  5609. {
  5610. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5611. }
  5612. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5613. }
  5614. void EmitDestructuredArray(
  5615. ParseNode *lhs,
  5616. Js::RegSlot rhsLocation,
  5617. ByteCodeGenerator *byteCodeGenerator,
  5618. FuncInfo *funcInfo);
  5619. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5620. {
  5621. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5622. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5623. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5624. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5625. }
  5626. /*
  5627. EmitDestructuredArray(lhsArray, rhs):
  5628. iterator = rhs[@@iterator]
  5629. if lhsArray empty
  5630. return
  5631. for each element in lhsArray except rest
  5632. value = iterator.next()
  5633. if element is a nested destructured array
  5634. EmitDestructuredArray(element, value)
  5635. else
  5636. if value is undefined and there is an initializer
  5637. evaluate initializer
  5638. evaluate element reference
  5639. element = initializer
  5640. else
  5641. element = value
  5642. if lhsArray has a rest element
  5643. rest = []
  5644. while iterator is not done
  5645. value = iterator.next()
  5646. rest.append(value)
  5647. */
  5648. void EmitDestructuredArrayCore(
  5649. ParseNode* list,
  5650. Js::RegSlot iteratorLocation,
  5651. Js::RegSlot nextMethodReg,
  5652. Js::RegSlot shouldCallReturnFunctionLocation,
  5653. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5654. ByteCodeGenerator* byteCodeGenerator,
  5655. FuncInfo* funcInfo)
  5656. {
  5657. Assert(list != nullptr);
  5658. ParseNode *elem = nullptr;
  5659. while (list != nullptr)
  5660. {
  5661. ParseNode *init = nullptr;
  5662. if (list->nop == knopList)
  5663. {
  5664. elem = list->AsParseNodeBin()->pnode1;
  5665. }
  5666. else
  5667. {
  5668. elem = list;
  5669. }
  5670. if (elem->nop == knopEllipsis)
  5671. {
  5672. break;
  5673. }
  5674. switch (elem->nop)
  5675. {
  5676. case knopAsg:
  5677. // An assignment node will always have an initializer
  5678. init = elem->AsParseNodeBin()->pnode2;
  5679. elem = elem->AsParseNodeBin()->pnode1;
  5680. break;
  5681. case knopVarDecl:
  5682. case knopLetDecl:
  5683. case knopConstDecl:
  5684. init = elem->AsParseNodeVar()->pnodeInit;
  5685. break;
  5686. default:
  5687. break;
  5688. }
  5689. byteCodeGenerator->StartStatement(elem);
  5690. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5691. if (isAssignmentTarget)
  5692. {
  5693. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5694. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5695. EmitReference(elem, byteCodeGenerator, funcInfo);
  5696. }
  5697. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5698. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5699. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5700. EmitFunctionCall(
  5701. itemLocation,
  5702. nextMethodReg,
  5703. iteratorLocation,
  5704. byteCodeGenerator,
  5705. funcInfo);
  5706. EmitThrowOnNotObject(itemLocation, byteCodeGenerator);
  5707. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5708. EmitGetObjectProperty(
  5709. doneLocation,
  5710. itemLocation,
  5711. Js::PropertyIds::done,
  5712. byteCodeGenerator,
  5713. funcInfo);
  5714. if (elem->nop == knopEmpty)
  5715. {
  5716. if (list->nop == knopList)
  5717. {
  5718. list = list->AsParseNodeBin()->pnode2;
  5719. funcInfo->ReleaseTmpRegister(doneLocation);
  5720. funcInfo->ReleaseTmpRegister(itemLocation);
  5721. continue;
  5722. }
  5723. else
  5724. {
  5725. Assert(list->nop == knopEmpty);
  5726. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5727. funcInfo->ReleaseTmpRegister(doneLocation);
  5728. funcInfo->ReleaseTmpRegister(itemLocation);
  5729. break;
  5730. }
  5731. }
  5732. // If the iterator hasn't completed, skip assigning undefined.
  5733. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5734. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5735. // We're not done with the iterator, so assign the .next() value.
  5736. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5737. EmitGetObjectProperty(
  5738. valueLocation,
  5739. itemLocation,
  5740. Js::PropertyIds::value,
  5741. byteCodeGenerator,
  5742. funcInfo);
  5743. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5744. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5745. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5746. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5747. // iteratorAlreadyDone:
  5748. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5749. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueLocation, funcInfo->undefinedConstantRegister);
  5750. // beforeDefaultAssign:
  5751. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5752. if (elem->IsPattern())
  5753. {
  5754. // If we get an undefined value and have an initializer, use it in place of undefined.
  5755. if (init != nullptr)
  5756. {
  5757. /*
  5758. the IR builder uses two symbols for a temp register in the if else path
  5759. R9 <- R3
  5760. if (...)
  5761. R9 <- R2
  5762. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5763. hence we have to create a new temp
  5764. TEMP REG USED TO FIX THIS PRODUCES THIS
  5765. R9 <- R3
  5766. if (BrEq_A R9, R3)
  5767. R10 <- R2 :
  5768. else
  5769. R10 <- R9 : skipdefault
  5770. ... = R10[@@iterator] : loadIter
  5771. */
  5772. // Temp Register
  5773. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5774. byteCodeGenerator->StartStatement(init);
  5775. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5776. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5777. // check value is undefined
  5778. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5779. // Evaluate the default expression and assign it.
  5780. Emit(init, byteCodeGenerator, funcInfo, false);
  5781. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5782. funcInfo->ReleaseLoc(init);
  5783. // jmp to loadIter
  5784. byteCodeGenerator->Writer()->Br(loadIter);
  5785. // skipDefault:
  5786. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5787. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueLocationTmp, valueLocation);
  5788. // loadIter:
  5789. // @@iterator
  5790. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5791. byteCodeGenerator->EndStatement(init);
  5792. if (elem->nop == knopObjectPattern)
  5793. {
  5794. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5795. }
  5796. else
  5797. {
  5798. // Recursively emit a destructured array using the current .next() as the RHS.
  5799. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5800. }
  5801. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5802. }
  5803. else
  5804. {
  5805. if (elem->nop == knopObjectPattern)
  5806. {
  5807. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5808. }
  5809. else
  5810. {
  5811. // Recursively emit a destructured array using the current .next() as the RHS.
  5812. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5813. }
  5814. }
  5815. }
  5816. else
  5817. {
  5818. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5819. }
  5820. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5821. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5822. if (list->nop != knopList)
  5823. {
  5824. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5825. }
  5826. funcInfo->ReleaseTmpRegister(valueLocation);
  5827. funcInfo->ReleaseTmpRegister(doneLocation);
  5828. funcInfo->ReleaseTmpRegister(itemLocation);
  5829. if (isAssignmentTarget)
  5830. {
  5831. funcInfo->ReleaseReference(elem);
  5832. }
  5833. byteCodeGenerator->EndStatement(elem);
  5834. if (list->nop == knopList)
  5835. {
  5836. list = list->AsParseNodeBin()->pnode2;
  5837. }
  5838. else
  5839. {
  5840. break;
  5841. }
  5842. }
  5843. // If we saw a rest element, emit the rest array.
  5844. if (elem != nullptr && elem->nop == knopEllipsis)
  5845. {
  5846. EmitDestructuredRestArray(
  5847. elem,
  5848. iteratorLocation,
  5849. nextMethodReg,
  5850. shouldCallReturnFunctionLocation,
  5851. shouldCallReturnFunctionLocationFinally,
  5852. byteCodeGenerator,
  5853. funcInfo);
  5854. }
  5855. }
  5856. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5857. {
  5858. Js::OpCode op;
  5859. Js::ByteCodeLabel label;
  5860. Js::RegSlot reg1;
  5861. Js::RegSlot reg2;
  5862. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5863. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5864. };
  5865. // Generating
  5866. // try {
  5867. // CallIteratorClose
  5868. // } catch (e) {
  5869. // do nothing
  5870. // }
  5871. void EmitTryCatchAroundIteratorClose(
  5872. Js::RegSlot iteratorLocation,
  5873. Js::ByteCodeLabel endLabel,
  5874. ByteCodeGenerator *byteCodeGenerator,
  5875. FuncInfo *funcInfo,
  5876. bool isAsync)
  5877. {
  5878. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5879. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5880. // Jump cleanup is only needed in a for-await loop since it will await the
  5881. // result of the call to the return method. Otherwise there can be no jump.
  5882. if (isAsync)
  5883. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  5884. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo, isAsync);
  5885. if (isAsync)
  5886. byteCodeGenerator->PopJumpCleanup();
  5887. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5888. byteCodeGenerator->Writer()->Br(endLabel);
  5889. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5890. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5891. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5892. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5893. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5894. }
  5895. // Generating
  5896. // catch(e) {
  5897. // if (shouldCallReturn)
  5898. // CallReturnWhichWrappedByTryCatch
  5899. // throw e;
  5900. // }
  5901. void EmitIteratorTopLevelCatch(
  5902. Js::ByteCodeLabel catchLabel,
  5903. Js::RegSlot iteratorLocation,
  5904. Js::RegSlot shouldCallReturnLocation,
  5905. Js::RegSlot shouldCallReturnLocationFinally,
  5906. ByteCodeGenerator* byteCodeGenerator,
  5907. FuncInfo* funcInfo,
  5908. bool isAsync)
  5909. {
  5910. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5911. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5912. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5913. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5914. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5915. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5916. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  5917. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5918. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5919. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnLocationFinally);
  5920. EmitTryCatchAroundIteratorClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo, isAsync);
  5921. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5922. // Rethrow the exception
  5923. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5924. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5925. byteCodeGenerator->PopJumpCleanup();
  5926. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5927. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5928. }
  5929. // Generating
  5930. // finally {
  5931. // if (shouldCallReturn)
  5932. // CallReturn
  5933. // }
  5934. void EmitIteratorTopLevelFinally(
  5935. Js::ByteCodeLabel finallyLabel,
  5936. Js::RegSlot iteratorLocation,
  5937. Js::RegSlot shouldCallReturnLocation,
  5938. Js::RegSlot yieldExceptionLocation,
  5939. Js::RegSlot yieldOffsetLocation,
  5940. ByteCodeGenerator* byteCodeGenerator,
  5941. FuncInfo* funcInfo,
  5942. bool hasYield,
  5943. bool isAsync)
  5944. {
  5945. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5946. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5947. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5948. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5949. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5950. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5951. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5952. byteCodeGenerator->PushJumpCleanupForTry(
  5953. Js::OpCode::ResumeFinally,
  5954. finallyLabel,
  5955. yieldExceptionLocation,
  5956. yieldOffsetLocation);
  5957. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5958. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5959. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo, isAsync);
  5960. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5961. byteCodeGenerator->PopJumpCleanup();
  5962. if (hasYield)
  5963. {
  5964. Assert(funcInfo->byteCodeFunction->IsCoroutine());
  5965. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5966. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5967. }
  5968. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5969. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5970. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5971. }
  5972. void EmitIteratorCatchAndFinally(
  5973. Js::ByteCodeLabel catchLabel,
  5974. Js::ByteCodeLabel finallyLabel,
  5975. Js::RegSlot iteratorLocation,
  5976. Js::RegSlot shouldCallReturnFunctionLocation,
  5977. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5978. Js::RegSlot yieldExceptionLocation,
  5979. Js::RegSlot yieldOffsetLocation,
  5980. ByteCodeGenerator* byteCodeGenerator,
  5981. FuncInfo* funcInfo,
  5982. bool hasYield,
  5983. bool isAsync = false)
  5984. {
  5985. byteCodeGenerator->PopJumpCleanup();
  5986. EmitIteratorTopLevelCatch(
  5987. catchLabel,
  5988. iteratorLocation,
  5989. shouldCallReturnFunctionLocation,
  5990. shouldCallReturnFunctionLocationFinally,
  5991. byteCodeGenerator,
  5992. funcInfo,
  5993. isAsync);
  5994. byteCodeGenerator->PopJumpCleanup();
  5995. EmitIteratorTopLevelFinally(
  5996. finallyLabel,
  5997. iteratorLocation,
  5998. shouldCallReturnFunctionLocationFinally,
  5999. yieldExceptionLocation,
  6000. yieldOffsetLocation,
  6001. byteCodeGenerator,
  6002. funcInfo,
  6003. hasYield,
  6004. isAsync);
  6005. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  6006. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  6007. }
  6008. // Emit a wrapper try..finaly block around the destructuring elements
  6009. void EmitDestructuredArray(
  6010. ParseNode *lhs,
  6011. Js::RegSlot rhsLocation,
  6012. ByteCodeGenerator *byteCodeGenerator,
  6013. FuncInfo *funcInfo)
  6014. {
  6015. byteCodeGenerator->StartStatement(lhs);
  6016. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  6017. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  6018. Assert(lhs->nop == knopArrayPattern);
  6019. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  6020. if (list == nullptr)
  6021. { // Handline this case ([] = obj);
  6022. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  6023. // No elements to bind or assign.
  6024. funcInfo->ReleaseTmpRegister(iteratorLocation);
  6025. byteCodeGenerator->EndStatement(lhs);
  6026. return;
  6027. }
  6028. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  6029. EmitGetObjectMethod(
  6030. nextMethodReg,
  6031. iteratorLocation,
  6032. Js::PropertyIds::next,
  6033. byteCodeGenerator,
  6034. funcInfo);
  6035. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  6036. // this variable will be set to true.
  6037. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  6038. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  6039. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  6040. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  6041. byteCodeGenerator->SetHasFinally(true);
  6042. byteCodeGenerator->SetHasTry(true);
  6043. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  6044. Js::RegSlot regException = Js::Constants::NoRegister;
  6045. Js::RegSlot regOffset = Js::Constants::NoRegister;
  6046. bool hasYield = byteCodeGenerator->GetHasYield(lhs);
  6047. if (hasYield)
  6048. {
  6049. Assert(funcInfo->byteCodeFunction->IsCoroutine());
  6050. regException = funcInfo->AcquireTmpRegister();
  6051. regOffset = funcInfo->AcquireTmpRegister();
  6052. }
  6053. // Insert try node here
  6054. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  6055. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  6056. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  6057. if (hasYield)
  6058. {
  6059. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  6060. byteCodeGenerator->PushJumpCleanupForTry(
  6061. Js::OpCode::TryFinallyWithYield,
  6062. finallyLabel,
  6063. regException,
  6064. regOffset);
  6065. }
  6066. else
  6067. {
  6068. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  6069. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  6070. }
  6071. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  6072. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  6073. EmitDestructuredArrayCore(
  6074. list,
  6075. iteratorLocation,
  6076. nextMethodReg,
  6077. shouldCallReturnFunctionLocation,
  6078. shouldCallReturnFunctionLocationFinally,
  6079. byteCodeGenerator,
  6080. funcInfo);
  6081. EmitIteratorCatchAndFinally(
  6082. catchLabel,
  6083. finallyLabel,
  6084. iteratorLocation,
  6085. shouldCallReturnFunctionLocation,
  6086. shouldCallReturnFunctionLocationFinally,
  6087. regException,
  6088. regOffset,
  6089. byteCodeGenerator,
  6090. funcInfo,
  6091. hasYield);
  6092. funcInfo->ReleaseTmpRegister(nextMethodReg);
  6093. funcInfo->ReleaseTmpRegister(iteratorLocation);
  6094. byteCodeGenerator->EndStatement(lhs);
  6095. }
  6096. void EmitNameInvoke(Js::RegSlot lhsLocation,
  6097. Js::RegSlot objectLocation,
  6098. Js::RegSlot computedPropIdArrLocation,
  6099. uint32 *computedIndex,
  6100. bool hasRest,
  6101. ParseNodePtr nameNode,
  6102. ByteCodeGenerator* byteCodeGenerator,
  6103. FuncInfo* funcInfo)
  6104. {
  6105. Assert(nameNode != nullptr);
  6106. if (nameNode->nop == knopComputedName)
  6107. {
  6108. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  6109. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  6110. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  6111. if (hasRest)
  6112. {
  6113. byteCodeGenerator->Writer()->Slot(Js::OpCode::StPropIdArrFromVar, pnode1->location, computedPropIdArrLocation, *computedIndex);
  6114. (*computedIndex)++;
  6115. }
  6116. funcInfo->ReleaseLoc(pnode1);
  6117. }
  6118. else
  6119. {
  6120. Assert(nameNode->nop == knopStr);
  6121. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  6122. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  6123. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  6124. }
  6125. }
  6126. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  6127. Js::RegSlot rhsLocation,
  6128. ParseNodePtr initializer,
  6129. bool isNonPatternAssignmentTarget,
  6130. ByteCodeGenerator *byteCodeGenerator,
  6131. FuncInfo *funcInfo)
  6132. {
  6133. // 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
  6134. Js::ByteCodeLabel useDefault = -1;
  6135. Js::ByteCodeLabel end = -1;
  6136. Js::RegSlot rhsLocationTmp = rhsLocation;
  6137. if (initializer != nullptr)
  6138. {
  6139. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  6140. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  6141. end = byteCodeGenerator->Writer()->DefineLabel();
  6142. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  6143. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  6144. byteCodeGenerator->Writer()->Br(end);
  6145. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  6146. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  6147. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, rhsLocationTmp, initializer->location);
  6148. funcInfo->ReleaseLoc(initializer);
  6149. byteCodeGenerator->Writer()->MarkLabel(end);
  6150. }
  6151. if (lhsElementNode->nop == knopArrayPattern)
  6152. {
  6153. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6154. }
  6155. else if (lhsElementNode->nop == knopObjectPattern)
  6156. {
  6157. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6158. }
  6159. else if (isNonPatternAssignmentTarget)
  6160. {
  6161. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6162. }
  6163. else
  6164. {
  6165. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6166. }
  6167. if (initializer != nullptr)
  6168. {
  6169. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  6170. }
  6171. }
  6172. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  6173. Js::RegSlot rhsLocation,
  6174. Js::RegSlot propIdArrLocation,
  6175. Js::RegSlot computedPropIdArrLocation,
  6176. uint32 *computedIndex,
  6177. bool hasRest,
  6178. ByteCodeGenerator *byteCodeGenerator,
  6179. FuncInfo *funcInfo)
  6180. {
  6181. Assert(memberNode->nop == knopObjectPatternMember || memberNode->nop == knopEllipsis);
  6182. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  6183. ParseNodePtr lhsElementNode = nullptr;
  6184. if (memberNode->nop == knopObjectPatternMember)
  6185. {
  6186. EmitNameInvoke(nameLocation, rhsLocation, computedPropIdArrLocation,
  6187. computedIndex, hasRest, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  6188. // Imagine we are transforming
  6189. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  6190. lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  6191. }
  6192. else
  6193. {
  6194. // memberNode->nop == knopEllipsis, aka we are performing Rest operation
  6195. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, nameLocation);
  6196. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Restify, rhsLocation, nameLocation, propIdArrLocation, computedPropIdArrLocation);
  6197. lhsElementNode = memberNode->AsParseNodeUni()->pnode1;
  6198. }
  6199. ParseNodePtr init = nullptr;
  6200. if (lhsElementNode->IsVarLetOrConst())
  6201. {
  6202. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  6203. }
  6204. else if (lhsElementNode->nop == knopAsg)
  6205. {
  6206. init = lhsElementNode->AsParseNodeBin()->pnode2;
  6207. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  6208. }
  6209. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  6210. funcInfo->ReleaseTmpRegister(nameLocation);
  6211. }
  6212. void EmitObjectPropertyIdsToArray(ByteCodeGenerator *byteCodeGenerator,
  6213. Js::PropertyId *ids,
  6214. ParseNodePtr memberNodes,
  6215. uint32 staticCount,
  6216. bool *hasComputedProps)
  6217. {
  6218. uint32 index = 0;
  6219. Parser::ForEachItemInList(memberNodes, [&](ParseNodePtr current) {
  6220. if (current->nop != knopEllipsis)
  6221. {
  6222. ParseNodePtr nameNode = current->AsParseNodeBin()->pnode1;
  6223. Assert(nameNode != nullptr);
  6224. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  6225. if (nameNode->nop == knopStr)
  6226. {
  6227. if (index >= staticCount)
  6228. {
  6229. Js::Throw::InternalError();
  6230. return;
  6231. }
  6232. ids[index] = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  6233. index++;
  6234. }
  6235. else
  6236. {
  6237. *hasComputedProps = true;
  6238. }
  6239. }
  6240. });
  6241. }
  6242. void EmitDestructuredObject(ParseNode *lhs,
  6243. Js::RegSlot rhsLocationOrig,
  6244. ByteCodeGenerator *byteCodeGenerator,
  6245. FuncInfo *funcInfo)
  6246. {
  6247. Assert(lhs->nop == knopObjectPattern);
  6248. ParseNodeObjLit *pnodeObjLit = lhs->AsParseNodeObjLit();
  6249. ParseNodePtr pnode1 = pnodeObjLit->pnode1;
  6250. uint32 staticCount = pnodeObjLit->staticCount;
  6251. uint32 computedCount = pnodeObjLit->computedCount;
  6252. bool hasRest = pnodeObjLit->hasRest;
  6253. bool hasComputedProps = false;
  6254. byteCodeGenerator->StartStatement(lhs);
  6255. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  6256. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  6257. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  6258. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  6259. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  6260. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  6261. if (pnode1 != nullptr)
  6262. {
  6263. Js::RegSlot propIdArrLocation = Js::Constants::NoRegister;
  6264. Js::RegSlot computedPropIdArrLocation = Js::Constants::NoRegister;
  6265. if (hasRest)
  6266. {
  6267. uint extraAlloc = UInt32Math::Mul(staticCount, sizeof(Js::PropertyId));
  6268. uint auxSize = UInt32Math::Add(sizeof(Js::PropertyIdArray), extraAlloc);
  6269. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::PropertyIdArray, staticCount, 0);
  6270. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember || pnode1->nop == knopEllipsis);
  6271. EmitObjectPropertyIdsToArray(byteCodeGenerator, propIds->elements, pnode1, staticCount, &hasComputedProps);
  6272. // Load static PropertyIdArray here
  6273. propIdArrLocation = funcInfo->AcquireTmpRegister();
  6274. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::LdPropIds, propIdArrLocation, propIds, auxSize, staticCount);
  6275. if (hasComputedProps)
  6276. {
  6277. computedPropIdArrLocation = funcInfo->AcquireTmpRegister();
  6278. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewPropIdArrForCompProps, computedPropIdArrLocation, computedCount);
  6279. }
  6280. else
  6281. {
  6282. computedPropIdArrLocation = propIdArrLocation;
  6283. }
  6284. }
  6285. uint32 index = 0;
  6286. Parser::ForEachItemInList(pnode1, [&](ParseNodePtr memberNode) {
  6287. EmitDestructuredObjectMember(memberNode, rhsLocation, propIdArrLocation, computedPropIdArrLocation,
  6288. &index, hasRest, byteCodeGenerator, funcInfo);
  6289. });
  6290. if (hasRest)
  6291. {
  6292. if (hasComputedProps)
  6293. {
  6294. funcInfo->ReleaseTmpRegister(computedPropIdArrLocation);
  6295. }
  6296. funcInfo->ReleaseTmpRegister(propIdArrLocation);
  6297. }
  6298. }
  6299. funcInfo->ReleaseTmpRegister(rhsLocation);
  6300. byteCodeGenerator->EndStatement(lhs);
  6301. }
  6302. void EmitAssignment(
  6303. ParseNode *asgnNode,
  6304. ParseNode *lhs,
  6305. Js::RegSlot rhsLocation,
  6306. ByteCodeGenerator *byteCodeGenerator,
  6307. FuncInfo *funcInfo)
  6308. {
  6309. switch (lhs->nop)
  6310. {
  6311. // assignment to a local or global variable
  6312. case knopVarDecl:
  6313. case knopLetDecl:
  6314. case knopConstDecl:
  6315. {
  6316. Symbol *sym = lhs->AsParseNodeVar()->sym;
  6317. Assert(sym != nullptr);
  6318. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  6319. break;
  6320. }
  6321. case knopName:
  6322. {
  6323. // Special names like 'this' or 'new.target' cannot be assigned to
  6324. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  6325. if (pnodeNameLhs->IsSpecialName())
  6326. {
  6327. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6328. }
  6329. else
  6330. {
  6331. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  6332. }
  6333. break;
  6334. }
  6335. // x.y =
  6336. case knopDot:
  6337. {
  6338. // PutValue(x, "y", rhs)
  6339. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6340. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6341. {
  6342. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6343. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  6344. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6345. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  6346. Js::OpCode stFldOpCode = funcInfo->GetIsStrictMode() ? Js::OpCode::StSuperFldStrict : Js::OpCode::StSuperFld;
  6347. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(stFldOpCode, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  6348. }
  6349. else
  6350. {
  6351. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  6352. byteCodeGenerator->Writer()->PatchableProperty(
  6353. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false, byteCodeGenerator->forceStrictModeForClassComputedPropertyName), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6354. }
  6355. break;
  6356. }
  6357. case knopIndex:
  6358. {
  6359. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  6360. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6361. {
  6362. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  6363. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  6364. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  6365. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6366. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6367. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  6368. }
  6369. byteCodeGenerator->Writer()->Element(
  6370. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  6371. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  6372. break;
  6373. }
  6374. case knopObjectPattern:
  6375. {
  6376. // Copy the rhs value to be the result of the assignment if needed.
  6377. if (asgnNode != nullptr)
  6378. {
  6379. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6380. }
  6381. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6382. }
  6383. case knopArrayPattern:
  6384. {
  6385. // Copy the rhs value to be the result of the assignment if needed.
  6386. if (asgnNode != nullptr)
  6387. {
  6388. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6389. }
  6390. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6391. }
  6392. case knopArray:
  6393. case knopObject:
  6394. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6395. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6396. // down early vs. runtime errors for destructuring.
  6397. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6398. break;
  6399. default:
  6400. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6401. break;
  6402. }
  6403. if (asgnNode != nullptr)
  6404. {
  6405. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6406. if (asgnNode->location != rhsLocation)
  6407. {
  6408. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6409. }
  6410. }
  6411. }
  6412. void EmitLoad(
  6413. ParseNode *lhs,
  6414. ByteCodeGenerator *byteCodeGenerator,
  6415. FuncInfo *funcInfo)
  6416. {
  6417. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6418. // in the process.
  6419. // We usually get here as part of an op-equiv expression: x.y += z;
  6420. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6421. switch (lhs->nop)
  6422. {
  6423. // load of a local or global variable
  6424. case knopName:
  6425. {
  6426. funcInfo->AcquireLoc(lhs);
  6427. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6428. break;
  6429. }
  6430. // = x.y
  6431. case knopDot:
  6432. {
  6433. // get field id for "y"
  6434. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6435. funcInfo->AcquireLoc(lhs);
  6436. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6437. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6438. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6439. break;
  6440. }
  6441. case knopIndex:
  6442. funcInfo->AcquireLoc(lhs);
  6443. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6444. byteCodeGenerator->Writer()->Element(
  6445. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6446. break;
  6447. // f(x) +=
  6448. case knopCall:
  6449. {
  6450. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6451. if (pnodeCallLhs->isSuperCall)
  6452. {
  6453. funcInfo->AcquireLoc(pnodeCallLhs);
  6454. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6455. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCallLhs->AsParseNodeSuperCall(), /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6456. }
  6457. else if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6458. {
  6459. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6460. Assert(CountArguments(args) == 2); // import() takes one argument
  6461. Emit(args, byteCodeGenerator, funcInfo, false);
  6462. funcInfo->ReleaseLoc(args);
  6463. funcInfo->AcquireLoc(pnodeCallLhs);
  6464. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6465. }
  6466. else
  6467. {
  6468. funcInfo->AcquireLoc(pnodeCallLhs);
  6469. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6470. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6471. }
  6472. break;
  6473. }
  6474. default:
  6475. funcInfo->AcquireLoc(lhs);
  6476. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6477. break;
  6478. }
  6479. }
  6480. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6481. {
  6482. if (pnode != nullptr)
  6483. {
  6484. while (pnode->nop == knopList)
  6485. {
  6486. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6487. pnode = pnode->AsParseNodeBin()->pnode2;
  6488. }
  6489. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6490. }
  6491. }
  6492. void EmitOneArg(
  6493. ParseNode *pnode,
  6494. BOOL fAssignRegs,
  6495. ByteCodeGenerator *byteCodeGenerator,
  6496. FuncInfo *funcInfo,
  6497. Js::ProfileId callSiteId,
  6498. Js::ArgSlot &argIndex,
  6499. Js::ArgSlot &spreadIndex,
  6500. Js::RegSlot argTempLocation,
  6501. bool emitProfiledArgout,
  6502. Js::AuxArray<uint32> *spreadIndices = nullptr
  6503. )
  6504. {
  6505. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6506. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6507. // We just need to emit the ArgOut instructions.
  6508. if (fAssignRegs)
  6509. {
  6510. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6511. }
  6512. if (pnode->nop == knopEllipsis)
  6513. {
  6514. Assert(spreadIndices != nullptr);
  6515. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6516. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6517. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6518. if (noArgOuts)
  6519. {
  6520. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6521. }
  6522. else
  6523. {
  6524. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6525. }
  6526. funcInfo->ReleaseTmpRegister(regVal);
  6527. }
  6528. else
  6529. {
  6530. if (noArgOuts)
  6531. {
  6532. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6533. }
  6534. else
  6535. {
  6536. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6537. }
  6538. }
  6539. argIndex++;
  6540. if (fAssignRegs)
  6541. {
  6542. funcInfo->ReleaseLoc(pnode);
  6543. }
  6544. }
  6545. size_t EmitArgsWithArgOutsAtEnd(
  6546. ParseNode *pnode,
  6547. BOOL fAssignRegs,
  6548. ByteCodeGenerator *byteCodeGenerator,
  6549. FuncInfo *funcInfo,
  6550. Js::ProfileId callSiteId,
  6551. Js::RegSlot thisLocation,
  6552. Js::ArgSlot argsCountForStartCall,
  6553. bool emitProfiledArgouts,
  6554. Js::AuxArray<uint32> *spreadIndices = nullptr
  6555. )
  6556. {
  6557. AssertOrFailFast(pnode != nullptr);
  6558. Js::ArgSlot argIndex = 0;
  6559. Js::ArgSlot spreadIndex = 0;
  6560. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6561. Js::RegSlot firstArgTempLocation = argTempLocation;
  6562. while (pnode->nop == knopList)
  6563. {
  6564. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6565. pnode = pnode->AsParseNodeBin()->pnode2;
  6566. argTempLocation = funcInfo->AcquireTmpRegister();
  6567. }
  6568. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6569. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6570. // Emit all argOuts now
  6571. if (thisLocation != Js::Constants::NoRegister)
  6572. {
  6573. // Emit the "this" object.
  6574. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6575. }
  6576. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6577. {
  6578. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6579. }
  6580. // Now release all those temps register
  6581. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6582. {
  6583. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6584. }
  6585. return argIndex;
  6586. }
  6587. size_t EmitArgs(
  6588. ParseNode *pnode,
  6589. BOOL fAssignRegs,
  6590. ByteCodeGenerator *byteCodeGenerator,
  6591. FuncInfo *funcInfo,
  6592. Js::ProfileId callSiteId,
  6593. bool emitProfiledArgouts,
  6594. Js::AuxArray<uint32> *spreadIndices = nullptr
  6595. )
  6596. {
  6597. Js::ArgSlot argIndex = 0;
  6598. Js::ArgSlot spreadIndex = 0;
  6599. if (pnode != nullptr)
  6600. {
  6601. while (pnode->nop == knopList)
  6602. {
  6603. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6604. pnode = pnode->AsParseNodeBin()->pnode2;
  6605. }
  6606. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6607. }
  6608. return argIndex;
  6609. }
  6610. void EmitArgListStart(
  6611. Js::RegSlot thisLocation,
  6612. ByteCodeGenerator *byteCodeGenerator,
  6613. FuncInfo *funcInfo,
  6614. Js::ProfileId callSiteId)
  6615. {
  6616. if (thisLocation != Js::Constants::NoRegister)
  6617. {
  6618. // Emit the "this" object.
  6619. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6620. }
  6621. }
  6622. Js::ArgSlot EmitArgListEnd(
  6623. ParseNode *pnode,
  6624. Js::RegSlot thisLocation,
  6625. Js::RegSlot evalLocation,
  6626. Js::RegSlot newTargetLocation,
  6627. ByteCodeGenerator *byteCodeGenerator,
  6628. FuncInfo *funcInfo,
  6629. size_t argIndex,
  6630. Js::ProfileId callSiteId)
  6631. {
  6632. BOOL fEvalInModule = false;
  6633. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6634. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6635. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6636. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6637. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6638. Js::ArgSlot evalIndex;
  6639. if (fIsEval && argSlotIndex > 0)
  6640. {
  6641. Assert(!fHasNewTarget);
  6642. // Pass the frame display as an extra argument to "eval".
  6643. // Do this only if eval is called with some args
  6644. Js::RegSlot evalEnv;
  6645. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6646. {
  6647. // Use current environment as the environment for the function being called when:
  6648. // - this is the root global function (not an eval's global function)
  6649. // - this is an eval's global function that is not in strict mode (see else block)
  6650. evalEnv = funcInfo->GetEnvRegister();
  6651. }
  6652. else
  6653. {
  6654. // Use the frame display as the environment for the function being called when:
  6655. // - this is not a global function and thus it will have its own scope
  6656. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6657. // has its own scope
  6658. evalEnv = funcInfo->frameDisplayRegister;
  6659. }
  6660. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6661. // Passing the FrameDisplay as an extra argument
  6662. evalIndex = argSlotIndex + 1;
  6663. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6664. {
  6665. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6666. }
  6667. else
  6668. {
  6669. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6670. }
  6671. }
  6672. if (fHasNewTarget)
  6673. {
  6674. Assert(!fIsEval);
  6675. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6676. }
  6677. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6678. // eval and no args passed, return 1 as argument count
  6679. if (fIsEval && pnode == nullptr)
  6680. {
  6681. return 1;
  6682. }
  6683. return argIntCount;
  6684. }
  6685. Js::ArgSlot EmitArgList(
  6686. ParseNode *pnode,
  6687. Js::RegSlot thisLocation,
  6688. Js::RegSlot newTargetLocation,
  6689. BOOL fIsEval,
  6690. BOOL fAssignRegs,
  6691. ByteCodeGenerator *byteCodeGenerator,
  6692. FuncInfo *funcInfo,
  6693. Js::ProfileId callSiteId,
  6694. Js::ArgSlot argsCountForStartCall,
  6695. bool emitArgOutsAtEnd,
  6696. bool emitProfiledArgouts,
  6697. uint16 spreadArgCount = 0,
  6698. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6699. {
  6700. // This function emits the arguments for a call.
  6701. // ArgOut's with uses immediately following defs.
  6702. if (!emitArgOutsAtEnd)
  6703. {
  6704. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6705. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6706. }
  6707. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6708. //
  6709. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6710. // This would be used while generating frameDisplay in EmitArgListEnd.
  6711. //
  6712. if (fIsEval)
  6713. {
  6714. evalLocation = funcInfo->AcquireTmpRegister();
  6715. }
  6716. if (spreadArgCount > 0)
  6717. {
  6718. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6719. Assert(spreadIndices != nullptr);
  6720. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6721. }
  6722. size_t argIndex = 0;
  6723. if (emitArgOutsAtEnd)
  6724. {
  6725. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6726. }
  6727. else
  6728. {
  6729. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6730. }
  6731. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6732. if (fIsEval)
  6733. {
  6734. funcInfo->ReleaseTmpRegister(evalLocation);
  6735. }
  6736. return argumentsCount;
  6737. }
  6738. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6739. {
  6740. uint index = 0;
  6741. while (args->nop == knopList && index < argCount)
  6742. {
  6743. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6744. {
  6745. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6746. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6747. }
  6748. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6749. {
  6750. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6751. #if ! FLOATVAR
  6752. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6753. #endif
  6754. vars[index++] = number;
  6755. }
  6756. else
  6757. {
  6758. AnalysisAssert(false);
  6759. }
  6760. args = args->AsParseNodeBin()->pnode2;
  6761. }
  6762. if (index == argCount)
  6763. {
  6764. Assert(false);
  6765. Js::Throw::InternalError();
  6766. return;
  6767. }
  6768. if (args->nop == knopInt)
  6769. {
  6770. int value = args->AsParseNodeInt()->lw;
  6771. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6772. }
  6773. else if (args->nop == knopFlt)
  6774. {
  6775. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6776. #if ! FLOATVAR
  6777. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6778. #endif
  6779. vars[index++] = number;
  6780. }
  6781. else
  6782. {
  6783. AnalysisAssert(false);
  6784. }
  6785. }
  6786. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6787. {
  6788. uint index = 0;
  6789. while (args->nop == knopList && index < argCount)
  6790. {
  6791. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6792. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6793. args = args->AsParseNodeBin()->pnode2;
  6794. }
  6795. if (index >= argCount)
  6796. {
  6797. Js::Throw::InternalError();
  6798. return;
  6799. }
  6800. Assert(args->nop == knopInt);
  6801. vars[index++] = args->AsParseNodeInt()->lw;
  6802. Assert(index == argCount);
  6803. }
  6804. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6805. {
  6806. uint index = 0;
  6807. while (args->nop == knopList && index < argCount)
  6808. {
  6809. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6810. if (nop == knopInt)
  6811. {
  6812. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6813. }
  6814. else
  6815. {
  6816. Assert(nop == knopFlt);
  6817. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6818. }
  6819. args = args->AsParseNodeBin()->pnode2;
  6820. }
  6821. if (index >= argCount)
  6822. {
  6823. Js::Throw::InternalError();
  6824. return;
  6825. }
  6826. if (args->nop == knopInt)
  6827. {
  6828. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6829. }
  6830. else
  6831. {
  6832. Assert(args->nop == knopFlt);
  6833. vars[index++] = args->AsParseNodeFloat()->dbl;
  6834. }
  6835. Assert(index == argCount);
  6836. }
  6837. //
  6838. // Called when we have new Ctr(constant, constant...)
  6839. //
  6840. Js::ArgSlot EmitNewObjectOfConstants(
  6841. ParseNode *pnode,
  6842. ByteCodeGenerator *byteCodeGenerator,
  6843. FuncInfo *funcInfo,
  6844. unsigned int argCount)
  6845. {
  6846. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6847. // Create the vars array
  6848. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6849. // Emit all constants to the vars array
  6850. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6851. // Finish the arg list
  6852. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6853. pnode->AsParseNodeCall()->pnodeArgs,
  6854. Js::Constants::NoRegister,
  6855. Js::Constants::NoRegister,
  6856. Js::Constants::NoRegister,
  6857. byteCodeGenerator,
  6858. funcInfo,
  6859. argCount - 1,
  6860. Js::Constants::NoProfileId);
  6861. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6862. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6863. // Generate the opcode with vars
  6864. byteCodeGenerator->Writer()->AuxiliaryContext(
  6865. Js::OpCode::NewScObject_A,
  6866. funcInfo->AcquireLoc(pnode),
  6867. vars,
  6868. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6869. pnode->AsParseNodeCall()->pnodeTarget->location);
  6870. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6871. return actualArgCount;
  6872. }
  6873. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6874. {
  6875. Js::OpCode opcode;
  6876. if (!isRoot)
  6877. {
  6878. if (callObjLocation == funcInfo->frameObjRegister)
  6879. {
  6880. opcode = Js::OpCode::LdLocalMethodFld;
  6881. }
  6882. else
  6883. {
  6884. opcode = Js::OpCode::LdMethodFld;
  6885. }
  6886. }
  6887. else if (isScoped)
  6888. {
  6889. opcode = Js::OpCode::ScopedLdMethodFld;
  6890. }
  6891. else
  6892. {
  6893. opcode = Js::OpCode::LdRootMethodFld;
  6894. }
  6895. if (isScoped || !isRoot)
  6896. {
  6897. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6898. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6899. if (callObjLocation == funcInfo->frameObjRegister)
  6900. {
  6901. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6902. }
  6903. else
  6904. {
  6905. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6906. }
  6907. }
  6908. else
  6909. {
  6910. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6911. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6912. }
  6913. }
  6914. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6915. {
  6916. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6917. // the global object, etc.)
  6918. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6919. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6920. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6921. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6922. }
  6923. // lhs.apply(this, arguments);
  6924. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6925. {
  6926. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6927. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6928. Assert(applyNode->nop == knopDot);
  6929. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6930. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6931. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6932. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6933. Assert(applyNode->nop == knopDot);
  6934. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6935. funcInfo->AcquireLoc(applyNode);
  6936. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6937. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6938. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6939. // call for apply, we won't remove the entry for "apply" cacheId from
  6940. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6941. // have removed an entry from a map upon seeing its corresponding call.
  6942. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6943. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6944. Assert(argSym && argSym->IsArguments());
  6945. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6946. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6947. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6948. // If apply is overridden, bail to slow path.
  6949. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6950. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6951. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6952. // may crash if we try to unbox it on the store.
  6953. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6954. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6955. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6956. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6957. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6958. funcInfo->ReleaseTmpRegister(argCountLocation);
  6959. funcInfo->ReleaseTmpRegister(stackArgReg);
  6960. funcInfo->ReleaseLoc(applyNode);
  6961. funcInfo->ReleaseLoc(funcNode);
  6962. // Clear these nodes as they are going to be used to re-generate the slow path.
  6963. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6964. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6965. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6966. // slow path
  6967. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6968. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6969. {
  6970. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6971. }
  6972. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6973. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6974. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6975. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6976. }
  6977. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6978. {
  6979. // Load a call target of the form x[y]().
  6980. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6981. }
  6982. void EmitCallTargetNoEvalComponents(
  6983. ParseNode *pnodeTarget,
  6984. BOOL fSideEffectArgs,
  6985. Js::RegSlot *thisLocation,
  6986. bool *releaseThisLocation,
  6987. Js::RegSlot *callObjLocation,
  6988. ByteCodeGenerator *byteCodeGenerator,
  6989. FuncInfo *funcInfo)
  6990. {
  6991. // We first get a reference to the call target, then evaluate the arguments, then
  6992. // evaluate the call target.
  6993. // - emit reference to target
  6994. // - copy instance to scratch reg if necessary.
  6995. // - assign this
  6996. // - assign instance for dynamic/global name
  6997. // - emit args
  6998. // - do call (CallFld/Elem/I)
  6999. *releaseThisLocation = true;
  7000. switch (pnodeTarget->nop)
  7001. {
  7002. case knopDot:
  7003. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7004. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7005. break;
  7006. case knopIndex:
  7007. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7008. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7009. break;
  7010. case knopName:
  7011. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  7012. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  7013. if (*thisLocation == Js::Constants::NoRegister)
  7014. {
  7015. *thisLocation = funcInfo->undefinedConstantRegister;
  7016. }
  7017. break;
  7018. default:
  7019. *thisLocation = funcInfo->undefinedConstantRegister;
  7020. break;
  7021. }
  7022. }
  7023. void EmitCallTarget(
  7024. ParseNode *pnodeTarget,
  7025. BOOL fSideEffectArgs,
  7026. Js::RegSlot *thisLocation,
  7027. bool *releaseThisLocation,
  7028. Js::RegSlot *callObjLocation,
  7029. ByteCodeGenerator *byteCodeGenerator,
  7030. FuncInfo *funcInfo,
  7031. Js::ProfileId * callApplyCallSiteId)
  7032. {
  7033. // - emit target
  7034. // - assign this
  7035. // - emit args
  7036. // - do call
  7037. // The call target is fully evaluated before the argument list. Note that we're not handling
  7038. // put-call cases here currently, as such cases only apply to host objects
  7039. // and are very unlikely to behave differently depending on the order of evaluation.
  7040. *releaseThisLocation = true;
  7041. switch (pnodeTarget->nop)
  7042. {
  7043. case knopDot:
  7044. {
  7045. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  7046. funcInfo->AcquireLoc(pnodeBinTarget);
  7047. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7048. // them from side-effects.
  7049. if (fSideEffectArgs)
  7050. {
  7051. // Though we're done with target evaluation after this point, still protect opnd1 from
  7052. // arg side-effects as it's the "this" pointer.
  7053. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  7054. }
  7055. Assert(pnodeBinTarget->pnode2->nop == knopName);
  7056. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  7057. {
  7058. funcInfo->EnsureCallSiteToCallApplyCallSiteMap();
  7059. *callApplyCallSiteId = byteCodeGenerator->GetNextCallApplyCallSiteId(Js::OpCode::CallI);
  7060. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  7061. }
  7062. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  7063. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  7064. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  7065. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  7066. {
  7067. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  7068. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  7069. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  7070. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  7071. // Function calls on the 'super' object should maintain current 'this' pointer.
  7072. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  7073. *releaseThisLocation = false;
  7074. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  7075. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld,
  7076. pnodeTarget->location, protoLocation, *thisLocation, cacheId, false);
  7077. }
  7078. else
  7079. {
  7080. *thisLocation = pnodeBinTarget->pnode1->location;
  7081. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  7082. }
  7083. break;
  7084. }
  7085. case knopIndex:
  7086. {
  7087. funcInfo->AcquireLoc(pnodeTarget);
  7088. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7089. // them from side-effects.
  7090. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  7091. {
  7092. // Though we're done with target evaluation after this point, still protect opnd1 from
  7093. // arg or opnd2 side-effects as it's the "this" pointer.
  7094. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  7095. }
  7096. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7097. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  7098. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  7099. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7100. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  7101. {
  7102. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  7103. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  7104. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  7105. // Function calls on the 'super' object should maintain current 'this' pointer
  7106. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  7107. *releaseThisLocation = false;
  7108. }
  7109. else
  7110. {
  7111. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7112. }
  7113. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  7114. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  7115. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  7116. {
  7117. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  7118. }
  7119. break;
  7120. }
  7121. case knopName:
  7122. {
  7123. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  7124. if (!pnodeNameTarget->IsSpecialName())
  7125. {
  7126. funcInfo->AcquireLoc(pnodeNameTarget);
  7127. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7128. // them from side-effects.
  7129. if (fSideEffectArgs)
  7130. {
  7131. SaveOpndValue(pnodeNameTarget, funcInfo);
  7132. }
  7133. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  7134. if (*callObjLocation != Js::Constants::NoRegister)
  7135. {
  7136. // Load the call target as a property of the instance.
  7137. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  7138. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7139. break;
  7140. }
  7141. }
  7142. // FALL THROUGH to evaluate call target.
  7143. }
  7144. default:
  7145. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7146. // them from side-effects.
  7147. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  7148. *thisLocation = funcInfo->undefinedConstantRegister;
  7149. break;
  7150. }
  7151. // "This" pointer should have been assigned by the above.
  7152. Assert(*thisLocation != Js::Constants::NoRegister);
  7153. }
  7154. void EmitCallI(
  7155. ParseNodeCall *pnodeCall,
  7156. BOOL fEvaluateComponents,
  7157. BOOL fIsEval,
  7158. BOOL fHasNewTarget,
  7159. uint32 actualArgCount,
  7160. ByteCodeGenerator *byteCodeGenerator,
  7161. FuncInfo *funcInfo,
  7162. Js::ProfileId callSiteId,
  7163. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7164. {
  7165. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  7166. // already evaluated.
  7167. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7168. Js::OpCode op;
  7169. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  7170. uint spreadExtraAlloc = 0;
  7171. bool isSuperCall = pnodeCall->isSuperCall;
  7172. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  7173. // check for integer overflow
  7174. if ((size_t)actualArgSlotCount != actualArgCount)
  7175. {
  7176. Js::Throw::OutOfMemory();
  7177. }
  7178. if (fEvaluateComponents && !isSuperCall)
  7179. {
  7180. // Release the call target operands we assigned above. If we didn't assign them here,
  7181. // we'll need them later, so we can't re-use them for the result of the call.
  7182. funcInfo->ReleaseLoc(pnodeTarget);
  7183. }
  7184. // Grab a register for the call result.
  7185. if (pnodeCall->isUsed)
  7186. {
  7187. funcInfo->AcquireLoc(pnodeCall);
  7188. }
  7189. if (fIsEval)
  7190. {
  7191. op = Js::OpCode::CallIExtendedFlags;
  7192. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  7193. }
  7194. else
  7195. {
  7196. if (isSuperCall)
  7197. {
  7198. callFlags = Js::CallFlags_New;
  7199. }
  7200. if (fHasNewTarget)
  7201. {
  7202. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  7203. }
  7204. if (pnodeCall->spreadArgCount > 0)
  7205. {
  7206. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  7207. }
  7208. else
  7209. {
  7210. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  7211. }
  7212. }
  7213. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  7214. {
  7215. if (isSuperCall)
  7216. {
  7217. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  7218. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  7219. }
  7220. else
  7221. {
  7222. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  7223. }
  7224. }
  7225. else
  7226. {
  7227. uint spreadIndicesSize = 0;
  7228. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  7229. if (pnodeCall->spreadArgCount > 0)
  7230. {
  7231. Assert(spreadIndices != nullptr);
  7232. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7233. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7234. options = Js::CallIExtended_SpreadArgs;
  7235. }
  7236. if (isSuperCall)
  7237. {
  7238. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  7239. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  7240. }
  7241. else
  7242. {
  7243. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  7244. }
  7245. }
  7246. if (pnodeCall->spreadArgCount > 0)
  7247. {
  7248. Assert(spreadExtraAlloc != 0);
  7249. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  7250. }
  7251. }
  7252. void EmitCallInstrNoEvalComponents(
  7253. ParseNodeCall *pnodeCall,
  7254. BOOL fIsEval,
  7255. BOOL fHasNewTarget,
  7256. Js::RegSlot thisLocation,
  7257. Js::RegSlot callObjLocation,
  7258. uint32 actualArgCount,
  7259. ByteCodeGenerator *byteCodeGenerator,
  7260. FuncInfo *funcInfo,
  7261. Js::ProfileId callSiteId,
  7262. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7263. {
  7264. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  7265. // it as part of doing the actual call.
  7266. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  7267. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  7268. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7269. switch (pnodeTarget->nop)
  7270. {
  7271. case knopDot:
  7272. {
  7273. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  7274. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  7275. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7276. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7277. }
  7278. break;
  7279. case knopIndex:
  7280. {
  7281. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  7282. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7283. }
  7284. break;
  7285. case knopName:
  7286. {
  7287. if (callObjLocation != Js::Constants::NoRegister)
  7288. {
  7289. // We still have to get the property from its instance, so emit CallFld.
  7290. if (thisLocation != callObjLocation)
  7291. {
  7292. funcInfo->ReleaseTmpRegister(thisLocation);
  7293. }
  7294. funcInfo->ReleaseTmpRegister(callObjLocation);
  7295. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  7296. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7297. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7298. break;
  7299. }
  7300. }
  7301. // FALL THROUGH
  7302. default:
  7303. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7304. break;
  7305. }
  7306. }
  7307. void EmitCallInstr(
  7308. ParseNodeCall *pnodeCall,
  7309. BOOL fIsEval,
  7310. BOOL fHasNewTarget,
  7311. Js::RegSlot thisLocation,
  7312. Js::RegSlot callObjLocation,
  7313. uint32 actualArgCount,
  7314. ByteCodeGenerator *byteCodeGenerator,
  7315. FuncInfo *funcInfo,
  7316. Js::ProfileId callSiteId,
  7317. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7318. {
  7319. // Emit a call instruction. The call target has been fully evaluated already, so we always
  7320. // emit a CallI through the register that holds the target value.
  7321. // Note that we don't handle !fEvaluateComponents cases at this point.
  7322. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  7323. if (thisLocation != Js::Constants::NoRegister)
  7324. {
  7325. funcInfo->ReleaseTmpRegister(thisLocation);
  7326. }
  7327. if (callObjLocation != Js::Constants::NoRegister &&
  7328. callObjLocation != thisLocation)
  7329. {
  7330. funcInfo->ReleaseTmpRegister(callObjLocation);
  7331. }
  7332. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7333. }
  7334. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7335. {
  7336. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  7337. argCount++; // include "this"
  7338. BOOL fSideEffectArgs = FALSE;
  7339. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  7340. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  7341. byteCodeGenerator->StartStatement(pnode);
  7342. // Start call, allocate out param space
  7343. funcInfo->StartRecordingOutArgs(argCount);
  7344. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7345. // them from side-effects.
  7346. if (fSideEffectArgs)
  7347. {
  7348. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  7349. }
  7350. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  7351. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  7352. {
  7353. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7354. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  7355. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  7356. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  7357. Assert(argCount == 1);
  7358. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7359. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7360. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  7361. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  7362. }
  7363. else
  7364. {
  7365. uint32 actualArgCount = 0;
  7366. if (IsCallOfConstants(pnode))
  7367. {
  7368. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7369. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7370. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  7371. }
  7372. else
  7373. {
  7374. Js::OpCode op;
  7375. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  7376. {
  7377. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  7378. }
  7379. else
  7380. {
  7381. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  7382. }
  7383. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7384. // Only emit profiled argouts if we're going to profile this call.
  7385. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7386. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7387. // Emit argouts at end for generators so that we don't need to restore them when bailing in
  7388. bool emitArgOutsAtEnd = pnode->AsParseNodeCall()->hasDestructuring || (funcInfo->byteCodeFunction->IsCoroutine() && pnode->AsParseNodeCall()->pnodeArgs != nullptr);
  7389. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7390. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, emitArgOutsAtEnd, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  7391. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7392. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  7393. {
  7394. Assert(spreadIndices != nullptr);
  7395. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7396. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7397. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7398. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7399. spreadIndices, spreadIndicesSize, callSiteId);
  7400. }
  7401. else
  7402. {
  7403. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7404. (uint16)actualArgCount, callSiteId);
  7405. }
  7406. }
  7407. Assert(argCount == actualArgCount);
  7408. }
  7409. // End call, pop param space
  7410. funcInfo->EndRecordingOutArgs(argCount);
  7411. return;
  7412. }
  7413. void EmitCall(
  7414. ParseNodeCall * pnodeCall,
  7415. ByteCodeGenerator* byteCodeGenerator,
  7416. FuncInfo* funcInfo,
  7417. BOOL fReturnValue,
  7418. BOOL fEvaluateComponents,
  7419. Js::RegSlot overrideThisLocation,
  7420. Js::RegSlot newTargetLocation)
  7421. {
  7422. // If the call returns a float, we'll note this in the byte code.
  7423. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7424. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7425. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7426. BOOL fSideEffectArgs = FALSE;
  7427. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7428. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7429. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7430. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7431. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7432. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7433. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7434. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7435. // "new" path, since then our native array handling can kick in.
  7436. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7437. return;*/
  7438. }
  7439. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7440. BOOL fIsEval = pnodeCall->isEvalCall;
  7441. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7442. if (fIsEval)
  7443. {
  7444. Assert(!fHasNewTarget);
  7445. //
  7446. // "eval" takes the closure environment as an extra argument
  7447. // Pass the closure env only if some argument is passed
  7448. // For just eval(), don't pass the closure environment
  7449. //
  7450. if (argCount > 1)
  7451. {
  7452. argCount++;
  7453. }
  7454. }
  7455. else if (fHasNewTarget)
  7456. {
  7457. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7458. // This is similar to how eval passes an extra argument for the frame display and is
  7459. // used to support cases where we need to pass both 'this' and new.target as part of
  7460. // a function call.
  7461. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7462. argCount++;
  7463. }
  7464. // argCount indicates the total arguments count including the extra arguments.
  7465. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7466. if (argCount < (unsigned int)argSlotCount)
  7467. {
  7468. Js::Throw::OutOfMemory();
  7469. }
  7470. if (fReturnValue)
  7471. {
  7472. pnodeCall->isUsed = true;
  7473. }
  7474. //
  7475. // Set up the call.
  7476. //
  7477. bool releaseThisLocation = true;
  7478. // We already emit the call target for super calls in EmitSuperCall
  7479. Js::ProfileId callApplyCallSiteId = Js::Constants::NoProfileId;
  7480. if (!fIsSuperCall)
  7481. {
  7482. if (!fEvaluateComponents)
  7483. {
  7484. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7485. }
  7486. else
  7487. {
  7488. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo, &callApplyCallSiteId);
  7489. }
  7490. }
  7491. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7492. if (overrideThisLocation != Js::Constants::NoRegister)
  7493. {
  7494. thisLocation = overrideThisLocation;
  7495. releaseThisLocation = false;
  7496. }
  7497. // Evaluate the arguments (nothing mode-specific here).
  7498. // Start call, allocate out param space
  7499. // 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
  7500. funcInfo->StartRecordingOutArgs(argCount);
  7501. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7502. if (callApplyCallSiteId != Js::Constants::NoProfileId)
  7503. {
  7504. funcInfo->callSiteToCallApplyCallSiteMap->AddNew(callSiteId, callApplyCallSiteId);
  7505. }
  7506. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7507. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7508. // Emit argouts at end for generators so that we don't need to restore them when bailing in
  7509. bool emitArgOutsAtEnd = pnodeCall->hasDestructuring || (funcInfo->byteCodeFunction->IsCoroutine() && pnodeCall->pnodeArgs != nullptr);
  7510. Js::AuxArray<uint32> *spreadIndices;
  7511. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, emitArgOutsAtEnd, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7512. if (!fEvaluateComponents)
  7513. {
  7514. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, fHasNewTarget, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7515. }
  7516. else
  7517. {
  7518. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7519. }
  7520. // End call, pop param space
  7521. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7522. }
  7523. void EmitInvoke(
  7524. Js::RegSlot location,
  7525. Js::RegSlot callObjLocation,
  7526. Js::PropertyId propertyId,
  7527. ByteCodeGenerator* byteCodeGenerator,
  7528. FuncInfo* funcInfo)
  7529. {
  7530. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7531. funcInfo->StartRecordingOutArgs(1);
  7532. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7533. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7534. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7535. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7536. }
  7537. void EmitInvoke(
  7538. Js::RegSlot location,
  7539. Js::RegSlot callObjLocation,
  7540. Js::PropertyId propertyId,
  7541. ByteCodeGenerator* byteCodeGenerator,
  7542. FuncInfo* funcInfo,
  7543. Js::RegSlot arg1Location)
  7544. {
  7545. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7546. funcInfo->StartRecordingOutArgs(2);
  7547. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7548. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7549. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7550. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7551. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7552. }
  7553. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7554. {
  7555. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7556. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7557. bool isFncDecl = exprNode->nop == knopFncDecl;
  7558. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7559. if (isFncDecl)
  7560. {
  7561. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7562. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7563. }
  7564. Js::RegSlot computedNamePropertyKey = Js::Constants::NoRegister;
  7565. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7566. // which makes this bytecode too late to influence the function.name.
  7567. if (nameNode->nop == knopComputedName)
  7568. {
  7569. // Computed property name
  7570. // Transparently pass the name expr
  7571. // The Emit will replace this with a temp register if necessary to preserve the value.
  7572. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7573. // Save the previous value of the flag to be restored later.
  7574. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7575. // Strict mode must be enforced on the evaluation of computed property names inside
  7576. // classes, thus enable the flag if the computed property name is a class member.
  7577. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7578. computedNamePropertyKey = funcInfo->AcquireTmpRegister();
  7579. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo, computedNamePropertyKey);
  7580. // Restore the flag's previous value.
  7581. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7582. if (isFncDecl)
  7583. {
  7584. if (exprNode->AsParseNodeFnc()->pnodeName == nullptr)
  7585. {
  7586. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, computedNamePropertyKey);
  7587. exprNode->AsParseNodeFnc()->SetHasComputedName();
  7588. }
  7589. }
  7590. else if (exprNode->nop == knopClassDecl)
  7591. {
  7592. if (exprNode->AsParseNodeClass()->pnodeName == nullptr)
  7593. {
  7594. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, computedNamePropertyKey);
  7595. exprNode->AsParseNodeClass()->pnodeConstructor->SetHasComputedName();
  7596. }
  7597. }
  7598. }
  7599. if (nameNode->nop == knopComputedName)
  7600. {
  7601. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7602. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7603. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7604. memberNode->nop == knopSetMember ?
  7605. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7606. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7607. // Save the previous value of the flag to be restored later.
  7608. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7609. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7610. // Strict mode must be enforced on the evaluation of computed property names inside
  7611. // classes, thus enable the flag if the computed property name is a class member.
  7612. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, computedNamePropertyKey, true,
  7613. byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  7614. // Restore the flag's previous value.
  7615. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7616. funcInfo->ReleaseLoc(exprNode);
  7617. funcInfo->ReleaseLoc(nameNode);
  7618. funcInfo->ReleaseTmpRegister(computedNamePropertyKey);
  7619. return;
  7620. }
  7621. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7622. if (useStore)
  7623. {
  7624. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7625. }
  7626. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7627. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7628. if (Js::PropertyIds::name == propertyId
  7629. && exprNode->nop == knopFncDecl
  7630. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7631. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7632. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7633. {
  7634. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7635. nameFunc->SetIsStaticNameFunction(true);
  7636. }
  7637. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7638. {
  7639. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7640. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7641. {
  7642. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7643. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7644. }
  7645. else
  7646. {
  7647. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7648. Js::OpCode patchablePropertyOpCode;
  7649. if (useStore)
  7650. {
  7651. patchablePropertyOpCode = stFldOpCode;
  7652. }
  7653. else if (isClassMember)
  7654. {
  7655. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7656. }
  7657. else
  7658. {
  7659. patchablePropertyOpCode = Js::OpCode::InitFld;
  7660. }
  7661. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7662. }
  7663. }
  7664. else
  7665. {
  7666. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7667. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7668. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7669. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7670. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7671. }
  7672. funcInfo->ReleaseLoc(exprNode);
  7673. if (propertyId == Js::PropertyIds::valueOf)
  7674. {
  7675. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7676. }
  7677. else if (propertyId == Js::PropertyIds::toString)
  7678. {
  7679. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7680. }
  7681. }
  7682. void EmitObjectSpreadNode(ParseNode *spreadNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7683. {
  7684. Js::RegSlot fromObjectLocation;
  7685. ParseNode *exprNode = spreadNode->AsParseNodeUni()->pnode1;
  7686. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7687. fromObjectLocation = exprNode->location;
  7688. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SpreadObjectLiteral, fromObjectLocation, objectLocation);
  7689. funcInfo->ReleaseLoc(exprNode);
  7690. }
  7691. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7692. {
  7693. if (memberList != nullptr)
  7694. {
  7695. while (memberList->nop == knopList)
  7696. {
  7697. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7698. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7699. memberList = memberList->AsParseNodeBin()->pnode2;
  7700. }
  7701. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7702. }
  7703. }
  7704. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7705. {
  7706. ParseNode *pmemberList = memberList;
  7707. unsigned int argCount = 0;
  7708. uint32 value;
  7709. Js::PropertyId propertyId;
  7710. //
  7711. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7712. // 2. Get the count of propertyIds
  7713. // 3. Create a propertyId array of size count
  7714. // 4. Put the propIds in the auxiliary area
  7715. // 5. Get the objectLiteralCacheId
  7716. // 6. Generate propId inits with values
  7717. //
  7718. // Handle propertyId collision
  7719. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7720. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7721. bool hasComputedNameOrSpread = false;
  7722. if (memberList != nullptr)
  7723. {
  7724. while (memberList->nop == knopList)
  7725. {
  7726. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7727. {
  7728. hasComputedNameOrSpread = true;
  7729. break;
  7730. }
  7731. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7732. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7733. {
  7734. propertyIds->Item(propertyId);
  7735. }
  7736. memberList = memberList->AsParseNodeBin()->pnode2;
  7737. }
  7738. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7739. {
  7740. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7741. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7742. {
  7743. propertyIds->Item(propertyId);
  7744. }
  7745. }
  7746. }
  7747. argCount = propertyIds->Count();
  7748. memberList = pmemberList;
  7749. if ((memberList == nullptr) || (argCount == 0))
  7750. {
  7751. // Empty literal or numeric property only object literal
  7752. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7753. }
  7754. else
  7755. {
  7756. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7757. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7758. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7759. {
  7760. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7761. // or not, in case the bytecode is later run with __proto__ enabled.
  7762. propIds->has__proto__ = true;
  7763. }
  7764. unsigned int argIndex = 0;
  7765. while (memberList->nop == knopList)
  7766. {
  7767. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7768. {
  7769. break;
  7770. }
  7771. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7772. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7773. {
  7774. propIds->elements[argIndex] = propertyId;
  7775. argIndex++;
  7776. }
  7777. memberList = memberList->AsParseNodeBin()->pnode2;
  7778. }
  7779. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7780. {
  7781. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7782. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7783. {
  7784. propIds->elements[argIndex] = propertyId;
  7785. argIndex++;
  7786. }
  7787. }
  7788. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7789. // Generate the opcode with propIds and cacheId
  7790. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7791. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7792. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7793. }
  7794. memberList = pmemberList;
  7795. bool useStore = false;
  7796. // Generate the actual assignment to those properties
  7797. if (memberList != nullptr)
  7798. {
  7799. while (memberList->nop == knopList)
  7800. {
  7801. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7802. if (memberNode->nop == knopEllipsis)
  7803. {
  7804. byteCodeGenerator->StartSubexpression(memberNode);
  7805. EmitObjectSpreadNode(memberNode, objectLocation, byteCodeGenerator, funcInfo);
  7806. byteCodeGenerator->EndSubexpression(memberNode);
  7807. }
  7808. else
  7809. {
  7810. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7811. {
  7812. useStore = true;
  7813. }
  7814. byteCodeGenerator->StartSubexpression(memberNode);
  7815. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7816. byteCodeGenerator->EndSubexpression(memberNode);
  7817. }
  7818. memberList = memberList->AsParseNodeBin()->pnode2;
  7819. }
  7820. byteCodeGenerator->StartSubexpression(memberList);
  7821. if (memberList->nop == knopEllipsis)
  7822. {
  7823. EmitObjectSpreadNode(memberList, objectLocation, byteCodeGenerator, funcInfo);
  7824. }
  7825. else
  7826. {
  7827. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7828. }
  7829. byteCodeGenerator->EndSubexpression(memberList);
  7830. }
  7831. }
  7832. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7833. {
  7834. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7835. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7836. // We only need to emit code for non-tagged string templates here.
  7837. if (!pnodeStrTemplate->isTaggedTemplate)
  7838. {
  7839. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7840. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7841. {
  7842. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7843. funcInfo->AcquireLoc(pnodeStrTemplate);
  7844. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7845. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7846. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7847. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7848. }
  7849. else
  7850. {
  7851. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7852. funcInfo->AcquireLoc(pnodeStrTemplate);
  7853. // First string must be a list node since we have substitutions.
  7854. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7855. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7856. // Emit the first string and load that into the pnode location.
  7857. // skip loading the string if it is empty
  7858. ParseNode* firstString = stringNodeList->AsParseNodeBin()->pnode1;
  7859. bool skippedFirst = false;
  7860. if (firstString->AsParseNodeStr()->pid->Cch() == 0)
  7861. {
  7862. skippedFirst = true;
  7863. }
  7864. else
  7865. {
  7866. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7867. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7868. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7869. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7870. }
  7871. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7872. ParseNode* stringNode;
  7873. ParseNode* expressionNode;
  7874. // Now append the substitution expressions and remaining string constants via normal add operator
  7875. // We will always have one more string constant than substitution expression
  7876. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7877. //
  7878. // strcon1 --- step 1 (above)
  7879. // expr1 \__ step 2
  7880. // strcon2 /
  7881. // expr2 \__ step 3
  7882. // strcon3 /
  7883. while (stringNodeList->nop == knopList)
  7884. {
  7885. // If the current head of the expression list is a list, fetch the node and walk the list.
  7886. if (expressionNodeList->nop == knopList)
  7887. {
  7888. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7889. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7890. }
  7891. else
  7892. {
  7893. // This is the last element of the expression list.
  7894. expressionNode = expressionNodeList;
  7895. }
  7896. // Emit the expression and append it to the string we're building.
  7897. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7898. // if this is the first expression AND the initial string was empty write directly to the pnodeStrTemplate location
  7899. if (skippedFirst == true)
  7900. {
  7901. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, pnodeStrTemplate->location, expressionNode->location);
  7902. skippedFirst = false;
  7903. }
  7904. else
  7905. {
  7906. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7907. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7908. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7909. funcInfo->ReleaseTmpRegister(toStringLocation);
  7910. }
  7911. funcInfo->ReleaseLoc(expressionNode);
  7912. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7913. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7914. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7915. if (stringNodeList->nop == knopList)
  7916. {
  7917. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7918. }
  7919. else
  7920. {
  7921. // This is the last element of the string literal list.
  7922. stringNode = stringNodeList;
  7923. }
  7924. // Emit the string node following the previous expression and append it to the string.
  7925. // This is either just some string in the list or it is the last string.
  7926. if (stringNode->AsParseNodeStr()->pid->Cch() != 0)
  7927. {
  7928. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7929. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7930. funcInfo->ReleaseLoc(stringNode);
  7931. }
  7932. }
  7933. }
  7934. }
  7935. }
  7936. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7937. {
  7938. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7939. uint argCount = pnode->AsParseNodeArrLit()->count;
  7940. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7941. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7942. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7943. if (arrayIntOpt)
  7944. {
  7945. int extraAlloc = 0, auxSize = 0;
  7946. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7947. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7948. {
  7949. ::Math::DefaultOverflowPolicy();
  7950. }
  7951. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7952. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7953. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7954. byteCodeGenerator->Writer()->Auxiliary(
  7955. Js::OpCode::NewScIntArray,
  7956. pnode->location,
  7957. ints,
  7958. auxSize,
  7959. argCount);
  7960. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7961. return;
  7962. }
  7963. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7964. if (arrayNumOpt)
  7965. {
  7966. int extraAlloc = 0, auxSize = 0;
  7967. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7968. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7969. {
  7970. ::Math::DefaultOverflowPolicy();
  7971. }
  7972. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7973. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7974. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7975. byteCodeGenerator->Writer()->Auxiliary(
  7976. Js::OpCode::NewScFltArray,
  7977. pnode->location,
  7978. doubles,
  7979. auxSize,
  7980. argCount);
  7981. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7982. return;
  7983. }
  7984. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7985. Assert(!arrayLitOpt || !nativeArrays);
  7986. Js::RegSlot spreadArrLoc = arrayLocation;
  7987. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7988. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7989. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7990. {
  7991. arrayLocation = funcInfo->AcquireTmpRegister();
  7992. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7993. }
  7994. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7995. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7996. arrayLocation,
  7997. argCount);
  7998. if (args != nullptr)
  7999. {
  8000. Js::OpCode opcode;
  8001. Js::RegSlot arrLoc;
  8002. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  8003. {
  8004. opcode = Js::OpCode::StArrItemC_CI4;
  8005. arrLoc = arrayLocation;
  8006. }
  8007. else if (arrayLitOpt)
  8008. {
  8009. opcode = Js::OpCode::StArrSegItem_A;
  8010. arrLoc = funcInfo->AcquireTmpRegister();
  8011. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  8012. }
  8013. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  8014. {
  8015. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  8016. // should be done relative to the array header to keep it alive (instead of the array segment).
  8017. opcode = Js::OpCode::StArrInlineItem_CI4;
  8018. arrLoc = arrayLocation;
  8019. }
  8020. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  8021. {
  8022. opcode = Js::OpCode::StArrSegItem_CI4;
  8023. arrLoc = funcInfo->AcquireTmpRegister();
  8024. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  8025. }
  8026. else
  8027. {
  8028. opcode = Js::OpCode::StArrItemI_CI4;
  8029. arrLoc = arrayLocation;
  8030. }
  8031. if (arrayLitOpt)
  8032. {
  8033. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  8034. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  8035. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  8036. // Generate the opcode with vars
  8037. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  8038. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  8039. }
  8040. else
  8041. {
  8042. uint i = 0;
  8043. unsigned spreadIndex = 0;
  8044. Js::RegSlot rhsLocation;
  8045. while (args->nop == knopList)
  8046. {
  8047. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  8048. {
  8049. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  8050. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  8051. Js::RegSlot regVal = rhsLocation;
  8052. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  8053. {
  8054. AnalysisAssert(spreadIndices);
  8055. regVal = funcInfo->AcquireTmpRegister();
  8056. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  8057. spreadIndices->elements[spreadIndex++] = i;
  8058. }
  8059. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  8060. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  8061. {
  8062. funcInfo->ReleaseTmpRegister(regVal);
  8063. }
  8064. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  8065. }
  8066. args = args->AsParseNodeBin()->pnode2;
  8067. i++;
  8068. }
  8069. if (args->nop != knopEmpty)
  8070. {
  8071. Emit(args, byteCodeGenerator, funcInfo, false);
  8072. rhsLocation = args->location;
  8073. Js::RegSlot regVal = rhsLocation;
  8074. if (args->nop == knopEllipsis)
  8075. {
  8076. regVal = funcInfo->AcquireTmpRegister();
  8077. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  8078. AnalysisAssert(spreadIndices);
  8079. spreadIndices->elements[spreadIndex] = i;
  8080. }
  8081. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  8082. if (args->nop == knopEllipsis)
  8083. {
  8084. funcInfo->ReleaseTmpRegister(regVal);
  8085. }
  8086. funcInfo->ReleaseLoc(args);
  8087. i++;
  8088. }
  8089. Assert(i <= argCount);
  8090. }
  8091. if (arrLoc != arrayLocation)
  8092. {
  8093. funcInfo->ReleaseTmpRegister(arrLoc);
  8094. }
  8095. }
  8096. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  8097. {
  8098. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  8099. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  8100. funcInfo->ReleaseTmpRegister(arrayLocation);
  8101. }
  8102. }
  8103. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  8104. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  8105. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  8106. // with special case for single-branch style.
  8107. void EmitBooleanExpression(
  8108. _In_ ParseNode* expr,
  8109. Js::ByteCodeLabel trueLabel,
  8110. Js::ByteCodeLabel falseLabel,
  8111. _In_ ByteCodeGenerator* byteCodeGenerator,
  8112. _In_ FuncInfo* funcInfo,
  8113. bool trueFallthrough,
  8114. bool falseFallthrough)
  8115. {
  8116. Assert(!trueFallthrough || !falseFallthrough);
  8117. byteCodeGenerator->StartStatement(expr);
  8118. switch (expr->nop)
  8119. {
  8120. case knopLogOr:
  8121. {
  8122. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  8123. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  8124. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8125. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  8126. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  8127. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8128. break;
  8129. }
  8130. case knopLogAnd:
  8131. {
  8132. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  8133. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  8134. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8135. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  8136. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  8137. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8138. break;
  8139. }
  8140. case knopLogNot:
  8141. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  8142. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  8143. break;
  8144. case knopEq:
  8145. case knopEqv:
  8146. case knopNEqv:
  8147. case knopNe:
  8148. case knopLt:
  8149. case knopLe:
  8150. case knopGe:
  8151. case knopGt:
  8152. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8153. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8154. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8155. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  8156. expr->AsParseNodeBin()->pnode2->location);
  8157. if (!falseFallthrough)
  8158. {
  8159. byteCodeGenerator->Writer()->Br(falseLabel);
  8160. }
  8161. break;
  8162. case knopTrue:
  8163. if (!trueFallthrough)
  8164. {
  8165. byteCodeGenerator->Writer()->Br(trueLabel);
  8166. }
  8167. break;
  8168. case knopFalse:
  8169. if (!falseFallthrough)
  8170. {
  8171. byteCodeGenerator->Writer()->Br(falseLabel);
  8172. }
  8173. break;
  8174. default:
  8175. // Note: we usually release the temp assigned to a node after we Emit it.
  8176. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  8177. // and the caller of EmitBooleanExpression expects to be able to release this register.
  8178. Emit(expr, byteCodeGenerator, funcInfo, false);
  8179. if (trueFallthrough)
  8180. {
  8181. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8182. }
  8183. else
  8184. {
  8185. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8186. if (!falseFallthrough)
  8187. {
  8188. byteCodeGenerator->Writer()->Br(falseLabel);
  8189. }
  8190. }
  8191. break;
  8192. }
  8193. byteCodeGenerator->EndStatement(expr);
  8194. }
  8195. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  8196. bool reuseLoc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8197. {
  8198. switch (expr->nop)
  8199. {
  8200. case knopLogOr:
  8201. {
  8202. byteCodeGenerator->StartStatement(expr);
  8203. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  8204. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, reuseLoc, byteCodeGenerator, funcInfo);
  8205. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8206. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  8207. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, true, byteCodeGenerator, funcInfo);
  8208. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8209. byteCodeGenerator->EndStatement(expr);
  8210. break;
  8211. }
  8212. case knopLogAnd:
  8213. {
  8214. byteCodeGenerator->StartStatement(expr);
  8215. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  8216. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, reuseLoc, byteCodeGenerator, funcInfo);
  8217. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8218. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  8219. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, true, byteCodeGenerator, funcInfo);
  8220. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8221. byteCodeGenerator->EndStatement(expr);
  8222. break;
  8223. }
  8224. case knopLogNot:
  8225. {
  8226. byteCodeGenerator->StartStatement(expr);
  8227. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  8228. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  8229. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  8230. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  8231. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  8232. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdTrue_ReuseLoc : Js::OpCode::LdTrue, writeto);
  8233. byteCodeGenerator->Writer()->Br(trueLabel);
  8234. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  8235. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, writeto);
  8236. if (!falsefallthrough)
  8237. {
  8238. byteCodeGenerator->Writer()->Br(falseLabel);
  8239. }
  8240. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  8241. byteCodeGenerator->EndStatement(expr);
  8242. break;
  8243. }
  8244. case knopEq:
  8245. case knopEqv:
  8246. case knopNEqv:
  8247. case knopNe:
  8248. case knopLt:
  8249. case knopLe:
  8250. case knopGe:
  8251. case knopGt:
  8252. byteCodeGenerator->StartStatement(expr);
  8253. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8254. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8255. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8256. funcInfo->AcquireLoc(expr);
  8257. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  8258. expr->AsParseNodeBin()->pnode2->location);
  8259. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8260. // The inliner likes small bytecode
  8261. if (!(truefallthrough || falsefallthrough))
  8262. {
  8263. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8264. byteCodeGenerator->Writer()->Br(falseLabel);
  8265. }
  8266. else if (truefallthrough && !falsefallthrough) {
  8267. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8268. }
  8269. else if (falsefallthrough && !truefallthrough) {
  8270. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8271. }
  8272. byteCodeGenerator->EndStatement(expr);
  8273. break;
  8274. case knopTrue:
  8275. byteCodeGenerator->StartStatement(expr);
  8276. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdTrue_ReuseLoc : Js::OpCode::LdTrue, writeto);
  8277. if (!truefallthrough)
  8278. {
  8279. byteCodeGenerator->Writer()->Br(trueLabel);
  8280. }
  8281. byteCodeGenerator->EndStatement(expr);
  8282. break;
  8283. case knopFalse:
  8284. byteCodeGenerator->StartStatement(expr);
  8285. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdFalse_ReuseLoc : Js::OpCode::LdFalse, writeto);
  8286. if (!falsefallthrough)
  8287. {
  8288. byteCodeGenerator->Writer()->Br(falseLabel);
  8289. }
  8290. byteCodeGenerator->EndStatement(expr);
  8291. break;
  8292. default:
  8293. // Note: we usually release the temp assigned to a node after we Emit it.
  8294. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  8295. // and the caller of EmitBooleanExpression expects to be able to release this register.
  8296. // For diagnostics purposes, register the name and dot to the statement list.
  8297. if (expr->nop == knopName || expr->nop == knopDot)
  8298. {
  8299. byteCodeGenerator->StartStatement(expr);
  8300. Emit(expr, byteCodeGenerator, funcInfo, false);
  8301. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8302. // The inliner likes small bytecode
  8303. if (!(truefallthrough || falsefallthrough))
  8304. {
  8305. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8306. byteCodeGenerator->Writer()->Br(falseLabel);
  8307. }
  8308. else if (truefallthrough && !falsefallthrough) {
  8309. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8310. }
  8311. else if (falsefallthrough && !truefallthrough) {
  8312. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8313. }
  8314. byteCodeGenerator->EndStatement(expr);
  8315. }
  8316. else
  8317. {
  8318. Emit(expr, byteCodeGenerator, funcInfo, false);
  8319. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8320. // The inliner likes small bytecode
  8321. if (!(truefallthrough || falsefallthrough))
  8322. {
  8323. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8324. byteCodeGenerator->Writer()->Br(falseLabel);
  8325. }
  8326. else if (truefallthrough && !falsefallthrough) {
  8327. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8328. }
  8329. else if (falsefallthrough && !truefallthrough) {
  8330. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8331. }
  8332. }
  8333. break;
  8334. }
  8335. }
  8336. // used by while and for loops
  8337. void EmitLoop(
  8338. ParseNodeStmt *loopNode,
  8339. ParseNode *cond,
  8340. ParseNode *body,
  8341. ParseNode *incr,
  8342. ByteCodeGenerator *byteCodeGenerator,
  8343. FuncInfo *funcInfo,
  8344. BOOL fReturnValue,
  8345. BOOL doWhile = FALSE,
  8346. ParseNodeBlock *forLoopBlock = nullptr)
  8347. {
  8348. // Need to increment loop count whether we are going to profile or not for HasLoop()
  8349. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8350. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8351. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8352. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8353. if (doWhile)
  8354. {
  8355. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8356. funcInfo->ReleaseLoc(body);
  8357. if (loopNode->emitLabels)
  8358. {
  8359. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8360. }
  8361. if (!ByteCodeGenerator::IsFalse(cond) ||
  8362. byteCodeGenerator->IsInDebugMode())
  8363. {
  8364. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  8365. }
  8366. funcInfo->ReleaseLoc(cond);
  8367. }
  8368. else
  8369. {
  8370. if (cond)
  8371. {
  8372. if (!(cond->nop == knopInt &&
  8373. cond->AsParseNodeInt()->lw != 0))
  8374. {
  8375. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8376. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  8377. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8378. }
  8379. funcInfo->ReleaseLoc(cond);
  8380. }
  8381. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8382. funcInfo->ReleaseLoc(body);
  8383. if (forLoopBlock != nullptr)
  8384. {
  8385. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  8386. }
  8387. if (loopNode->emitLabels)
  8388. {
  8389. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8390. }
  8391. if (incr != nullptr)
  8392. {
  8393. Emit(incr, byteCodeGenerator, funcInfo, false);
  8394. funcInfo->ReleaseLoc(incr);
  8395. }
  8396. byteCodeGenerator->Writer()->Br(loopEntrance);
  8397. }
  8398. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8399. if (loopNode->emitLabels)
  8400. {
  8401. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8402. }
  8403. byteCodeGenerator->PopJumpCleanup();
  8404. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8405. }
  8406. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeStmt* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  8407. {
  8408. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  8409. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  8410. // emit branch around original
  8411. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  8412. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  8413. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  8414. // emit original
  8415. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  8416. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  8417. // clear temporary registers since inverted loop may share nodes with
  8418. // emitted original loop
  8419. VisitClearTmpRegs(outerLoop, this, funcInfo);
  8420. // emit branch around inverted
  8421. this->m_writer.Br(afterInvertedLoop);
  8422. this->m_writer.MarkLabel(invertedLoopLabel);
  8423. // Emit a zero trip test for the original outer-loop if the outer-loop
  8424. // has a condition
  8425. if (outerLoop->AsParseNodeFor()->pnodeCond)
  8426. {
  8427. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  8428. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  8429. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  8430. this->m_writer.MarkLabel(zeroTrip);
  8431. funcInfo->ReleaseLoc(testNode);
  8432. }
  8433. // emit inverted
  8434. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  8435. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  8436. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  8437. invertedLoop->pnodeIncr, this, funcInfo, false);
  8438. this->m_writer.MarkLabel(afterInvertedLoop);
  8439. }
  8440. void EmitGetIterator(
  8441. Js::RegSlot iteratorReg,
  8442. Js::RegSlot iterableReg,
  8443. ByteCodeGenerator* byteCodeGenerator,
  8444. FuncInfo* funcInfo)
  8445. {
  8446. EmitGetObjectMethod(
  8447. iteratorReg,
  8448. iterableReg,
  8449. Js::PropertyIds::_symbolIterator,
  8450. byteCodeGenerator,
  8451. funcInfo);
  8452. EmitFunctionCall(iteratorReg, iteratorReg, iterableReg, byteCodeGenerator, funcInfo);
  8453. EmitThrowOnNotObject(iteratorReg, byteCodeGenerator);
  8454. }
  8455. void EmitGetAsyncIterator(
  8456. Js::RegSlot resultReg,
  8457. Js::RegSlot iterableReg,
  8458. ByteCodeGenerator* byteCodeGenerator,
  8459. FuncInfo* funcInfo)
  8460. {
  8461. auto* writer = byteCodeGenerator->Writer();
  8462. Js::ByteCodeLabel noAsyncIterator = writer->DefineLabel();
  8463. EmitGetOptionalObjectMethod(
  8464. resultReg,
  8465. iterableReg,
  8466. Js::PropertyIds::_symbolAsyncIterator,
  8467. noAsyncIterator,
  8468. byteCodeGenerator,
  8469. funcInfo);
  8470. EmitFunctionCall(resultReg, resultReg, iterableReg, byteCodeGenerator, funcInfo);
  8471. EmitThrowOnNotObject(resultReg, byteCodeGenerator);
  8472. Js::ByteCodeLabel finished = writer->DefineLabel();
  8473. writer->Br(finished);
  8474. // Iterable does not have a Symbol.asyncIterator method: attempt to get a sync
  8475. // iterable and wrap it with an AsyncFromSyncIterator
  8476. writer->MarkLabel(noAsyncIterator);
  8477. Js::RegSlot iteratorReg = funcInfo->AcquireTmpRegister();
  8478. EmitGetIterator(iteratorReg, iterableReg, byteCodeGenerator, funcInfo);
  8479. writer->Reg2(Js::OpCode::NewAsyncFromSyncIterator, iteratorReg, iteratorReg);
  8480. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, resultReg, iteratorReg);
  8481. funcInfo->ReleaseTmpRegister(iteratorReg);
  8482. byteCodeGenerator->Writer()->MarkLabel(finished);
  8483. }
  8484. // Generating
  8485. // if (hasReturnFunction) {
  8486. // value = Call Retrun;
  8487. // if (value != Object)
  8488. // throw TypeError;
  8489. // }
  8490. void EmitIteratorClose(
  8491. Js::RegSlot iteratorLocation,
  8492. ByteCodeGenerator* byteCodeGenerator,
  8493. FuncInfo* funcInfo,
  8494. bool isAsync)
  8495. {
  8496. Js::RegSlot returnReg = funcInfo->AcquireTmpRegister();
  8497. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8498. EmitGetOptionalObjectMethod(
  8499. returnReg,
  8500. iteratorLocation,
  8501. Js::PropertyIds::return_,
  8502. noReturn,
  8503. byteCodeGenerator,
  8504. funcInfo);
  8505. EmitFunctionCall(returnReg, returnReg, iteratorLocation, byteCodeGenerator, funcInfo);
  8506. // In for-await or async yield* use await on the returned value
  8507. if (isAsync)
  8508. EmitAwait(returnReg, returnReg, byteCodeGenerator, funcInfo);
  8509. EmitThrowOnNotObject(returnReg, byteCodeGenerator);
  8510. funcInfo->ReleaseTmpRegister(returnReg);
  8511. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8512. }
  8513. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8514. Js::ByteCodeLabel loopEntrance,
  8515. Js::ByteCodeLabel continuePastLoop,
  8516. ByteCodeGenerator *byteCodeGenerator,
  8517. FuncInfo *funcInfo,
  8518. BOOL fReturnValue)
  8519. {
  8520. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8521. loopNode->pnodeLval->nop != knopLetDecl &&
  8522. loopNode->pnodeLval->nop != knopConstDecl)
  8523. {
  8524. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8525. }
  8526. else
  8527. {
  8528. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8529. sym->SetNeedDeclaration(false);
  8530. }
  8531. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8532. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8533. // The StartStatement is already done in the caller of this function.
  8534. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8535. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8536. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8537. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8538. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8539. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8540. if (loopNode->emitLabels)
  8541. {
  8542. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8543. }
  8544. byteCodeGenerator->Writer()->Br(loopEntrance);
  8545. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8546. if (loopNode->emitLabels)
  8547. {
  8548. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8549. }
  8550. }
  8551. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8552. Js::ByteCodeLabel loopEntrance,
  8553. Js::ByteCodeLabel continuePastLoop,
  8554. ByteCodeGenerator *byteCodeGenerator,
  8555. FuncInfo *funcInfo,
  8556. BOOL fReturnValue)
  8557. {
  8558. Assert(loopNode->nop == knopForIn);
  8559. Assert(loopNode->location == Js::Constants::NoRegister);
  8560. // Grab registers for the enumerator and for the current enumerated item.
  8561. // The enumerator register will be released after this call returns.
  8562. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8563. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8564. // get enumerator from the collection
  8565. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8566. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8567. byteCodeGenerator->EndStatement(loopNode);
  8568. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8569. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8570. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8571. // The EndStatement will happen in the EmitForInOfLoopBody function
  8572. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8573. // branch past loop when MoveAndGetNext returns nullptr
  8574. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8575. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8576. byteCodeGenerator->PopJumpCleanup();
  8577. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8578. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8579. }
  8580. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8581. {
  8582. bool isForIn = (loopNode->nop == knopForIn);
  8583. bool isForAwaitOf = (loopNode->nop == knopForAwaitOf);
  8584. bool hasYield = isForAwaitOf || byteCodeGenerator->GetHasYield(loopNode);
  8585. Assert(isForAwaitOf || isForIn || loopNode->nop == knopForOf);
  8586. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8587. byteCodeGenerator->StartStatement(loopNode);
  8588. if (!isForIn)
  8589. {
  8590. funcInfo->AcquireLoc(loopNode);
  8591. }
  8592. // Record the branch bytecode offset.
  8593. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8594. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8595. // otherwise use offset of next stmt.
  8596. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8597. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8598. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8599. // See WinBlue 231880 for details.
  8600. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8601. if (loopNode->pnodeBlock->HasBlockScopedContent())
  8602. {
  8603. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8604. }
  8605. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8606. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8607. if (loopNode->pnodeLval->nop == knopVarDecl)
  8608. {
  8609. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8610. }
  8611. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8612. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8613. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8614. if (loopNode->pnodeBlock->scope != nullptr)
  8615. {
  8616. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8617. sym->SetIsTrackedForDebugger(false);
  8618. });
  8619. }
  8620. if (isForIn)
  8621. {
  8622. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8623. return;
  8624. }
  8625. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8626. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8627. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8628. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8629. Js::RegSlot regException = Js::Constants::NoRegister;
  8630. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8631. // These two temp variables track whether the return method of the source iterator should
  8632. // be called. One variable is used for catch block and one is used for finally block.
  8633. // Non-temps are used so that when jitting loop bodies, writes to these variables are not
  8634. // mistaken for dead stores.
  8635. Js::RegSlot shouldCallReturnFunctionLocation = loopNode->shouldCallReturnFunctionLocation;
  8636. Js::RegSlot shouldCallReturnFunctionLocationFinally = loopNode->shouldCallReturnFunctionLocationFinally;
  8637. if (hasYield)
  8638. {
  8639. Assert(funcInfo->byteCodeFunction->IsCoroutine());
  8640. regException = funcInfo->AcquireTmpRegister();
  8641. regOffset = funcInfo->AcquireTmpRegister();
  8642. }
  8643. // Grab registers for the enumerator and for the current enumerated item.
  8644. // The enumerator register will be released after this call returns.
  8645. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  8646. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8647. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8648. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8649. // to the profiler and JIT.
  8650. byteCodeGenerator->SetHasFinally(true);
  8651. byteCodeGenerator->SetHasTry(true);
  8652. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8653. // do a ToObject on the collection
  8654. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8655. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8656. if (isForAwaitOf)
  8657. EmitGetAsyncIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8658. else
  8659. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8660. funcInfo->ReleaseTmpRegister(tmpObj);
  8661. EmitGetObjectMethod(
  8662. nextMethodReg,
  8663. loopNode->location,
  8664. Js::PropertyIds::next,
  8665. byteCodeGenerator,
  8666. funcInfo);
  8667. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8668. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8669. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8670. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8671. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8672. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8673. if (hasYield)
  8674. {
  8675. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8676. byteCodeGenerator->PushJumpCleanupForTry(
  8677. Js::OpCode::TryFinallyWithYield,
  8678. finallyLabel,
  8679. regException,
  8680. regOffset);
  8681. }
  8682. else
  8683. {
  8684. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8685. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  8686. }
  8687. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8688. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  8689. byteCodeGenerator->EndStatement(loopNode);
  8690. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8691. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8692. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8693. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8694. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8695. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8696. // Call next on the iterator
  8697. EmitFunctionCall(
  8698. loopNode->itemLocation,
  8699. nextMethodReg,
  8700. loopNode->location,
  8701. byteCodeGenerator,
  8702. funcInfo);
  8703. // If this is a for-await-of then await the iterator next result
  8704. if (isForAwaitOf)
  8705. EmitAwait(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8706. EmitThrowOnNotObject(loopNode->itemLocation, byteCodeGenerator);
  8707. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8708. EmitGetObjectProperty(
  8709. doneLocation,
  8710. loopNode->itemLocation,
  8711. Js::PropertyIds::done,
  8712. byteCodeGenerator,
  8713. funcInfo);
  8714. // Branch past loop if the result's done property is truthy
  8715. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8716. funcInfo->ReleaseTmpRegister(doneLocation);
  8717. // Otherwise put result's value property in itemLocation
  8718. EmitGetObjectProperty(
  8719. loopNode->itemLocation,
  8720. loopNode->itemLocation,
  8721. Js::PropertyIds::value,
  8722. byteCodeGenerator,
  8723. funcInfo);
  8724. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8725. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8726. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8727. byteCodeGenerator->PopJumpCleanup();
  8728. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8729. funcInfo->ReleaseTmpRegister(nextMethodReg);
  8730. EmitIteratorCatchAndFinally(catchLabel,
  8731. finallyLabel,
  8732. loopNode->location,
  8733. shouldCallReturnFunctionLocation,
  8734. shouldCallReturnFunctionLocationFinally,
  8735. regException,
  8736. regOffset,
  8737. byteCodeGenerator,
  8738. funcInfo,
  8739. hasYield,
  8740. isForAwaitOf);
  8741. }
  8742. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8743. {
  8744. funcInfo->AcquireLoc(pnode);
  8745. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8746. if (args == nullptr)
  8747. {
  8748. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8749. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8750. pnode->location,
  8751. ByteCodeGenerator::DefaultArraySize);
  8752. }
  8753. else
  8754. {
  8755. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8756. }
  8757. }
  8758. void ByteCodeGenerator::EmitJumpCleanup(ParseNode* target, FuncInfo* funcInfo)
  8759. {
  8760. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Next();)
  8761. {
  8762. const JumpCleanupInfo& info = iter.Data();
  8763. if (info.loopNode)
  8764. {
  8765. if (info.loopNode == target)
  8766. break;
  8767. #if ENABLE_PROFILE_INFO
  8768. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8769. this->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, info.loopId);
  8770. #endif
  8771. }
  8772. else
  8773. {
  8774. Assert(
  8775. info.tryOp == Js::OpCode::TryCatch ||
  8776. info.tryOp == Js::OpCode::TryFinally ||
  8777. info.tryOp == Js::OpCode::TryFinallyWithYield ||
  8778. info.tryOp == Js::OpCode::ResumeCatch ||
  8779. info.tryOp == Js::OpCode::ResumeFinally);
  8780. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8781. // This is for flow control and does not participate in identifying boundaries
  8782. // of try/catch blocks, thus we shouldn't call RecordCrossFrameEntryExitRecord
  8783. // here.
  8784. this->Writer()->Empty(Js::OpCode::Leave);
  8785. }
  8786. }
  8787. }
  8788. void EmitBinaryOpnds(ParseNode* pnode1, ParseNode* pnode2, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot computedPropertyLocation)
  8789. {
  8790. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8791. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8792. {
  8793. SaveOpndValue(pnode1, funcInfo);
  8794. }
  8795. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8796. if (pnode1->nop == knopComputedName && computedPropertyLocation != Js::Constants::NoRegister)
  8797. {
  8798. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Prop, computedPropertyLocation, pnode1->location);
  8799. }
  8800. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, computedPropertyLocation);
  8801. }
  8802. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8803. {
  8804. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8805. switch (pnode1->nop)
  8806. {
  8807. case knopName:
  8808. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8809. {
  8810. // Given x op y, y may kill x, so stash x.
  8811. // Note that this only matters if we're loading x prior to the op.
  8812. SaveOpndValue(pnode1, funcInfo);
  8813. }
  8814. break;
  8815. case knopDot:
  8816. if (fLoadLhs)
  8817. {
  8818. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8819. funcInfo->AcquireLoc(pnode1);
  8820. }
  8821. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator))
  8822. {
  8823. // Given x.y op z, z may kill x, so stash x away.
  8824. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8825. }
  8826. break;
  8827. case knopIndex:
  8828. if (fLoadLhs)
  8829. {
  8830. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8831. funcInfo->AcquireLoc(pnode1);
  8832. }
  8833. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator) ||
  8834. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2, byteCodeGenerator))
  8835. {
  8836. // Given x[y] op z, y or z may kill x, so stash x away.
  8837. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8838. }
  8839. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2, byteCodeGenerator))
  8840. {
  8841. // Given x[y] op z, z may kill y, so stash y away.
  8842. // But make sure that x gets a register before y.
  8843. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8844. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8845. }
  8846. break;
  8847. }
  8848. if (fLoadLhs)
  8849. {
  8850. // Emit code to load the value of the LHS.
  8851. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8852. }
  8853. else
  8854. {
  8855. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8856. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8857. }
  8858. // Evaluate the RHS.
  8859. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8860. }
  8861. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8862. {
  8863. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8864. if (location != Js::Constants::NoRegister)
  8865. {
  8866. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8867. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8868. }
  8869. }
  8870. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8871. {
  8872. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8873. // if necessary.
  8874. if (sym != nullptr &&
  8875. !sym->GetIsModuleExportStorage() &&
  8876. sym->GetNeedDeclaration() &&
  8877. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8878. sym->GetScope()->GetFunc() == funcInfo)
  8879. {
  8880. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8881. }
  8882. }
  8883. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8884. {
  8885. byteCodeGenerator->StartStatement(pnode);
  8886. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8887. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8888. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8889. funcInfo->AcquireLoc(pnode);
  8890. byteCodeGenerator->Writer()->Reg3(opcode,
  8891. pnode->location,
  8892. pnode->AsParseNodeBin()->pnode1->location,
  8893. pnode->AsParseNodeBin()->pnode2->location);
  8894. byteCodeGenerator->EndStatement(pnode);
  8895. }
  8896. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator
  8897. #ifdef ENABLE_TEST_HOOKS
  8898. , bool Force32BitByteCode = false
  8899. #endif
  8900. )
  8901. {
  8902. Assert(pnodeAdd->nop == knopAdd);
  8903. Assert(pnodeAdd->CanFlattenConcatExpr());
  8904. bool doConcatString = false;
  8905. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8906. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8907. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8908. while (true)
  8909. {
  8910. if (!pnode->CanFlattenConcatExpr())
  8911. {
  8912. concatOpnds.Append(pnode);
  8913. }
  8914. else if (pnode->nop == knopStr)
  8915. {
  8916. concatOpnds.Append(pnode);
  8917. // Detect if there are any string larger then the append size limit.
  8918. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8919. #ifdef ENABLE_TEST_HOOKS
  8920. if (Force32BitByteCode)
  8921. {
  8922. doConcatString = doConcatString || (pnode->AsParseNodeStr()->pid->Cch() > 4);
  8923. }
  8924. else
  8925. {
  8926. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8927. }
  8928. #else
  8929. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8930. #endif
  8931. }
  8932. else
  8933. {
  8934. Assert(pnode->nop == knopAdd);
  8935. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8936. pnode = pnode->AsParseNodeBin()->pnode1;
  8937. continue;
  8938. }
  8939. if (pnodeStack.Empty())
  8940. {
  8941. break;
  8942. }
  8943. pnode = pnodeStack.Head();
  8944. pnodeStack.RemoveHead();
  8945. }
  8946. return doConcatString;
  8947. }
  8948. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8949. {
  8950. byteCodeGenerator->StartStatement(pnode);
  8951. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator) || MayHaveSideEffectOnNode(pnode1, pnode3, byteCodeGenerator))
  8952. {
  8953. SaveOpndValue(pnode1, funcInfo);
  8954. }
  8955. if (MayHaveSideEffectOnNode(pnode2, pnode3, byteCodeGenerator))
  8956. {
  8957. SaveOpndValue(pnode2, funcInfo);
  8958. }
  8959. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8960. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8961. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8962. funcInfo->ReleaseLoc(pnode3);
  8963. funcInfo->ReleaseLoc(pnode2);
  8964. funcInfo->ReleaseLoc(pnode1);
  8965. funcInfo->AcquireLoc(pnode);
  8966. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8967. pnode->location,
  8968. pnode1->location,
  8969. pnode2->location,
  8970. pnode3->location);
  8971. byteCodeGenerator->EndStatement(pnode);
  8972. }
  8973. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8974. {
  8975. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8976. funcInfo->ReleaseLoc(pnode2);
  8977. funcInfo->ReleaseLoc(pnode1);
  8978. funcInfo->AcquireLoc(pnode);
  8979. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8980. pnode->location,
  8981. pnode1->location,
  8982. pnode2->location,
  8983. count);
  8984. }
  8985. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8986. {
  8987. Assert(pnode->nop == knopAdd);
  8988. if (pnode->CanFlattenConcatExpr())
  8989. {
  8990. // We should only have a string concat if the feature is on.
  8991. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8992. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8993. #ifdef ENABLE_TEST_HOOKS
  8994. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator(),
  8995. byteCodeGenerator->GetScriptContext()->GetConfig()->Force32BitByteCode());
  8996. #else
  8997. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8998. #endif
  8999. if (doConcatString)
  9000. {
  9001. uint concatCount = concatOpnds.Count();
  9002. Assert(concatCount >= 2);
  9003. // Don't do concatN if the number is too high
  9004. // CONSIDER: although we could have done multiple ConcatNs
  9005. if (concatCount > 2 && concatCount <= UINT8_MAX)
  9006. {
  9007. #if DBG
  9008. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  9009. #endif
  9010. ParseNode * pnode1 = concatOpnds.Head();
  9011. concatOpnds.RemoveHead();
  9012. ParseNode * pnode2 = concatOpnds.Head();
  9013. concatOpnds.RemoveHead();
  9014. if (concatCount == 3)
  9015. {
  9016. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  9017. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  9018. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  9019. byteCodeGenerator->Writer()->ByteCodeDataSize());
  9020. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  9021. return;
  9022. }
  9023. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  9024. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  9025. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  9026. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  9027. byteCodeGenerator->StartStatement(pnode);
  9028. funcInfo->AcquireLoc(pnode);
  9029. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  9030. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  9031. uint i = 2;
  9032. do
  9033. {
  9034. ParseNode * currNode = concatOpnds.Head();
  9035. concatOpnds.RemoveHead();
  9036. ParseNode * currNode2 = concatOpnds.Head();
  9037. concatOpnds.RemoveHead();
  9038. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  9039. funcInfo->ReleaseLoc(currNode2);
  9040. funcInfo->ReleaseLoc(currNode);
  9041. byteCodeGenerator->Writer()->Reg3B1(
  9042. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  9043. i += 2;
  9044. } while (concatOpnds.Count() > 1);
  9045. if (!concatOpnds.Empty())
  9046. {
  9047. ParseNode * currNode = concatOpnds.Head();
  9048. Emit(currNode, byteCodeGenerator, funcInfo, false);
  9049. funcInfo->ReleaseLoc(currNode);
  9050. byteCodeGenerator->Writer()->Reg2B1(
  9051. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  9052. i++;
  9053. }
  9054. Assert(concatCount == i);
  9055. byteCodeGenerator->EndStatement(pnode);
  9056. return;
  9057. }
  9058. }
  9059. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  9060. byteCodeGenerator->StartStatement(pnode);
  9061. ParseNode * currNode = concatOpnds.Head();
  9062. concatOpnds.RemoveHead();
  9063. ParseNode * currNode2 = concatOpnds.Head();
  9064. concatOpnds.RemoveHead();
  9065. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  9066. funcInfo->ReleaseLoc(currNode2);
  9067. funcInfo->ReleaseLoc(currNode);
  9068. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  9069. byteCodeGenerator->Writer()->Reg3(
  9070. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  9071. while (!concatOpnds.Empty())
  9072. {
  9073. currNode = concatOpnds.Head();
  9074. concatOpnds.RemoveHead();
  9075. Emit(currNode, byteCodeGenerator, funcInfo, false);
  9076. funcInfo->ReleaseLoc(currNode);
  9077. byteCodeGenerator->Writer()->Reg3(
  9078. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  9079. }
  9080. byteCodeGenerator->EndStatement(pnode);
  9081. }
  9082. else
  9083. {
  9084. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  9085. }
  9086. }
  9087. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  9088. {
  9089. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Next();)
  9090. {
  9091. const JumpCleanupInfo& info = iter.Data();
  9092. switch (info.tryOp)
  9093. {
  9094. case Js::OpCode::TryFinallyWithYield:
  9095. this->Writer()->Empty(Js::OpCode::LeaveNull);
  9096. break;
  9097. case Js::OpCode::TryCatch:
  9098. case Js::OpCode::ResumeFinally:
  9099. case Js::OpCode::ResumeCatch:
  9100. this->Writer()->Empty(Js::OpCode::Leave);
  9101. break;
  9102. case Js::OpCode::Nop:
  9103. break;
  9104. default:
  9105. AssertMsg(false, "Unexpected OpCode in jumpCleanupList");
  9106. break;
  9107. }
  9108. }
  9109. }
  9110. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  9111. {
  9112. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Prev();)
  9113. {
  9114. const JumpCleanupInfo& info = iter.Data();
  9115. switch (info.tryOp)
  9116. {
  9117. case Js::OpCode::TryCatch:
  9118. this->Writer()->Br(info.tryOp, info.label);
  9119. break;
  9120. case Js::OpCode::TryFinallyWithYield:
  9121. case Js::OpCode::ResumeFinally:
  9122. this->Writer()->BrReg2(info.tryOp, info.label, info.regSlot1, info.regSlot2);
  9123. break;
  9124. case Js::OpCode::ResumeCatch:
  9125. this->Writer()->Empty(info.tryOp);
  9126. break;
  9127. case Js::OpCode::Nop:
  9128. break;
  9129. default:
  9130. AssertMsg(false, "Unexpected OpCode in jumpCleanupList");
  9131. break;
  9132. }
  9133. }
  9134. }
  9135. void EmitYieldAndResume(
  9136. Js::RegSlot resumeValueReg,
  9137. Js::RegSlot inputReg,
  9138. Js::ByteCodeLabel resumeNormalLabel,
  9139. Js::ByteCodeLabel resumeThrowLabel,
  9140. ByteCodeGenerator* byteCodeGenerator,
  9141. FuncInfo* funcInfo)
  9142. {
  9143. // If `resultThrowLabel` is a valid label, then the instruction
  9144. // sequence following this call must handle the return yield resume
  9145. // case. Otherwise, the instruction sequence following this call
  9146. // must handle both the throw and return cases.
  9147. auto* writer = byteCodeGenerator->Writer();
  9148. // If in a loop mark it as containing Yield and hence not eligible for Jit loop body
  9149. writer->SetCurrentLoopHasYield();
  9150. if (inputReg != funcInfo->yieldRegister)
  9151. writer->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputReg);
  9152. // Yield the result. On resume, the resume yield object will be in yieldRegister
  9153. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  9154. writer->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  9155. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  9156. Js::RegSlot resumeKindReg = funcInfo->AcquireTmpRegister();
  9157. // Get the "kind" property of the resume object
  9158. EmitGetObjectProperty(
  9159. resumeKindReg,
  9160. funcInfo->yieldRegister,
  9161. Js::PropertyIds::kind,
  9162. byteCodeGenerator,
  9163. funcInfo);
  9164. // Get the "value" property of the resume object
  9165. EmitGetObjectProperty(
  9166. resumeValueReg,
  9167. funcInfo->yieldRegister,
  9168. Js::PropertyIds::value,
  9169. byteCodeGenerator,
  9170. funcInfo);
  9171. Js::RegSlot normalConst = funcInfo->constantToRegister.Lookup(
  9172. (uint)Js::ResumeYieldKind::Normal,
  9173. Js::Constants::NoRegister);
  9174. Assert(normalConst != Js::Constants::NoRegister);
  9175. // Branch to normal resume if kind is Normal
  9176. writer->BrReg2(Js::OpCode::BrSrEq_A, resumeNormalLabel, resumeKindReg, normalConst);
  9177. if (resumeThrowLabel != Js::Constants::NoByteCodeLabel)
  9178. {
  9179. Js::RegSlot throwConst = funcInfo->constantToRegister.Lookup(
  9180. (uint)Js::ResumeYieldKind::Throw,
  9181. Js::Constants::NoRegister);
  9182. Assert(throwConst != Js::Constants::NoRegister);
  9183. // Branch to throw if kind is Throw
  9184. writer->BrReg2(Js::OpCode::BrSrEq_A, resumeThrowLabel, resumeKindReg, throwConst);
  9185. }
  9186. funcInfo->ReleaseTmpRegister(resumeKindReg);
  9187. }
  9188. void EmitReturnFromYield(
  9189. Js::RegSlot resultReg,
  9190. ByteCodeGenerator* byteCodeGenerator,
  9191. FuncInfo* funcInfo)
  9192. {
  9193. auto* writer = byteCodeGenerator->Writer();
  9194. writer->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, resultReg);
  9195. byteCodeGenerator->EmitJumpCleanup(nullptr, funcInfo);
  9196. writer->Br(funcInfo->singleExit);
  9197. }
  9198. void EmitStartupYield(ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  9199. {
  9200. // Generators are "paused" after evaluating the parameter list. A synthetic
  9201. // yield is inserted at the beginning of the function for this purpose. It
  9202. // has the following special properties: it can only be resumed with a "normal"
  9203. // completion (the other types are handled in the generator logic), the
  9204. // resume value is not observable to user code, and it cannot be contained
  9205. // within a try scope.
  9206. Assert(!byteCodeGenerator->HasJumpCleanup());
  9207. auto* writer = byteCodeGenerator->Writer();
  9208. writer->Reg1(Js::OpCode::LdUndef, funcInfo->yieldRegister);
  9209. writer->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  9210. }
  9211. void EmitAwait(
  9212. Js::RegSlot resultReg,
  9213. Js::RegSlot inputReg,
  9214. ByteCodeGenerator* byteCodeGenerator,
  9215. FuncInfo* funcInfo)
  9216. {
  9217. auto writer = byteCodeGenerator->Writer();
  9218. writer->PatchableProperty(
  9219. Js::OpCode::StFld,
  9220. inputReg,
  9221. funcInfo->awaitRegister,
  9222. funcInfo->FindOrAddInlineCacheId(funcInfo->awaitRegister, Js::PropertyIds::value, false, true));
  9223. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9224. EmitYieldAndResume(
  9225. resultReg,
  9226. funcInfo->awaitRegister,
  9227. resumeNormal,
  9228. Js::Constants::NoByteCodeLabel,
  9229. byteCodeGenerator,
  9230. funcInfo);
  9231. // Throw case: throw the resume value
  9232. writer->Reg1(Js::OpCode::Throw, resultReg);
  9233. // Normal case: continue (value is already in result register)
  9234. writer->MarkLabel(resumeNormal);
  9235. }
  9236. void EmitCreateYieldResult(
  9237. Js::RegSlot resultReg,
  9238. Js::RegSlot inputReg,
  9239. ByteCodeGenerator* byteCodeGenerator,
  9240. FuncInfo* funcInfo)
  9241. {
  9242. Assert(resultReg != inputReg);
  9243. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, resultReg);
  9244. byteCodeGenerator->Writer()->PatchableProperty(
  9245. Js::OpCode::StFld,
  9246. inputReg,
  9247. resultReg,
  9248. funcInfo->FindOrAddInlineCacheId(resultReg, Js::PropertyIds::value, false, true));
  9249. byteCodeGenerator->Writer()->PatchableProperty(
  9250. Js::OpCode::StFld,
  9251. funcInfo->falseConstantRegister,
  9252. resultReg,
  9253. funcInfo->FindOrAddInlineCacheId(resultReg, Js::PropertyIds::done, false, true));
  9254. }
  9255. void EmitYield(
  9256. Js::RegSlot resultReg,
  9257. Js::RegSlot inputReg,
  9258. ByteCodeGenerator* byteCodeGenerator,
  9259. FuncInfo* funcInfo)
  9260. {
  9261. auto* writer = byteCodeGenerator->Writer();
  9262. Js::RegSlot yieldReg = funcInfo->yieldRegister;
  9263. EmitCreateYieldResult(yieldReg, inputReg, byteCodeGenerator, funcInfo);
  9264. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9265. Js::ByteCodeLabel resumeThrow = writer->DefineLabel();
  9266. EmitYieldAndResume(
  9267. resultReg,
  9268. yieldReg,
  9269. resumeNormal,
  9270. resumeThrow,
  9271. byteCodeGenerator,
  9272. funcInfo);
  9273. // Return case: set the return register value and branch to function exit
  9274. EmitReturnFromYield(resultReg, byteCodeGenerator, funcInfo);
  9275. // Throw case: throw the resume value
  9276. writer->MarkLabel(resumeThrow);
  9277. writer->Reg1(Js::OpCode::Throw, resultReg);
  9278. // Normal case: continue (value is already in result register)
  9279. writer->MarkLabel(resumeNormal);
  9280. }
  9281. void EmitYieldStar(
  9282. ParseNodeUni* yieldStarNode,
  9283. ByteCodeGenerator* byteCodeGenerator,
  9284. FuncInfo* funcInfo)
  9285. {
  9286. bool isAsync = funcInfo->IsAsyncGenerator();
  9287. auto* writer = byteCodeGenerator->Writer();
  9288. Js::ByteCodeLabel loopEntrance = writer->DefineLabel();
  9289. Js::ByteCodeLabel continueLoop = writer->DefineLabel();
  9290. Js::ByteCodeLabel continuePastLoop = writer->DefineLabel();
  9291. Js::ByteCodeLabel finishReturn = writer->DefineLabel();
  9292. Js::ByteCodeLabel finishNormal = writer->DefineLabel();
  9293. Js::RegSlot yieldStarReg = yieldStarNode->location;
  9294. // Initialize shouldReturn to false; this flag is used to indicate
  9295. // whether we should return or continue after the loop is complete
  9296. Js::RegSlot shouldReturnReg = funcInfo->AcquireTmpRegister();
  9297. writer->Reg1(Js::OpCode::LdFalse, shouldReturnReg);
  9298. // Evaluate operand and get the inner iterator
  9299. Js::RegSlot iteratorReg = funcInfo->AcquireTmpRegister();
  9300. ParseNode* operand = yieldStarNode->pnode1;
  9301. Emit(operand, byteCodeGenerator, funcInfo, false);
  9302. if (isAsync)
  9303. EmitGetAsyncIterator(iteratorReg, operand->location, byteCodeGenerator, funcInfo);
  9304. else
  9305. EmitGetIterator(iteratorReg, operand->location, byteCodeGenerator, funcInfo);
  9306. funcInfo->ReleaseLoc(operand);
  9307. // Load next method
  9308. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  9309. EmitGetObjectMethod(
  9310. nextMethodReg,
  9311. iteratorReg,
  9312. Js::PropertyIds::next,
  9313. byteCodeGenerator,
  9314. funcInfo);
  9315. // Call the next method of iterator to obtain the first result
  9316. EmitFunctionCall(
  9317. yieldStarReg,
  9318. nextMethodReg,
  9319. iteratorReg,
  9320. funcInfo->undefinedConstantRegister,
  9321. byteCodeGenerator,
  9322. funcInfo);
  9323. // Begin loop
  9324. uint loopId = writer->EnterLoop(loopEntrance);
  9325. // If this is an async generator await the yielded value
  9326. if (isAsync)
  9327. EmitAwait(yieldStarReg, yieldStarReg, byteCodeGenerator, funcInfo);
  9328. EmitThrowOnNotObject(yieldStarReg, byteCodeGenerator);
  9329. // Get the iterator result's done property
  9330. Js::RegSlot doneReg = funcInfo->AcquireTmpRegister();
  9331. EmitGetObjectProperty(
  9332. doneReg,
  9333. yieldStarReg,
  9334. Js::PropertyIds::done,
  9335. byteCodeGenerator,
  9336. funcInfo);
  9337. // Break out of loop if the done property is truthy
  9338. writer->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneReg);
  9339. funcInfo->ReleaseTmpRegister(doneReg);
  9340. // Reset shouldReturn to false
  9341. writer->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldReturnReg);
  9342. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9343. Js::ByteCodeLabel resumeThrow = writer->DefineLabel();
  9344. Js::RegSlot resumeValueReg = funcInfo->AcquireTmpRegister();
  9345. if (isAsync)
  9346. {
  9347. // For async generators, extract the value property and wrap it in a
  9348. // new result object, so that exceptions thrown when getting the value
  9349. // property are handled appropriately
  9350. Js::RegSlot valueReg = funcInfo->AcquireTmpRegister();
  9351. EmitGetObjectProperty(
  9352. valueReg,
  9353. yieldStarReg,
  9354. Js::PropertyIds::value,
  9355. byteCodeGenerator,
  9356. funcInfo);
  9357. EmitCreateYieldResult(yieldStarReg, valueReg, byteCodeGenerator, funcInfo);
  9358. funcInfo->ReleaseTmpRegister(valueReg);
  9359. }
  9360. // Yield the next result to the caller
  9361. EmitYieldAndResume(
  9362. resumeValueReg,
  9363. yieldStarReg,
  9364. resumeNormal,
  9365. resumeThrow,
  9366. byteCodeGenerator,
  9367. funcInfo);
  9368. // Return case: set shouldReturn to true and attempt to call return
  9369. writer->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldReturnReg);
  9370. Js::RegSlot returnMethodReg = funcInfo->AcquireTmpRegister();
  9371. // Load return method
  9372. Js::ByteCodeLabel noReturnMethod = writer->DefineLabel();
  9373. EmitGetOptionalObjectMethod(
  9374. returnMethodReg,
  9375. iteratorReg,
  9376. Js::PropertyIds::return_,
  9377. noReturnMethod,
  9378. byteCodeGenerator,
  9379. funcInfo);
  9380. // The iterator has a return method: call method and loop
  9381. EmitFunctionCall(
  9382. yieldStarReg,
  9383. returnMethodReg,
  9384. iteratorReg,
  9385. resumeValueReg,
  9386. byteCodeGenerator,
  9387. funcInfo);
  9388. funcInfo->ReleaseTmpRegister(returnMethodReg);
  9389. writer->Br(continueLoop);
  9390. // The iterator does not have a return method: exit loop
  9391. writer->MarkLabel(noReturnMethod);
  9392. if (isAsync)
  9393. {
  9394. Js::RegSlot awaitValue = funcInfo->AcquireTmpRegister();
  9395. writer->Reg2(Js::OpCode::Ld_A, awaitValue, resumeValueReg);
  9396. EmitAwait(awaitValue, awaitValue, byteCodeGenerator, funcInfo);
  9397. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, yieldStarReg, awaitValue);
  9398. funcInfo->ReleaseTmpRegister(awaitValue);
  9399. }
  9400. else
  9401. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, yieldStarReg, resumeValueReg);
  9402. writer->Br(finishReturn);
  9403. // Throw case: attempt to call throw
  9404. writer->MarkLabel(resumeThrow);
  9405. Js::RegSlot throwMethodReg = funcInfo->AcquireTmpRegister();
  9406. Js::ByteCodeLabel noThrowMethod = writer->DefineLabel();
  9407. // Load throw method
  9408. EmitGetOptionalObjectMethod(
  9409. throwMethodReg,
  9410. iteratorReg,
  9411. Js::PropertyIds::throw_,
  9412. noThrowMethod,
  9413. byteCodeGenerator,
  9414. funcInfo);
  9415. // Iterator has throw method: call method and loop
  9416. EmitFunctionCall(
  9417. yieldStarReg,
  9418. throwMethodReg,
  9419. iteratorReg,
  9420. resumeValueReg,
  9421. byteCodeGenerator,
  9422. funcInfo);
  9423. funcInfo->ReleaseTmpRegister(throwMethodReg);
  9424. writer->Br(continueLoop);
  9425. // Iterator does not have a throw method; close the iterator and throw a TypeError
  9426. writer->MarkLabel(noThrowMethod);
  9427. EmitIteratorClose(iteratorReg, byteCodeGenerator, funcInfo, isAsync);
  9428. byteCodeGenerator->Writer()->W1(
  9429. Js::OpCode::RuntimeTypeError,
  9430. SCODE_CODE(JSERR_YieldStarThrowMissing));
  9431. // Normal case: call next method of iterator
  9432. writer->MarkLabel(resumeNormal);
  9433. EmitFunctionCall(
  9434. yieldStarReg,
  9435. nextMethodReg,
  9436. iteratorReg,
  9437. resumeValueReg,
  9438. byteCodeGenerator,
  9439. funcInfo);
  9440. funcInfo->ReleaseTmpRegister(resumeValueReg);
  9441. funcInfo->ReleaseTmpRegister(nextMethodReg);
  9442. funcInfo->ReleaseTmpRegister(iteratorReg);
  9443. // Loop end
  9444. writer->MarkLabel(continueLoop);
  9445. writer->Br(loopEntrance);
  9446. writer->MarkLabel(continuePastLoop);
  9447. writer->ExitLoop(loopId);
  9448. // Load the iterator result value into place
  9449. EmitGetObjectProperty(
  9450. yieldStarReg,
  9451. yieldStarReg,
  9452. Js::PropertyIds::value,
  9453. byteCodeGenerator,
  9454. funcInfo);
  9455. writer->BrReg1(Js::OpCode::BrFalse_A, finishNormal, shouldReturnReg);
  9456. funcInfo->ReleaseTmpRegister(shouldReturnReg);
  9457. // Return case: return the value from the generator
  9458. writer->MarkLabel(finishReturn);
  9459. EmitReturnFromYield(yieldStarReg, byteCodeGenerator, funcInfo);
  9460. // Normal case
  9461. writer->MarkLabel(finishNormal);
  9462. }
  9463. void EmitClass(ParseNodeClass * pnodeClass, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo)
  9464. {
  9465. funcInfo->AcquireLoc(pnodeClass);
  9466. Assert(pnodeClass->pnodeConstructor);
  9467. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9468. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister();
  9469. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9470. Js::RegSlot frameDisplayLoc = funcInfo->frameDisplayRegister != Js::Constants::NoRegister ? funcInfo->frameDisplayRegister : funcInfo->GetEnvRegister();
  9471. Js::RegSlot tmpFrameDisplayLoc = funcInfo->AcquireTmpRegister();
  9472. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpFrameDisplayLoc, funcInfo);
  9473. if (frameDisplayLoc != tmpFrameDisplayLoc)
  9474. {
  9475. funcInfo->ReleaseTmpRegister(tmpFrameDisplayLoc);
  9476. }
  9477. // Extends
  9478. if (pnodeClass->pnodeExtends)
  9479. {
  9480. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9481. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9482. Js::RegSlot ctorParentLoc = funcInfo->IsTmpReg(pnodeClass->pnodeExtends->location) ? pnodeClass->pnodeExtends->location : funcInfo->AcquireTmpRegister();
  9483. Js::RegSlot protoParentLoc = funcInfo->AcquireTmpRegister();
  9484. if (pnodeClass->pnodeExtends->location != ctorParentLoc)
  9485. {
  9486. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, ctorParentLoc, pnodeClass->pnodeExtends->location);
  9487. }
  9488. Js::ByteCodeLabel needProto = byteCodeGenerator->Writer()->DefineLabel();
  9489. Js::ByteCodeLabel haveConstructor = byteCodeGenerator->Writer()->DefineLabel();
  9490. Js::ByteCodeLabel labelParentsFound = byteCodeGenerator->Writer()->DefineLabel();
  9491. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnNotNullObj_A, needProto, ctorParentLoc);
  9492. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdC_A_Null, protoParentLoc);
  9493. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdBaseFncProto, ctorParentLoc);
  9494. byteCodeGenerator->Writer()->Br(labelParentsFound);
  9495. byteCodeGenerator->Writer()->MarkLabel(needProto);
  9496. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnConstructor_A, haveConstructor, ctorParentLoc);
  9497. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ErrorOnNew));
  9498. byteCodeGenerator->Writer()->MarkLabel(haveConstructor);
  9499. uint cacheId = funcInfo->FindOrAddInlineCacheId(ctorParentLoc, Js::PropertyIds::prototype, false, false);
  9500. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld_ReuseLoc, protoParentLoc, ctorParentLoc, cacheId);
  9501. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObjectOrNull_A, labelParentsFound, protoParentLoc);
  9502. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_InvalidPrototype));
  9503. byteCodeGenerator->Writer()->MarkLabel(labelParentsFound);
  9504. if (frameDisplayLoc == funcInfo->frameDisplayRegister || frameDisplayLoc == funcInfo->GetEnvRegister())
  9505. {
  9506. byteCodeGenerator->Writer()->Reg4U(Js::OpCode::InitClass, pnodeClass->location, protoLoc, ctorParentLoc, protoParentLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9507. }
  9508. else
  9509. {
  9510. byteCodeGenerator->Writer()->Reg5U(Js::OpCode::InitInnerClass, pnodeClass->location, protoLoc, ctorParentLoc, protoParentLoc, frameDisplayLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9511. }
  9512. funcInfo->ReleaseTmpRegister(protoParentLoc);
  9513. funcInfo->ReleaseTmpRegister(ctorParentLoc);
  9514. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9515. }
  9516. else
  9517. {
  9518. if (frameDisplayLoc == funcInfo->frameDisplayRegister || frameDisplayLoc == funcInfo->GetEnvRegister())
  9519. {
  9520. byteCodeGenerator->Writer()->Reg2U(Js::OpCode::InitBaseClass, pnodeClass->location, protoLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9521. }
  9522. else
  9523. {
  9524. byteCodeGenerator->Writer()->Reg3U(Js::OpCode::InitInnerBaseClass, pnodeClass->location, protoLoc, frameDisplayLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9525. }
  9526. }
  9527. funcInfo->ReleaseTmpRegister(frameDisplayLoc);
  9528. // Methods
  9529. bool isObjectEmpty = true;
  9530. ParseNode * pnodeMembers = pnodeClass->pnodeMembers;
  9531. ParseNode * pnodeMember;
  9532. ParseNodeFnc * pnodeMemberFnc;
  9533. if (pnodeMembers != nullptr)
  9534. {
  9535. while (pnodeMembers->nop == knopList)
  9536. {
  9537. pnodeMember = pnodeMembers->AsParseNodeBin()->pnode1;
  9538. pnodeMemberFnc = pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc();
  9539. EmitMemberNode(pnodeMember, pnodeMemberFnc->IsStaticMember() ? pnodeClass->location : protoLoc, byteCodeGenerator, funcInfo, pnodeClass, /*useStore*/ false, &isObjectEmpty);
  9540. pnodeMembers = pnodeMembers->AsParseNodeBin()->pnode2;
  9541. }
  9542. pnodeMemberFnc = pnodeMembers->AsParseNodeBin()->pnode2->AsParseNodeFnc();
  9543. EmitMemberNode(pnodeMembers, pnodeMemberFnc->IsStaticMember() ? pnodeClass->location : protoLoc, byteCodeGenerator, funcInfo, pnodeClass, /*useStore*/ false, &isObjectEmpty);
  9544. }
  9545. funcInfo->ReleaseTmpRegister(protoLoc);
  9546. // Emit name binding.
  9547. if (pnodeClass->pnodeName)
  9548. {
  9549. Symbol * sym = pnodeClass->pnodeName->sym;
  9550. sym->SetNeedDeclaration(false);
  9551. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9552. }
  9553. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9554. if (pnodeClass->pnodeDeclName)
  9555. {
  9556. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9557. sym->SetNeedDeclaration(false);
  9558. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9559. }
  9560. if (pnodeClass->IsDefaultModuleExport())
  9561. {
  9562. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9563. }
  9564. }
  9565. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  9566. {
  9567. if (isSymGlobalAndSingleAssignment)
  9568. {
  9569. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  9570. }
  9571. }
  9572. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  9573. {
  9574. if (isSymGlobalAndSingleAssignment)
  9575. {
  9576. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  9577. }
  9578. }
  9579. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  9580. {
  9581. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  9582. {
  9583. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  9584. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  9585. }
  9586. }
  9587. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  9588. {
  9589. Assert(objNode->nop == knopObject);
  9590. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  9591. while (memberList != nullptr)
  9592. {
  9593. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  9594. if (memberNode->nop != knopEllipsis)
  9595. {
  9596. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  9597. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  9598. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  9599. {
  9600. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  9601. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  9602. }
  9603. }
  9604. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  9605. }
  9606. }
  9607. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  9608. {
  9609. Assert(knopDotNode->nop == knopDot);
  9610. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  9611. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  9612. bool isSymGlobalAndSingleAssignment = false;
  9613. if (objectNode->nop == knopName)
  9614. {
  9615. if (ByteCodeGenerator::IsThis(objectNode))
  9616. {
  9617. // Assume 'this' always refer to GlobalObject
  9618. // Cases like "this.a = "
  9619. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  9620. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  9621. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  9622. }
  9623. else
  9624. {
  9625. Symbol * sym = objectNode->AsParseNodeName()->sym;
  9626. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  9627. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  9628. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  9629. }
  9630. }
  9631. }
  9632. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  9633. {
  9634. // Track the Global Int Constant properties' assignments here.
  9635. uint nodeType = ParseNode::Grfnop(pnode->nop);
  9636. if (nodeType & fnopAsg)
  9637. {
  9638. if (nodeType & fnopBin)
  9639. {
  9640. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  9641. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  9642. Assert(lhs && rhs);
  9643. // Don't track other than integers and objects with member nodes.
  9644. if (rhs->nop == knopObject)
  9645. {
  9646. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  9647. }
  9648. else if (rhs->nop != knopInt &&
  9649. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  9650. {
  9651. return;
  9652. }
  9653. if (lhs->nop == knopName)
  9654. {
  9655. // Handle "a = <Integer>" cases here
  9656. Symbol * sym = lhs->AsParseNodeName()->sym;
  9657. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9658. }
  9659. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  9660. {
  9661. // Cases like "obj.a = <Integer>"
  9662. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  9663. }
  9664. }
  9665. else if (nodeType & fnopUni)
  9666. {
  9667. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  9668. if (lhs->nop == knopName)
  9669. {
  9670. // Cases like "a++"
  9671. Symbol * sym = lhs->AsParseNodeName()->sym;
  9672. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9673. }
  9674. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  9675. {
  9676. // Cases like "obj.a++"
  9677. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  9678. }
  9679. }
  9680. }
  9681. }
  9682. void Emit(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, bool isConstructorCall, bool isTopLevel)
  9683. {
  9684. if (pnode == nullptr)
  9685. {
  9686. return;
  9687. }
  9688. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  9689. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  9690. // printNop(pnode->nop);
  9691. switch (pnode->nop)
  9692. {
  9693. case knopList:
  9694. EmitList(pnode, byteCodeGenerator, funcInfo);
  9695. break;
  9696. case knopInt:
  9697. // currently, these are loaded at the top
  9698. break;
  9699. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  9700. case knopFlt:
  9701. // currently, these are loaded at the top
  9702. break;
  9703. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  9704. case knopStr:
  9705. // TODO: protocol for combining string constants
  9706. break;
  9707. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  9708. case knopBigInt:
  9709. // PTNODE(knopBigInt , "bigint const" ,None ,Pid ,fnopLeaf|fnopConst)
  9710. break;
  9711. case knopRegExp:
  9712. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  9713. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  9714. break;
  9715. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  9716. case knopNull:
  9717. // enregistered
  9718. break;
  9719. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  9720. case knopFalse:
  9721. // enregistered
  9722. break;
  9723. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  9724. case knopTrue:
  9725. // enregistered
  9726. break;
  9727. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  9728. case knopEmpty:
  9729. break;
  9730. // Unary operators.
  9731. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  9732. case knopNot:
  9733. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9734. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9735. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9736. byteCodeGenerator->Writer()->Reg2(
  9737. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9738. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9739. break;
  9740. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  9741. case knopNeg:
  9742. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9743. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9744. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9745. funcInfo->AcquireLoc(pnode);
  9746. byteCodeGenerator->Writer()->Reg2(
  9747. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9748. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9749. break;
  9750. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  9751. case knopPos:
  9752. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9753. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9754. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9755. byteCodeGenerator->Writer()->Reg2(
  9756. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9757. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9758. break;
  9759. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  9760. case knopLogNot:
  9761. {
  9762. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9763. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9764. // For boolean expressions that compute a result, we have to burn a register for the result
  9765. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9766. // full-on renaming in the back end.
  9767. funcInfo->AcquireLoc(pnode);
  9768. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  9769. {
  9770. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  9771. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  9772. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  9773. }
  9774. else
  9775. {
  9776. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9777. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  9778. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  9779. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, pnode->location);
  9780. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9781. }
  9782. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9783. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9784. break;
  9785. }
  9786. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  9787. case knopEllipsis:
  9788. {
  9789. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9790. // Transparently pass the location of the object or array.
  9791. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9792. break;
  9793. }
  9794. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  9795. case knopIncPost:
  9796. case knopDecPost:
  9797. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  9798. if (pnode->isUsed || fReturnValue)
  9799. {
  9800. byteCodeGenerator->StartStatement(pnode);
  9801. bool isESBigIntEnabled = byteCodeGenerator->GetScriptContext()->GetConfig()->IsESBigIntEnabled();
  9802. Js::OpCode op1;
  9803. if (isESBigIntEnabled)
  9804. {
  9805. op1 = (pnode->nop == knopDecPost) ? Js::OpCode::Decr_Num_A : Js::OpCode::Incr_Num_A;
  9806. }
  9807. else
  9808. {
  9809. op1 = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  9810. }
  9811. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9812. // Grab a register for the expression result.
  9813. funcInfo->AcquireLoc(pnode);
  9814. // Load the initial value, convert it (this is the expression result), and increment it.
  9815. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9816. const Js::OpCode op2 = isESBigIntEnabled ? Js::OpCode::Conv_Numeric : Js::OpCode::Conv_Num;
  9817. byteCodeGenerator->Writer()->Reg2(op2, pnode->location, pnode1->location);
  9818. // Use temporary register if lhs cannot be assigned
  9819. Js::RegSlot incDecResult = pnode1->location;
  9820. if (funcInfo->RegIsConst(incDecResult) ||
  9821. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  9822. {
  9823. incDecResult = funcInfo->AcquireTmpRegister();
  9824. }
  9825. if (isESBigIntEnabled)
  9826. {
  9827. byteCodeGenerator->Writer()->Reg2(op1, incDecResult, pnode->location);
  9828. }
  9829. else
  9830. {
  9831. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  9832. Assert(oneReg != Js::Constants::NoRegister);
  9833. byteCodeGenerator->Writer()->Reg3(op1, incDecResult, pnode->location, oneReg);
  9834. }
  9835. // Store the incremented value.
  9836. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9837. // Release the incremented value and the l-value.
  9838. if (incDecResult != pnode1->location)
  9839. {
  9840. funcInfo->ReleaseTmpRegister(incDecResult);
  9841. }
  9842. funcInfo->ReleaseLoad(pnode1);
  9843. byteCodeGenerator->EndStatement(pnode);
  9844. break;
  9845. }
  9846. else
  9847. {
  9848. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  9849. }
  9850. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  9851. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  9852. case knopIncPre:
  9853. case knopDecPre:
  9854. {
  9855. byteCodeGenerator->StartStatement(pnode);
  9856. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  9857. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9858. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9859. // (i.e., is a constant).
  9860. const bool need_result_location =
  9861. pnode->isUsed
  9862. || fReturnValue
  9863. || funcInfo->RegIsConst(pnode1->location)
  9864. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  9865. if (need_result_location)
  9866. {
  9867. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9868. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9869. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  9870. // Store the incremented value and release the l-value.
  9871. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  9872. }
  9873. else
  9874. {
  9875. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9876. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  9877. // Store the incremented value and release the l-value.
  9878. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  9879. }
  9880. funcInfo->ReleaseLoad(pnode1);
  9881. byteCodeGenerator->EndStatement(pnode);
  9882. break;
  9883. }
  9884. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  9885. case knopTypeof:
  9886. {
  9887. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9888. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  9889. switch (pnodeOpnd->nop)
  9890. {
  9891. case knopDot:
  9892. {
  9893. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9894. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9895. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  9896. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9897. funcInfo->AcquireLoc(pnode);
  9898. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  9899. break;
  9900. }
  9901. case knopIndex:
  9902. {
  9903. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9904. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9905. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9906. funcInfo->AcquireLoc(pnode);
  9907. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9908. break;
  9909. }
  9910. case knopName:
  9911. {
  9912. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9913. if (pnodeNameOpnd->IsUserIdentifier())
  9914. {
  9915. funcInfo->AcquireLoc(pnode);
  9916. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9917. break;
  9918. }
  9919. // Special names should fallthrough to default case
  9920. }
  9921. default:
  9922. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9923. funcInfo->ReleaseLoc(pnodeOpnd);
  9924. byteCodeGenerator->Writer()->Reg2(
  9925. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9926. break;
  9927. }
  9928. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9929. break;
  9930. }
  9931. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9932. case knopVoid:
  9933. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9934. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9935. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9936. break;
  9937. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9938. case knopArray:
  9939. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9940. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9941. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9942. break;
  9943. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9944. case knopObject:
  9945. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9946. funcInfo->AcquireLoc(pnode);
  9947. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9948. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9949. break;
  9950. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9951. case knopComputedName:
  9952. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9953. if (pnode->location == Js::Constants::NoRegister)
  9954. {
  9955. // The name is some expression with no home location. We can just re-use the register.
  9956. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9957. }
  9958. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9959. {
  9960. // The name had to be protected from side-effects of the RHS.
  9961. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9962. }
  9963. break;
  9964. // Binary and Ternary Operators
  9965. case knopAdd:
  9966. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9967. break;
  9968. case knopSub:
  9969. case knopMul:
  9970. case knopExpo:
  9971. case knopDiv:
  9972. case knopMod:
  9973. case knopOr:
  9974. case knopXor:
  9975. case knopAnd:
  9976. case knopLsh:
  9977. case knopRsh:
  9978. case knopRs2:
  9979. case knopIn:
  9980. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9981. break;
  9982. case knopInstOf:
  9983. {
  9984. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9985. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9986. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9987. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9988. funcInfo->AcquireLoc(pnode);
  9989. uint cacheId = funcInfo->NewIsInstInlineCache();
  9990. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9991. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9992. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9993. }
  9994. break;
  9995. case knopEq:
  9996. case knopEqv:
  9997. case knopNEqv:
  9998. case knopNe:
  9999. case knopLt:
  10000. case knopLe:
  10001. case knopGe:
  10002. case knopGt:
  10003. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10004. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  10005. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10006. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10007. funcInfo->AcquireLoc(pnode);
  10008. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  10009. pnode->AsParseNodeBin()->pnode2->location);
  10010. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10011. break;
  10012. case knopNew:
  10013. {
  10014. EmitNew(pnode, byteCodeGenerator, funcInfo);
  10015. byteCodeGenerator->EndStatement(pnode);
  10016. break;
  10017. }
  10018. case knopDelete:
  10019. {
  10020. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  10021. byteCodeGenerator->StartStatement(pnode);
  10022. switch (pexpr->nop)
  10023. {
  10024. case knopName:
  10025. {
  10026. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  10027. if (pnodeName->IsSpecialName())
  10028. {
  10029. funcInfo->AcquireLoc(pnode);
  10030. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  10031. }
  10032. else
  10033. {
  10034. funcInfo->AcquireLoc(pnode);
  10035. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  10036. }
  10037. break;
  10038. }
  10039. case knopDot:
  10040. {
  10041. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  10042. {
  10043. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  10044. funcInfo->AcquireLoc(pnode);
  10045. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  10046. }
  10047. else
  10048. {
  10049. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10050. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  10051. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  10052. funcInfo->AcquireLoc(pnode);
  10053. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  10054. funcInfo->FindOrAddReferencedPropertyId(propertyId), byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  10055. }
  10056. break;
  10057. }
  10058. case knopIndex:
  10059. {
  10060. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  10061. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  10062. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  10063. funcInfo->AcquireLoc(pnode);
  10064. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  10065. break;
  10066. }
  10067. default:
  10068. {
  10069. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  10070. funcInfo->ReleaseLoc(pexpr);
  10071. byteCodeGenerator->Writer()->Reg2(
  10072. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  10073. break;
  10074. }
  10075. }
  10076. byteCodeGenerator->EndStatement(pnode);
  10077. break;
  10078. }
  10079. case knopCall:
  10080. {
  10081. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  10082. byteCodeGenerator->StartStatement(pnodeCall);
  10083. if (pnodeCall->isSuperCall)
  10084. {
  10085. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue, /*fEvaluateComponents=*/ true);
  10086. }
  10087. else if (pnodeCall->pnodeTarget->nop == knopImport)
  10088. {
  10089. ParseNodePtr args = pnodeCall->pnodeArgs;
  10090. Assert(CountArguments(args) == 2); // import() takes one argument
  10091. Emit(args, byteCodeGenerator, funcInfo, false);
  10092. funcInfo->ReleaseLoc(args);
  10093. funcInfo->AcquireLoc(pnodeCall);
  10094. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  10095. }
  10096. else
  10097. {
  10098. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  10099. {
  10100. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  10101. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  10102. }
  10103. else
  10104. {
  10105. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  10106. }
  10107. }
  10108. byteCodeGenerator->EndStatement(pnode);
  10109. break;
  10110. }
  10111. case knopIndex:
  10112. {
  10113. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10114. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  10115. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  10116. Js::RegSlot protoLocation = callObjLocation;
  10117. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10118. {
  10119. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  10120. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  10121. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  10122. }
  10123. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10124. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10125. funcInfo->AcquireLoc(pnode);
  10126. byteCodeGenerator->Writer()->Element(
  10127. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  10128. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10129. break;
  10130. }
  10131. // this is MemberExpression as rvalue
  10132. case knopDot:
  10133. {
  10134. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10135. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  10136. Js::RegSlot protoLocation = callObjLocation;
  10137. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10138. {
  10139. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  10140. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  10141. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  10142. }
  10143. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10144. funcInfo->AcquireLoc(pnode);
  10145. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  10146. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  10147. if (propertyId == Js::PropertyIds::length)
  10148. {
  10149. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  10150. }
  10151. else if (pnode->IsCallApplyTargetLoad())
  10152. {
  10153. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  10154. }
  10155. else if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10156. {
  10157. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  10158. }
  10159. else
  10160. {
  10161. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  10162. }
  10163. break;
  10164. }
  10165. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10166. case knopAsg:
  10167. {
  10168. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  10169. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  10170. byteCodeGenerator->StartStatement(pnode);
  10171. if (pnode->isUsed || fReturnValue)
  10172. {
  10173. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  10174. // which will copy the assigned value there.
  10175. funcInfo->AcquireLoc(pnode);
  10176. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  10177. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  10178. }
  10179. else
  10180. {
  10181. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  10182. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  10183. }
  10184. funcInfo->ReleaseLoc(rhs);
  10185. if (!lhs->IsPattern())
  10186. {
  10187. funcInfo->ReleaseReference(lhs);
  10188. }
  10189. byteCodeGenerator->EndStatement(pnode);
  10190. break;
  10191. }
  10192. case knopName:
  10193. funcInfo->AcquireLoc(pnode);
  10194. if (ByteCodeGenerator::IsThis(pnode))
  10195. {
  10196. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  10197. }
  10198. else
  10199. {
  10200. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  10201. }
  10202. break;
  10203. case knopComma:
  10204. {
  10205. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10206. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  10207. // Easier to correct this here than to check every binary op in the parser.
  10208. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  10209. pnode1->isUsed = false;
  10210. if (pnode1->nop == knopComma)
  10211. {
  10212. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  10213. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  10214. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  10215. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  10216. SList<ParseNode *> rhsStack(alloc);
  10217. do
  10218. {
  10219. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  10220. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  10221. pnode1->isUsed = false;
  10222. } while (pnode1->nop == knopComma);
  10223. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  10224. while (!rhsStack.Empty())
  10225. {
  10226. ParseNode *pnodeRhs = rhsStack.Pop();
  10227. pnodeRhs->isUsed = false;
  10228. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  10229. funcInfo->ReleaseLoc(pnodeRhs);
  10230. }
  10231. }
  10232. else
  10233. {
  10234. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  10235. }
  10236. funcInfo->ReleaseLoc(pnode1);
  10237. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  10238. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  10239. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10240. funcInfo->AcquireLoc(pnode);
  10241. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  10242. {
  10243. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  10244. }
  10245. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10246. }
  10247. break;
  10248. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  10249. // boolean value short-circuits the operation, and to the value of the right-hand expression
  10250. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  10251. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10252. case knopLogOr:
  10253. {
  10254. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10255. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10256. // We use a single dest here for the whole generating boolean expr, because we were poorly
  10257. // optimizing the previous version where we had a dest for each level
  10258. funcInfo->AcquireLoc(pnode);
  10259. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, false, byteCodeGenerator, funcInfo);
  10260. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10261. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10262. break;
  10263. }
  10264. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10265. case knopLogAnd:
  10266. {
  10267. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10268. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10269. // We use a single dest here for the whole generating boolean expr, because we were poorly
  10270. // optimizing the previous version where we had a dest for each level
  10271. funcInfo->AcquireLoc(pnode);
  10272. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, false, byteCodeGenerator, funcInfo);
  10273. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10274. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10275. break;
  10276. }
  10277. // The Coalescing operator resolves to the left hand side if it is not null or undefined
  10278. // In that case the right hand side is not evaluated
  10279. // If the left hand side is null or undefined it resolves to the right hand side
  10280. // PTNODE(knopCoalesce , "??" ,None ,Bin ,fnopBin)
  10281. case knopCoalesce:
  10282. {
  10283. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10284. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10285. funcInfo->AcquireLoc(pnode);
  10286. // LHS
  10287. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10288. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode1->location);
  10289. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10290. // check for null/undefined with != null
  10291. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, doneLabel, pnode->location, funcInfo->nullConstantRegister);
  10292. // RHS
  10293. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  10294. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  10295. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10296. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10297. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10298. break;
  10299. }
  10300. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10301. case knopQmark:
  10302. {
  10303. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  10304. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  10305. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  10306. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  10307. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  10308. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  10309. // For boolean expressions that compute a result, we have to burn a register for the result
  10310. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  10311. // full-on renaming in the back end.
  10312. funcInfo->AcquireLoc(pnode);
  10313. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  10314. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  10315. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  10316. // Record the branch bytecode offset
  10317. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  10318. byteCodeGenerator->Writer()->Br(skipLabel);
  10319. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10320. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  10321. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  10322. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  10323. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  10324. break;
  10325. }
  10326. case knopAsgAdd:
  10327. case knopAsgSub:
  10328. case knopAsgMul:
  10329. case knopAsgDiv:
  10330. case knopAsgExpo:
  10331. case knopAsgMod:
  10332. case knopAsgAnd:
  10333. case knopAsgXor:
  10334. case knopAsgOr:
  10335. case knopAsgLsh:
  10336. case knopAsgRsh:
  10337. case knopAsgRs2:
  10338. {
  10339. byteCodeGenerator->StartStatement(pnode);
  10340. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  10341. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  10342. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  10343. // (i.e., is a constant).
  10344. const bool need_result_location =
  10345. pnode->isUsed
  10346. || fReturnValue
  10347. || funcInfo->RegIsConst(lhs->location)
  10348. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  10349. if (need_result_location)
  10350. {
  10351. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  10352. // Grab a register for the initial value and load it.
  10353. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  10354. funcInfo->ReleaseLoc(rhs);
  10355. // Do the arithmetic, store the result, and release the l-value.
  10356. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  10357. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  10358. }
  10359. else
  10360. {
  10361. // Grab a register for the initial value and load it. Might modify lhs->location.
  10362. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  10363. funcInfo->ReleaseLoc(rhs);
  10364. // Do the arithmetic, store the result, and release the l-value.
  10365. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  10366. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  10367. }
  10368. funcInfo->ReleaseLoad(lhs);
  10369. byteCodeGenerator->EndStatement(pnode);
  10370. break;
  10371. }
  10372. // General nodes.
  10373. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  10374. case knopTempRef:
  10375. // TODO: check whether mov is necessary
  10376. funcInfo->AcquireLoc(pnode);
  10377. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  10378. break;
  10379. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  10380. case knopTemp:
  10381. // Emit initialization code
  10382. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  10383. {
  10384. byteCodeGenerator->StartStatement(pnode);
  10385. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  10386. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  10387. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  10388. byteCodeGenerator->EndStatement(pnode);
  10389. }
  10390. break;
  10391. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10392. case knopVarDecl:
  10393. case knopConstDecl:
  10394. case knopLetDecl:
  10395. {
  10396. // Emit initialization code
  10397. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  10398. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  10399. if (initNode != nullptr || pnode->nop == knopLetDecl)
  10400. {
  10401. Symbol *sym = pnode->AsParseNodeVar()->sym;
  10402. Js::RegSlot rhsLocation;
  10403. byteCodeGenerator->StartStatement(pnode);
  10404. if (initNode != nullptr)
  10405. {
  10406. Emit(initNode, byteCodeGenerator, funcInfo, false);
  10407. rhsLocation = initNode->location;
  10408. if (initNode->nop == knopObject)
  10409. {
  10410. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  10411. }
  10412. else if (initNode->nop == knopInt)
  10413. {
  10414. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  10415. }
  10416. }
  10417. else
  10418. {
  10419. Assert(pnode->nop == knopLetDecl);
  10420. rhsLocation = funcInfo->AcquireTmpRegister();
  10421. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  10422. }
  10423. if (pnode->nop != knopVarDecl)
  10424. {
  10425. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  10426. sym->SetNeedDeclaration(false);
  10427. }
  10428. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  10429. funcInfo->ReleaseTmpRegister(rhsLocation);
  10430. byteCodeGenerator->EndStatement(pnode);
  10431. }
  10432. break;
  10433. }
  10434. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10435. case knopFncDecl:
  10436. // The "function declarations" were emitted in DefineFunctions()
  10437. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  10438. {
  10439. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  10440. }
  10441. break;
  10442. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  10443. case knopClassDecl:
  10444. EmitClass(pnode->AsParseNodeClass(), byteCodeGenerator, funcInfo);
  10445. break;
  10446. case knopStrTemplate:
  10447. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10448. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  10449. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10450. break;
  10451. case knopEndCode:
  10452. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  10453. // load undefined for the fallthrough case:
  10454. if (!funcInfo->IsGlobalFunction())
  10455. {
  10456. if (funcInfo->IsClassConstructor())
  10457. {
  10458. // For class constructors, we need to explicitly load 'this' into the return register.
  10459. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  10460. }
  10461. else
  10462. {
  10463. // In the global function, implicit return values are copied to the return register, and if
  10464. // necessary the return register is initialized at the top. Don't clobber the value here.
  10465. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  10466. }
  10467. }
  10468. // Label for non-fall-through return
  10469. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  10470. if (funcInfo->GetHasCachedScope())
  10471. {
  10472. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  10473. }
  10474. byteCodeGenerator->StartStatement(pnode);
  10475. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  10476. byteCodeGenerator->EndStatement(pnode);
  10477. break;
  10478. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10479. case knopDebugger:
  10480. byteCodeGenerator->StartStatement(pnode);
  10481. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  10482. byteCodeGenerator->EndStatement(pnode);
  10483. break;
  10484. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10485. case knopFor:
  10486. {
  10487. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  10488. if (pnodeFor->pnodeInverted != nullptr)
  10489. {
  10490. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  10491. }
  10492. else
  10493. {
  10494. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10495. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  10496. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  10497. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10498. EmitLoop(pnodeFor,
  10499. pnodeFor->pnodeCond,
  10500. pnodeFor->pnodeBody,
  10501. pnodeFor->pnodeIncr,
  10502. byteCodeGenerator,
  10503. funcInfo,
  10504. fReturnValue,
  10505. FALSE,
  10506. pnodeFor->pnodeBlock);
  10507. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10508. }
  10509. break;
  10510. }
  10511. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10512. case knopIf:
  10513. {
  10514. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  10515. byteCodeGenerator->StartStatement(pnodeIf);
  10516. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  10517. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  10518. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  10519. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  10520. byteCodeGenerator->EndStatement(pnodeIf);
  10521. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  10522. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  10523. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  10524. if (pnodeIf->pnodeFalse != nullptr)
  10525. {
  10526. // has else clause
  10527. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  10528. // Record the branch bytecode offset
  10529. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  10530. // then clause skips else clause
  10531. byteCodeGenerator->Writer()->Br(skipLabel);
  10532. // generate code for else clause
  10533. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10534. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  10535. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  10536. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  10537. }
  10538. else
  10539. {
  10540. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10541. }
  10542. if (pnodeIf->emitLabels)
  10543. {
  10544. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  10545. }
  10546. break;
  10547. }
  10548. case knopWhile:
  10549. {
  10550. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  10551. EmitLoop(pnodeWhile,
  10552. pnodeWhile->pnodeCond,
  10553. pnodeWhile->pnodeBody,
  10554. nullptr,
  10555. byteCodeGenerator,
  10556. funcInfo,
  10557. fReturnValue);
  10558. break;
  10559. }
  10560. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10561. case knopDoWhile:
  10562. {
  10563. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  10564. EmitLoop(pnodeWhile,
  10565. pnodeWhile->pnodeCond,
  10566. pnodeWhile->pnodeBody,
  10567. nullptr,
  10568. byteCodeGenerator,
  10569. funcInfo,
  10570. fReturnValue,
  10571. true);
  10572. break;
  10573. }
  10574. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10575. case knopForIn:
  10576. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  10577. break;
  10578. case knopForAwaitOf:
  10579. case knopForOf:
  10580. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  10581. break;
  10582. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10583. case knopReturn:
  10584. {
  10585. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  10586. byteCodeGenerator->StartStatement(pnodeReturn);
  10587. if (pnodeReturn->pnodeExpr != nullptr)
  10588. {
  10589. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  10590. {
  10591. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  10592. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  10593. }
  10594. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  10595. if (funcInfo->IsAsyncGenerator())
  10596. {
  10597. EmitAwait(
  10598. ByteCodeGenerator::ReturnRegister,
  10599. pnodeReturn->pnodeExpr->location,
  10600. byteCodeGenerator,
  10601. funcInfo);
  10602. }
  10603. else if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  10604. {
  10605. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  10606. }
  10607. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  10608. }
  10609. else
  10610. {
  10611. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  10612. }
  10613. if (funcInfo->IsClassConstructor())
  10614. {
  10615. // return expr; // becomes like below:
  10616. //
  10617. // if (IsObject(expr)) {
  10618. // return expr;
  10619. // } else if (IsBaseClassConstructor) {
  10620. // return this;
  10621. // } else if (!IsUndefined(expr)) {
  10622. // throw TypeError;
  10623. // }
  10624. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  10625. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  10626. if (funcInfo->IsBaseClassConstructor())
  10627. {
  10628. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  10629. }
  10630. else
  10631. {
  10632. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  10633. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  10634. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  10635. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  10636. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  10637. }
  10638. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  10639. }
  10640. if (pnodeReturn->grfnop & fnopCleanup)
  10641. {
  10642. byteCodeGenerator->EmitJumpCleanup(nullptr, funcInfo);
  10643. }
  10644. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  10645. byteCodeGenerator->EndStatement(pnodeReturn);
  10646. break;
  10647. }
  10648. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10649. case knopBlock:
  10650. {
  10651. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  10652. if (pnodeBlock->pnodeStmt != nullptr)
  10653. {
  10654. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  10655. if (pnodeBlock->emitLabels)
  10656. {
  10657. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  10658. }
  10659. }
  10660. break;
  10661. }
  10662. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10663. case knopWith:
  10664. {
  10665. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  10666. Assert(pnodeWith->pnodeObj != nullptr);
  10667. byteCodeGenerator->StartStatement(pnodeWith);
  10668. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  10669. // is overwritten in the body, the lookups are not affected.
  10670. funcInfo->AcquireLoc(pnodeWith);
  10671. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  10672. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10673. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  10674. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewUnscopablesWrapperObject, pnodeWith->location, regVal);
  10675. byteCodeGenerator->EndStatement(pnodeWith);
  10676. #ifdef PERF_HINT
  10677. if (PHASE_TRACE1(Js::PerfHintPhase))
  10678. {
  10679. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  10680. }
  10681. #endif
  10682. if (pnodeWith->pnodeBody != nullptr)
  10683. {
  10684. Scope *scope = pnodeWith->scope;
  10685. scope->SetLocation(pnodeWith->location);
  10686. byteCodeGenerator->PushScope(scope);
  10687. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  10688. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  10689. {
  10690. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  10691. }
  10692. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10693. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  10694. byteCodeGenerator->PopScope();
  10695. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  10696. }
  10697. if (pnodeWith->emitLabels)
  10698. {
  10699. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  10700. }
  10701. funcInfo->ReleaseTmpRegister(regVal);
  10702. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  10703. break;
  10704. }
  10705. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10706. case knopBreak:
  10707. {
  10708. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10709. Assert(pnodeJump->pnodeTarget->emitLabels);
  10710. byteCodeGenerator->StartStatement(pnodeJump);
  10711. if (pnodeJump->grfnop & fnopCleanup)
  10712. {
  10713. byteCodeGenerator->EmitJumpCleanup(pnodeJump->pnodeTarget, funcInfo);
  10714. }
  10715. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  10716. if (pnodeJump->emitLabels)
  10717. {
  10718. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  10719. }
  10720. byteCodeGenerator->EndStatement(pnodeJump);
  10721. break;
  10722. }
  10723. case knopContinue:
  10724. {
  10725. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10726. Assert(pnodeJump->pnodeTarget->emitLabels);
  10727. byteCodeGenerator->StartStatement(pnodeJump);
  10728. if (pnodeJump->grfnop & fnopCleanup)
  10729. {
  10730. byteCodeGenerator->EmitJumpCleanup(pnodeJump->pnodeTarget, funcInfo);
  10731. }
  10732. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  10733. byteCodeGenerator->EndStatement(pnodeJump);
  10734. break;
  10735. }
  10736. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10737. case knopSwitch:
  10738. {
  10739. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  10740. BOOL fHasDefault = false;
  10741. Assert(pnodeSwitch->pnodeVal != nullptr);
  10742. byteCodeGenerator->StartStatement(pnodeSwitch);
  10743. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  10744. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10745. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  10746. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10747. byteCodeGenerator->EndStatement(pnodeSwitch);
  10748. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  10749. // code so the BE can optimize it.
  10750. ParseNodeCase *pnodeCase;
  10751. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10752. {
  10753. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  10754. // expression take place regardless.
  10755. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  10756. if (pnodeCase == pnodeSwitch->pnodeDefault)
  10757. {
  10758. fHasDefault = true;
  10759. continue;
  10760. }
  10761. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10762. byteCodeGenerator->Writer()->BrReg2(
  10763. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  10764. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  10765. }
  10766. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  10767. if (fHasDefault)
  10768. {
  10769. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  10770. }
  10771. else
  10772. {
  10773. if (!pnodeSwitch->emitLabels)
  10774. {
  10775. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  10776. }
  10777. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  10778. }
  10779. // Now emit the case arms to which we jump on matching a case value.
  10780. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10781. {
  10782. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  10783. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10784. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  10785. }
  10786. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10787. funcInfo->ReleaseTmpRegister(regVal);
  10788. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  10789. if (!fHasDefault || pnodeSwitch->emitLabels)
  10790. {
  10791. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  10792. }
  10793. break;
  10794. }
  10795. case knopTryCatch:
  10796. {
  10797. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  10798. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  10799. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  10800. Assert(pnodeTry);
  10801. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  10802. Assert(pnodeCatch);
  10803. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  10804. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  10805. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  10806. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  10807. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  10808. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  10809. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10810. byteCodeGenerator->PopJumpCleanup();
  10811. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10812. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  10813. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10814. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  10815. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  10816. Js::RegSlot location = Js::Constants::NoRegister;
  10817. Js::DebuggerScope *debuggerScope = nullptr;
  10818. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  10819. ParseNode *tempLocationNode = nullptr;
  10820. if (pnodeCatch->HasPatternParam())
  10821. {
  10822. location = pnodeCatch->GetParam()->AsParseNodeParamPattern()->location;
  10823. }
  10824. else if (pnodeCatch->HasParam())
  10825. {
  10826. location = pnodeCatch->GetParam()->AsParseNodeName()->sym->GetLocation();
  10827. }
  10828. if (location == Js::Constants::NoRegister)
  10829. {
  10830. tempLocationNode = pnodeCatch->HasParam() ? pnodeCatch->GetParam() : pnodeCatch;
  10831. location = funcInfo->AcquireLoc(tempLocationNode);
  10832. }
  10833. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10834. Scope *scope = pnodeCatch->scope;
  10835. byteCodeGenerator->PushScope(scope);
  10836. if (scope->GetMustInstantiate())
  10837. {
  10838. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10839. if (scope->GetIsObject())
  10840. {
  10841. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10842. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10843. }
  10844. else
  10845. {
  10846. int index = Js::DebuggerScope::InvalidScopeIndex;
  10847. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10848. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10849. }
  10850. }
  10851. else
  10852. {
  10853. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10854. }
  10855. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10856. {
  10857. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10858. {
  10859. Assert(scope->GetMustInstantiate());
  10860. if (scope->GetIsObject())
  10861. {
  10862. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10863. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10864. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10865. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10866. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10867. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10868. }
  10869. else
  10870. {
  10871. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10872. if (initializeParam)
  10873. {
  10874. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10875. }
  10876. else
  10877. {
  10878. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10879. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10880. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10881. funcInfo->ReleaseTmpRegister(tmpReg);
  10882. }
  10883. }
  10884. }
  10885. else
  10886. {
  10887. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10888. if (initializeParam)
  10889. {
  10890. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10891. }
  10892. else
  10893. {
  10894. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10895. }
  10896. }
  10897. };
  10898. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10899. if (pnodeCatch->HasPatternParam())
  10900. {
  10901. ParseNode *pnode1 = pnodeCatch->GetParam()->AsParseNodeParamPattern()->pnode1;
  10902. Parser::MapBindIdentifier(pnode1, [&](ParseNodePtr item)
  10903. {
  10904. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10905. if (itemLocation == Js::Constants::NoRegister)
  10906. {
  10907. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10908. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10909. itemLocation = ByteCodeGenerator::ReturnRegister;
  10910. }
  10911. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10912. });
  10913. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10914. // Now emitting bytecode for destructuring pattern
  10915. byteCodeGenerator->StartStatement(pnodeCatch);
  10916. Assert(pnode1->IsPattern());
  10917. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  10918. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10919. byteCodeGenerator->EndStatement(pnodeCatch);
  10920. }
  10921. else
  10922. {
  10923. if (pnodeCatch->HasParam())
  10924. {
  10925. Symbol *sym = pnodeCatch->GetParam()->AsParseNodeName()->sym;
  10926. ParamTrackAndInitialization(sym, true /*initializeParam*/, location);
  10927. if (scope->GetMustInstantiate())
  10928. {
  10929. sym->SetIsGlobalCatch(true);
  10930. }
  10931. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10932. }
  10933. // Allow a debugger to stop on the 'catch'
  10934. byteCodeGenerator->StartStatement(pnodeCatch);
  10935. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10936. byteCodeGenerator->EndStatement(pnodeCatch);
  10937. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  10938. }
  10939. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10940. byteCodeGenerator->PopJumpCleanup();
  10941. byteCodeGenerator->PopScope();
  10942. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10943. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10944. if (tempLocationNode != nullptr)
  10945. {
  10946. funcInfo->ReleaseLoc(tempLocationNode);
  10947. }
  10948. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10949. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10950. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10951. break;
  10952. }
  10953. case knopTryFinally:
  10954. {
  10955. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10956. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10957. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10958. Assert(pnodeTry);
  10959. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10960. Assert(pnodeFinally);
  10961. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10962. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10963. Js::RegSlot regException = Js::Constants::NoRegister;
  10964. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10965. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10966. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10967. bool hasYield = byteCodeGenerator->GetHasYield(pnodeTryFinally);
  10968. if (hasYield)
  10969. {
  10970. Assert(funcInfo->byteCodeFunction->IsCoroutine());
  10971. regException = funcInfo->AcquireTmpRegister();
  10972. regOffset = funcInfo->AcquireTmpRegister();
  10973. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10974. byteCodeGenerator->PushJumpCleanupForTry(
  10975. Js::OpCode::TryFinallyWithYield,
  10976. finallyLabel,
  10977. regException,
  10978. regOffset);
  10979. }
  10980. else
  10981. {
  10982. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10983. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  10984. }
  10985. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10986. funcInfo->StartRecordingOutArgs(1);
  10987. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10988. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10989. byteCodeGenerator->PopJumpCleanup();
  10990. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10991. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10992. // Note: although we don't use OpCode::Leave for finally block,
  10993. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10994. // This has to be on offset prior to offset of 1st statement of finally.
  10995. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10996. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10997. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10998. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10999. byteCodeGenerator->PushJumpCleanupForTry(
  11000. Js::OpCode::ResumeFinally,
  11001. finallyLabel,
  11002. regException,
  11003. regOffset);
  11004. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  11005. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  11006. if (hasYield)
  11007. {
  11008. funcInfo->ReleaseTmpRegister(regOffset);
  11009. funcInfo->ReleaseTmpRegister(regException);
  11010. }
  11011. byteCodeGenerator->PopJumpCleanup();
  11012. funcInfo->EndRecordingOutArgs(1);
  11013. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  11014. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  11015. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  11016. break;
  11017. }
  11018. case knopThrow:
  11019. byteCodeGenerator->StartStatement(pnode);
  11020. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11021. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  11022. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11023. byteCodeGenerator->EndStatement(pnode);
  11024. break;
  11025. case knopYieldLeaf:
  11026. byteCodeGenerator->StartStatement(pnode);
  11027. funcInfo->AcquireLoc(pnode);
  11028. EmitYield(pnode->location, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  11029. byteCodeGenerator->EndStatement(pnode);
  11030. break;
  11031. case knopAwait:
  11032. byteCodeGenerator->StartStatement(pnode);
  11033. funcInfo->AcquireLoc(pnode);
  11034. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11035. EmitAwait(pnode->location, pnode->AsParseNodeUni()->pnode1->location, byteCodeGenerator, funcInfo);
  11036. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11037. byteCodeGenerator->EndStatement(pnode);
  11038. break;
  11039. case knopYield:
  11040. byteCodeGenerator->StartStatement(pnode);
  11041. funcInfo->AcquireLoc(pnode);
  11042. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11043. EmitYield(pnode->location, pnode->AsParseNodeUni()->pnode1->location, byteCodeGenerator, funcInfo);
  11044. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11045. byteCodeGenerator->EndStatement(pnode);
  11046. break;
  11047. case knopYieldStar:
  11048. byteCodeGenerator->StartStatement(pnode);
  11049. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  11050. byteCodeGenerator->EndStatement(pnode);
  11051. break;
  11052. case knopExportDefault:
  11053. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  11054. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  11055. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  11056. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  11057. break;
  11058. default:
  11059. AssertMsg(0, "emit unhandled pnode op");
  11060. break;
  11061. }
  11062. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  11063. {
  11064. // If this statement may produce the global function's return value, copy its result to the return register.
  11065. // fReturnValue implies global function, which implies that "return" is a parse error.
  11066. Assert(funcInfo->IsGlobalFunction());
  11067. Assert(pnode->nop != knopReturn);
  11068. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  11069. }
  11070. }