ByteCodeEmitter.cpp 468 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeByteCodePch.h"
  6. #include "FormalsUtil.h"
  7. #include "Language/AsmJs.h"
  8. #include "ConfigFlagsList.h"
  9. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  10. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  12. void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
  13. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator = Js::Constants::NoRegister);
  14. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  15. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  16. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  17. bool CallTargetIsArray(ParseNode *pnode)
  18. {
  19. return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
  20. }
  21. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  22. if ((isTopLevel)) \
  23. { \
  24. byteCodeGenerator->StartStatement(pnode); \
  25. }
  26. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  27. if ((isTopLevel)) \
  28. { \
  29. byteCodeGenerator->EndStatement(pnode); \
  30. }
  31. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE, ByteCodeGenerator *byteCodeGenerator)
  32. {
  33. // Try to determine whether pnodeSE (SE = side effect) may kill the named var represented by pnode.
  34. if (pnode->nop == knopComputedName)
  35. {
  36. pnode = pnode->AsParseNodeUni()->pnode1;
  37. }
  38. if (pnode->nop != knopName)
  39. {
  40. // Only investigating named vars here.
  41. return false;
  42. }
  43. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  44. SList<ParseNode*> pNodeSEStack(alloc);
  45. pNodeSEStack.Push(pnodeSE);
  46. // A pnodeSE can have children that can cause a side effect on pnode. A stack is used to check
  47. // pnodeSE and all potential pnodeSE children that could cause a side effect on pnode. When a
  48. // child pnodeSE can cause a side effect on pnode, immediately return true. Otherwise continue
  49. // checking children of pnodeSE until none exist
  50. while (!pNodeSEStack.Empty())
  51. {
  52. ParseNode *currPnodeSE = pNodeSEStack.Pop();
  53. uint fnop = ParseNode::Grfnop(currPnodeSE->nop);
  54. if (fnop & fnopLeaf)
  55. {
  56. // pnodeSE is a leaf and can't kill anything.
  57. continue;
  58. }
  59. else if (fnop & fnopAsg)
  60. {
  61. // pnodeSE is an assignment (=, ++, +=, etc.)
  62. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  63. // maybe because of code layout or some other subtle effect.
  64. return true;
  65. }
  66. else if (fnop & fnopUni)
  67. {
  68. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  69. if (currPnodeSE->nop == knopTempRef)
  70. {
  71. continue;
  72. }
  73. else if (currPnodeSE->AsParseNodeUni()->pnode1)
  74. {
  75. pNodeSEStack.Push(currPnodeSE->AsParseNodeUni()->pnode1);
  76. }
  77. }
  78. else if (fnop & fnopBin)
  79. {
  80. // currPnodeSE is a binary (or ternary) op, so check sources (if present).
  81. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode1);
  82. if (currPnodeSE->AsParseNodeBin()->pnode2)
  83. {
  84. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode2);
  85. }
  86. }
  87. else if (currPnodeSE->nop == knopQmark)
  88. {
  89. ParseNodeTri * pnodeTriSE = currPnodeSE->AsParseNodeTri();
  90. pNodeSEStack.Push(pnodeTriSE->pnode1);
  91. pNodeSEStack.Push(pnodeTriSE->pnode2);
  92. pNodeSEStack.Push(pnodeTriSE->pnode3);
  93. }
  94. else if (currPnodeSE->nop == knopCall || currPnodeSE->nop == knopNew)
  95. {
  96. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeTarget);
  97. if (currPnodeSE->AsParseNodeCall()->pnodeArgs)
  98. {
  99. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeArgs);
  100. }
  101. }
  102. else if (currPnodeSE->nop == knopList)
  103. {
  104. return true;
  105. }
  106. }
  107. return false;
  108. }
  109. bool IsCallOfConstants(ParseNode *pnode);
  110. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  111. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  112. bool IsArguments(ParseNode *pnode)
  113. {
  114. for (;;)
  115. {
  116. switch (pnode->nop)
  117. {
  118. case knopName:
  119. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  120. case knopCall:
  121. case knopNew:
  122. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  123. {
  124. return true;
  125. }
  126. if (pnode->AsParseNodeCall()->pnodeArgs)
  127. {
  128. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  129. while (pnodeArg->nop == knopList)
  130. {
  131. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  132. return true;
  133. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  134. }
  135. pnode = pnodeArg;
  136. break;
  137. }
  138. return false;
  139. case knopArray:
  140. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  141. {
  142. return false;
  143. }
  144. pnode = pnode->AsParseNodeUni()->pnode1;
  145. break;
  146. case knopQmark:
  147. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  148. {
  149. return true;
  150. }
  151. pnode = pnode->AsParseNodeTri()->pnode3;
  152. break;
  153. //
  154. // Cases where we don't check for "arguments" yet.
  155. // Assume that they might have it. Disable the optimization is such scenarios
  156. //
  157. case knopList:
  158. case knopObject:
  159. case knopVarDecl:
  160. case knopConstDecl:
  161. case knopLetDecl:
  162. case knopFncDecl:
  163. case knopClassDecl:
  164. case knopFor:
  165. case knopIf:
  166. case knopDoWhile:
  167. case knopWhile:
  168. case knopForIn:
  169. case knopForOf:
  170. case knopReturn:
  171. case knopBlock:
  172. case knopBreak:
  173. case knopContinue:
  174. case knopTypeof:
  175. case knopThrow:
  176. case knopWith:
  177. case knopFinally:
  178. case knopTry:
  179. case knopTryCatch:
  180. case knopTryFinally:
  181. case knopArrayPattern:
  182. case knopObjectPattern:
  183. case knopParamPattern:
  184. return true;
  185. default:
  186. {
  187. uint flags = ParseNode::Grfnop(pnode->nop);
  188. if (flags&fnopUni)
  189. {
  190. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  191. Assert(pnodeUni->pnode1);
  192. pnode = pnodeUni->pnode1;
  193. break;
  194. }
  195. else if (flags&fnopBin)
  196. {
  197. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  198. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  199. if (IsArguments(pnodeBin->pnode1))
  200. {
  201. return true;
  202. }
  203. pnode = pnodeBin->pnode2;
  204. break;
  205. }
  206. return false;
  207. }
  208. }
  209. }
  210. }
  211. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  212. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
  213. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  214. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  215. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  216. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  217. static const Js::OpCode nopToOp[knopLim] =
  218. {
  219. #define OP(x) Br##x##_A
  220. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  221. #include "ptlist.h"
  222. };
  223. static const Js::OpCode nopToCMOp[knopLim] =
  224. {
  225. #define OP(x) Cm##x##_A
  226. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  227. #include "ptlist.h"
  228. };
  229. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  230. {
  231. switch (op)
  232. {
  233. case Js::OpCode::StLocalSlot:
  234. return Js::OpCode::StLocalSlotChkUndecl;
  235. case Js::OpCode::StParamSlot:
  236. return Js::OpCode::StParamSlotChkUndecl;
  237. case Js::OpCode::StInnerSlot:
  238. return Js::OpCode::StInnerSlotChkUndecl;
  239. case Js::OpCode::StEnvSlot:
  240. return Js::OpCode::StEnvSlotChkUndecl;
  241. case Js::OpCode::StObjSlot:
  242. return Js::OpCode::StObjSlotChkUndecl;
  243. case Js::OpCode::StLocalObjSlot:
  244. return Js::OpCode::StLocalObjSlotChkUndecl;
  245. case Js::OpCode::StParamObjSlot:
  246. return Js::OpCode::StParamObjSlotChkUndecl;
  247. case Js::OpCode::StInnerObjSlot:
  248. return Js::OpCode::StInnerObjSlotChkUndecl;
  249. case Js::OpCode::StEnvObjSlot:
  250. return Js::OpCode::StEnvObjSlotChkUndecl;
  251. default:
  252. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  253. return Js::OpCode::InvalidOpCode;
  254. }
  255. }
  256. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  257. // debuggerScope - The scope to add the variable to.
  258. // symbol - The symbol that represents the register property.
  259. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  260. // flags - The flags to assign to the property.
  261. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  262. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  263. Js::DebuggerScope *debuggerScope,
  264. Symbol *symbol,
  265. FuncInfo *funcInfo,
  266. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  267. bool isFunctionDeclaration /*= false*/)
  268. {
  269. Assert(debuggerScope);
  270. Assert(symbol);
  271. Assert(funcInfo);
  272. Js::RegSlot location = symbol->GetLocation();
  273. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  274. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  275. {
  276. // We have to get the appropriate scope and add property over there.
  277. // Make sure the scope is created whether we're in debug mode or not, because we
  278. // need the empty scopes present during reparsing for debug mode.
  279. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  280. }
  281. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  282. {
  283. // Only track the property if we're in debug mode since it's only needed by the debugger.
  284. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  285. this->Writer()->AddPropertyToDebuggerScope(
  286. correctDebuggerScope,
  287. location,
  288. propertyId,
  289. /*shouldConsumeRegister*/ true,
  290. flags,
  291. isFunctionDeclaration);
  292. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  293. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  294. symbol->SetIsTrackedForDebugger(true);
  295. }
  296. }
  297. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  298. Js::DebuggerScope *debuggerScope,
  299. Symbol *symbol,
  300. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  301. bool isFunctionDeclaration /*= false*/)
  302. {
  303. Assert(debuggerScope);
  304. Assert(symbol);
  305. // Only need to track activation object properties in debug mode.
  306. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  307. {
  308. Js::RegSlot location = symbol->GetLocation();
  309. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  310. this->Writer()->AddPropertyToDebuggerScope(
  311. debuggerScope,
  312. location,
  313. propertyId,
  314. /*shouldConsumeRegister*/ false,
  315. flags,
  316. isFunctionDeclaration);
  317. symbol->SetIsTrackedForDebugger(true);
  318. }
  319. }
  320. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  321. Js::DebuggerScope *debuggerScope,
  322. Symbol* symbol,
  323. Js::PropertyId propertyId,
  324. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  325. bool isFunctionDeclaration /*= false*/)
  326. {
  327. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  328. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  329. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  330. Assert(debuggerScope);
  331. Assert(symbol);
  332. if (!symbol->GetIsTrackedForDebugger())
  333. {
  334. Js::RegSlot location = symbol->GetScopeSlot();
  335. Assert(location != Js::Constants::NoRegister);
  336. Assert(propertyId != Js::Constants::NoProperty);
  337. this->Writer()->AddPropertyToDebuggerScope(
  338. debuggerScope,
  339. location,
  340. propertyId,
  341. /*shouldConsumeRegister*/ false,
  342. flags,
  343. isFunctionDeclaration);
  344. symbol->SetIsTrackedForDebugger(true);
  345. }
  346. }
  347. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  348. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  349. {
  350. Assert(functionDeclarationSymbol);
  351. Assert(funcInfoParent);
  352. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  353. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  354. // which is done in other Track* functions that we call.
  355. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  356. {
  357. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  358. {
  359. this->TrackActivationObjectPropertyForDebugger(
  360. this->Writer()->GetCurrentDebuggerScope(),
  361. functionDeclarationSymbol,
  362. Js::DebuggerScopePropertyFlags_None,
  363. true /*isFunctionDeclaration*/);
  364. }
  365. else
  366. {
  367. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  368. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  369. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  370. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  371. functionDeclarationSymbol->EnsurePosition(this);
  372. this->TrackSlotArrayPropertyForDebugger(
  373. this->Writer()->GetCurrentDebuggerScope(),
  374. functionDeclarationSymbol,
  375. functionDeclarationSymbol->GetPosition(),
  376. Js::DebuggerScopePropertyFlags_None,
  377. true /*isFunctionDeclaration*/);
  378. }
  379. }
  380. else
  381. {
  382. this->TrackRegisterPropertyForDebugger(
  383. this->Writer()->GetCurrentDebuggerScope(),
  384. functionDeclarationSymbol,
  385. funcInfoParent,
  386. Js::DebuggerScopePropertyFlags_None,
  387. true /*isFunctionDeclaration*/);
  388. }
  389. }
  390. // Updates the byte code offset of the property with the passed in location and ID.
  391. // Used to track let/const variables that are in the dead zone debugger side.
  392. // location - The activation object, scope slot index, or register location for the property.
  393. // propertyId - The ID of the property to update.
  394. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  395. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  396. {
  397. Assert(this->Writer());
  398. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  399. Assert(currentDebuggerScope);
  400. if (currentDebuggerScope != nullptr)
  401. {
  402. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  403. currentDebuggerScope,
  404. location,
  405. propertyId,
  406. shouldConsumeRegister);
  407. }
  408. }
  409. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  410. {
  411. if (funcInfo->GetHasCachedScope())
  412. {
  413. this->LoadCachedHeapArguments(funcInfo);
  414. }
  415. else
  416. {
  417. this->LoadUncachedHeapArguments(funcInfo);
  418. }
  419. }
  420. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  421. {
  422. Assert(funcInfo);
  423. Assert(propIds);
  424. Assert(byteCodeGenerator);
  425. bool hadDuplicates = false;
  426. Js::ArgSlot i = 0;
  427. auto processArg = [&](ParseNode *pnode)
  428. {
  429. if (pnode->IsVarLetOrConst())
  430. {
  431. Assert(i < propIds->count);
  432. Symbol *sym = pnode->AsParseNodeVar()->sym;
  433. Assert(sym);
  434. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  435. //
  436. // Check if the function has any same name parameters
  437. // For the same name param, only the last one will be passed the correct propertyid
  438. // For remaining dup param names, pass Constants::NoProperty
  439. //
  440. for (Js::ArgSlot j = 0; j < i; j++)
  441. {
  442. if (propIds->elements[j] == symPos)
  443. {
  444. // Found a dup parameter name
  445. propIds->elements[j] = Js::Constants::NoProperty;
  446. hadDuplicates = true;
  447. break;
  448. }
  449. }
  450. propIds->elements[i] = symPos;
  451. }
  452. else
  453. {
  454. propIds->elements[i] = Js::Constants::NoProperty;
  455. }
  456. ++i;
  457. };
  458. MapFormals(funcInfo->root, processArg);
  459. propIds->hadDuplicates = hadDuplicates;
  460. }
  461. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  462. {
  463. Assert(funcInfo->GetHasHeapArguments());
  464. Scope *scope = funcInfo->GetBodyScope();
  465. Assert(scope);
  466. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  467. Assert(argSym && argSym->IsArguments());
  468. Js::RegSlot argumentsLoc = argSym->GetLocation();
  469. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  470. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  471. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  472. if (count == 0)
  473. {
  474. // If no formals to function (only "this"), then no need to create the scope object.
  475. // Leave both the arguments location and the propertyIds location as null.
  476. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  477. }
  478. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  479. {
  480. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  481. }
  482. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  483. {
  484. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  485. // at the expected location.
  486. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  487. GetFormalArgsArray(this, funcInfo, propIds);
  488. }
  489. this->m_writer.Reg1(opcode, argumentsLoc);
  490. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  491. }
  492. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  493. {
  494. Assert(funcInfo->GetHasHeapArguments());
  495. Scope *scope = funcInfo->GetBodyScope();
  496. Assert(scope);
  497. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  498. Assert(argSym && argSym->IsArguments());
  499. Js::RegSlot argumentsLoc = argSym->GetLocation();
  500. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  501. this->m_writer.Reg1(op, argumentsLoc);
  502. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  503. }
  504. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  505. {
  506. Assert(stringNodeList);
  507. uint index = 0;
  508. Js::Var str;
  509. IdentPtr pid;
  510. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  511. while (stringNodeList->nop == knopList)
  512. {
  513. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  514. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  515. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  516. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  517. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  518. index++;
  519. }
  520. Assert(stringNodeList->nop == knopStr);
  521. pid = stringNodeList->AsParseNodeStr()->pid;
  522. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  523. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  524. return pArr;
  525. }
  526. // For now, this just assigns field ids for the current script.
  527. // Later, we will combine this information with the global field id map.
  528. // This temporary code will not work if a global member is accessed both with and without a LHS.
  529. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  530. {
  531. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  532. {
  533. this->AssignPropertyId(sym, functionInfo);
  534. });
  535. }
  536. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  537. {
  538. Assert(pnodeBlock->nop == knopBlock);
  539. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  540. {
  541. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  542. // the debugger scope will not be created.
  543. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  544. FuncInfo *funcInfo = this->TopFuncInfo();
  545. Symbol *sym = pnode->AsParseNodeVar()->sym;
  546. Scope *scope = sym->GetScope();
  547. if (sym->GetIsGlobal())
  548. {
  549. Js::PropertyId propertyId = sym->EnsurePosition(this);
  550. if (this->flags & fscrEval)
  551. {
  552. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  553. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  554. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  555. }
  556. else
  557. {
  558. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  559. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  560. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  561. }
  562. }
  563. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  564. {
  565. if (scope->GetIsObject())
  566. {
  567. Js::RegSlot scopeLocation = scope->GetLocation();
  568. Js::PropertyId propertyId = sym->EnsurePosition(this);
  569. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  570. {
  571. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  572. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  573. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  574. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  575. }
  576. else
  577. {
  578. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  579. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  580. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  581. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  582. }
  583. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  584. }
  585. else
  586. {
  587. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  588. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  589. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  590. funcInfo->ReleaseTmpRegister(tmpReg);
  591. // Slot array properties are tracked in non-debug mode as well because they need to stay
  592. // around for heap enumeration and escaping during attach/detach.
  593. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  594. }
  595. }
  596. else if (!sym->GetIsModuleExportStorage())
  597. {
  598. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  599. {
  600. // let/const declared in a switch is the only case of a variable that must be checked for
  601. // use-before-declaration dynamically within its own function.
  602. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  603. }
  604. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  605. // will live only in slots, so tell the debugger to find them there.
  606. if (sym->NeedsSlotAlloc(this, funcInfo))
  607. {
  608. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  609. }
  610. else
  611. {
  612. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  613. }
  614. }
  615. };
  616. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  617. }
  618. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  619. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  620. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  621. {
  622. Assert(pnode);
  623. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  624. {
  625. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  626. // don't add a block to the chain if it has no let/const variables at all.
  627. return nullptr;
  628. }
  629. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  630. }
  631. // Records the end of the current scope, but only if the current block has block scoped content.
  632. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  633. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  634. {
  635. Assert(pnodeBlock);
  636. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  637. {
  638. return;
  639. }
  640. this->Writer()->RecordEndScopeObject();
  641. }
  642. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  643. {
  644. Js::DebuggerScope* debuggerScope = nullptr;
  645. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  646. {
  647. Scope *scope = pnodeBlock->scope;
  648. byteCodeGenerator->PushScope(scope);
  649. Js::RegSlot scopeLocation = scope->GetLocation();
  650. if (scope->GetMustInstantiate())
  651. {
  652. Assert(scopeLocation == Js::Constants::NoRegister);
  653. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  654. if (scope->GetIsObject())
  655. {
  656. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  657. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  658. }
  659. else
  660. {
  661. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  662. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  663. // TODO: Handle heap enumeration
  664. int scopeSlotCount = scope->GetScopeSlotCount();
  665. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  666. }
  667. }
  668. else
  669. {
  670. // In the direct register access case, there is no block scope emitted but we can still track
  671. // the start and end offset of the block. The location registers for let/const variables will still be
  672. // captured along with this range in InitBlockScopedContent().
  673. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  674. }
  675. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  676. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  677. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  678. ParseNodePtr pnodeScope;
  679. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  680. {
  681. switch (pnodeScope->nop)
  682. {
  683. case knopFncDecl:
  684. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  685. {
  686. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  687. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  688. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  689. // So we'll supply a temp that we allocate and release here.
  690. if (frameDisplayLoc == Js::Constants::NoRegister)
  691. {
  692. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  693. {
  694. frameDisplayLoc = funcInfo->frameDisplayRegister;
  695. }
  696. else
  697. {
  698. frameDisplayLoc = funcInfo->GetEnvRegister();
  699. }
  700. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  701. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  702. }
  703. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  704. }
  705. // If this is the global eval block scope, the function is actually assigned to the global
  706. // so we don't need to keep the registers.
  707. if (isGlobalEvalBlockScope)
  708. {
  709. funcInfo->ReleaseLoc(pnodeScope);
  710. pnodeScope->location = Js::Constants::NoRegister;
  711. }
  712. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  713. break;
  714. case knopBlock:
  715. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  716. break;
  717. case knopCatch:
  718. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  719. break;
  720. case knopWith:
  721. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  722. break;
  723. }
  724. }
  725. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  726. {
  727. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  728. }
  729. }
  730. else
  731. {
  732. Scope *scope = pnodeBlock->scope;
  733. if (scope)
  734. {
  735. if (scope->GetMustInstantiate())
  736. {
  737. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  738. }
  739. else
  740. {
  741. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  742. }
  743. }
  744. else
  745. {
  746. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  747. }
  748. }
  749. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  750. }
  751. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  752. {
  753. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  754. {
  755. Scope *scope = pnodeBlock->scope;
  756. Assert(scope);
  757. Assert(scope == byteCodeGenerator->GetCurrentScope());
  758. byteCodeGenerator->PopScope();
  759. }
  760. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  761. }
  762. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  763. {
  764. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  765. {
  766. // Only let variables have observable behavior when there are per iteration
  767. // bindings. const variables do not since they are immutable. Therefore,
  768. // (and the spec agrees), only create new scope clones if the loop variable
  769. // is a let declaration.
  770. bool isConst = false;
  771. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  772. // Exploit the fact that a for loop sxBlock can only have let and const
  773. // declarations, and can only have one or the other, regardless of how
  774. // many syms there might be. Thus only check the first sym.
  775. isConst = sym->GetDecl()->nop == knopConstDecl;
  776. return true;
  777. });
  778. if (!isConst)
  779. {
  780. Scope *scope = pnodeBlock->scope;
  781. Assert(scope == byteCodeGenerator->GetCurrentScope());
  782. if (scope->GetMustInstantiate())
  783. {
  784. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  785. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  786. }
  787. }
  788. }
  789. }
  790. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  791. {
  792. Assert(pnodeBlock->nop == knopBlock);
  793. ParseNode *pnode = pnodeBlock->pnodeStmt;
  794. if (pnode == nullptr)
  795. {
  796. return;
  797. }
  798. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  799. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  800. while (pnode->nop == knopList)
  801. {
  802. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  803. if (stmt == pnodeLastValStmt)
  804. {
  805. // This is the last guaranteed return value, so any potential return values have to be
  806. // copied to the return register from this point forward.
  807. pnodeLastValStmt = nullptr;
  808. }
  809. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  810. pnode = pnode->AsParseNodeBin()->pnode2;
  811. }
  812. if (pnode == pnodeLastValStmt)
  813. {
  814. pnodeLastValStmt = nullptr;
  815. }
  816. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  817. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  818. }
  819. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  820. {
  821. if (emitFunc->IsTmpReg(pnode->location))
  822. {
  823. pnode->location = Js::Constants::NoRegister;
  824. }
  825. }
  826. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  827. {
  828. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  829. {
  830. // Function declarations (not function-declaration RHS's) are already fully processed.
  831. // Skip them here so the temp registers don't get messed up.
  832. return;
  833. }
  834. if (stmt->nop == knopName || stmt->nop == knopDot)
  835. {
  836. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  837. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  838. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  839. StartStatement(stmt);
  840. Writer()->Empty(Js::OpCode::Nop);
  841. EndStatement(stmt);
  842. }
  843. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
  844. if (funcInfo->IsTmpReg(stmt->location))
  845. {
  846. if (!stmt->isUsed && !fReturnValue)
  847. {
  848. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  849. }
  850. funcInfo->ReleaseLoc(stmt);
  851. }
  852. }
  853. // ByteCodeGenerator::DefineFunctions
  854. //
  855. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  856. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  857. // to make sure that sources of the stores have been defined.
  858. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  859. {
  860. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  861. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  862. if (funcInfoParent->GetHasCachedScope())
  863. {
  864. this->DefineCachedFunctions(funcInfoParent);
  865. }
  866. else
  867. {
  868. this->DefineUncachedFunctions(funcInfoParent);
  869. }
  870. }
  871. // Iterate over all child functions in a function's parameter and body scopes.
  872. template<typename Fn>
  873. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  874. {
  875. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  876. {
  877. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  878. {
  879. switch (pnode->nop)
  880. {
  881. case knopFncDecl:
  882. fn(pnode);
  883. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  884. break;
  885. case knopBlock:
  886. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  887. break;
  888. case knopCatch:
  889. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  890. break;
  891. case knopWith:
  892. pnode = pnode->AsParseNodeWith()->pnodeNext;
  893. break;
  894. default:
  895. AssertMsg(false, "Unexpected opcode in tree of scopes");
  896. return;
  897. }
  898. }
  899. };
  900. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  901. }
  902. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  903. {
  904. ParseNode *pnodeParent = funcInfoParent->root;
  905. uint slotCount = 0;
  906. auto countFncSlots = [&](ParseNode *pnodeFnc)
  907. {
  908. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  909. {
  910. slotCount++;
  911. }
  912. };
  913. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  914. if (slotCount == 0)
  915. {
  916. return;
  917. }
  918. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  919. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  920. if (extraBytesActual > INT_MAX)
  921. {
  922. Js::Throw::OutOfMemory();
  923. }
  924. int extraBytes = (int)extraBytesActual;
  925. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  926. // slotCount is guaranteed to be non-zero here.
  927. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  928. slotCount = 0;
  929. auto fillEntries = [&](ParseNode *pnodeFnc)
  930. {
  931. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  932. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration()))
  933. {
  934. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  935. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  936. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  937. entry->scopeSlot = sym->GetScopeSlot();
  938. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  939. slotCount++;
  940. }
  941. };
  942. MapContainerScopeFunctions(pnodeParent, fillEntries);
  943. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  944. info,
  945. sizeof(Js::FuncInfoArray) + extraBytes,
  946. sizeof(Js::FuncInfoArray) + extraBytes);
  947. slotCount = 0;
  948. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  949. {
  950. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  951. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  952. {
  953. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  954. // Only happens if the sym is null (e.g., function x.y(){}).
  955. if (sym == nullptr)
  956. {
  957. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  958. }
  959. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  960. {
  961. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  962. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  963. }
  964. // The "x = function() {...}" case is being generated on the fly, during emission,
  965. // so the caller expects to be able to release this register.
  966. funcInfoParent->ReleaseLoc(pnodeFnc);
  967. pnodeFnc->location = Js::Constants::NoRegister;
  968. slotCount++;
  969. }
  970. };
  971. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  972. AdeletePlus(alloc, extraBytes, info);
  973. }
  974. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  975. {
  976. ParseNode *pnodeParent = funcInfoParent->root;
  977. auto defineCheck = [&](ParseNode *pnodeFnc)
  978. {
  979. Assert(pnodeFnc->nop == knopFncDecl);
  980. //
  981. // Don't define the function upfront in following cases
  982. // 1. x = function() {...};
  983. // Don't define the function for all modes.
  984. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  985. // rather than the scope entry to save a register (and possibly save the whole definition).
  986. //
  987. // 2. x = function f() {...};
  988. // f is not visible in the enclosing scope.
  989. // Such function expressions should be emitted only at the assignment point, as can be used only
  990. // after the assignment. Might save register.
  991. //
  992. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  993. {
  994. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  995. // The "x = function() {...}" case is being generated on the fly, during emission,
  996. // so the caller expects to be able to release this register.
  997. funcInfoParent->ReleaseLoc(pnodeFnc);
  998. pnodeFnc->location = Js::Constants::NoRegister;
  999. }
  1000. };
  1001. MapContainerScopeFunctions(pnodeParent, defineCheck);
  1002. }
  1003. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  1004. {
  1005. // Assign the location holding the func object reference to the given name.
  1006. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  1007. Symbol *sym = pnodeFnc->pnodeName->sym;
  1008. if (sym != nullptr && !sym->GetIsFuncExpr())
  1009. {
  1010. if (sym->GetIsModuleExportStorage())
  1011. {
  1012. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1013. }
  1014. else if (sym->GetIsGlobal())
  1015. {
  1016. Js::PropertyId propertyId = sym->GetPosition();
  1017. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1018. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1019. {
  1020. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1026. {
  1027. if (!sym->GetHasNonCommittedReference() ||
  1028. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1029. {
  1030. // No point in trying to optimize if there are no references before we have to commit to slot.
  1031. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1032. sym->SetIsCommittedToSlot();
  1033. }
  1034. }
  1035. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1036. {
  1037. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1038. }
  1039. else
  1040. {
  1041. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1042. }
  1043. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1044. if (fncScopeSym)
  1045. {
  1046. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1047. {
  1048. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1049. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1050. }
  1051. else
  1052. {
  1053. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1054. }
  1055. }
  1056. }
  1057. }
  1058. }
  1059. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1060. {
  1061. Assert(pnodeFnc->nop == knopFncDecl);
  1062. funcInfoParent->AcquireLoc(pnodeFnc);
  1063. if (regEnv == Js::Constants::NoRegister)
  1064. {
  1065. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1066. if (frameDisplayTemp != Js::Constants::NoRegister)
  1067. {
  1068. // We allocated a temp to hold a local frame display value. Use that.
  1069. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1070. regEnv = frameDisplayTemp;
  1071. }
  1072. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1073. {
  1074. // This function has built a frame display, so pass it down.
  1075. regEnv = funcInfoParent->frameDisplayRegister;
  1076. }
  1077. else
  1078. {
  1079. // This function has no captured locals but inherits a closure environment, so pass it down.
  1080. regEnv = funcInfoParent->GetEnvRegister();
  1081. }
  1082. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1083. }
  1084. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1085. // "We need a closure for the nested function");
  1086. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1087. // If we are in a parameter scope and it is not merged with body scope then we have to create the child function as an inner function
  1088. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1089. {
  1090. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1091. }
  1092. else
  1093. {
  1094. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1095. }
  1096. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1097. {
  1098. // A function declared at global scope in eval is untrackable,
  1099. // so make sure the caller's cached scope is invalidated.
  1100. this->funcEscapes = true;
  1101. }
  1102. else
  1103. {
  1104. if (pnodeFnc->IsDeclaration())
  1105. {
  1106. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1107. if (funcSymbol)
  1108. {
  1109. // In the case where a let/const declaration is the same symbol name
  1110. // as the function declaration (shadowing case), the let/const var and
  1111. // the function declaration symbol are the same and share the same flags
  1112. // (particularly, sym->GetIsBlockVar() for this code path).
  1113. //
  1114. // For example:
  1115. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1116. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1117. //
  1118. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1119. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1120. //
  1121. // In order to tell if the function is actually part
  1122. // of a block scope, we compare against the function scope here.
  1123. // Note that having a function with the same name as a let/const declaration
  1124. // is a redeclaration error, but we're pushing the fix for this out since it's
  1125. // a bit involved.
  1126. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1127. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1128. // Track all vars/lets/consts register slot function declarations.
  1129. if (ShouldTrackDebuggerMetadata()
  1130. // If this is a let binding function declaration at global level, we want to
  1131. // be sure to track the register location as well.
  1132. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1133. {
  1134. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1135. {
  1136. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1137. }
  1138. }
  1139. if (isFunctionDeclarationInBlock)
  1140. {
  1141. // We only track inner let bindings for the debugger side.
  1142. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. if (pnodeFnc->IsDefaultModuleExport())
  1148. {
  1149. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1150. }
  1151. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1152. {
  1153. return regEnv;
  1154. }
  1155. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1156. return regEnv;
  1157. }
  1158. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1159. {
  1160. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1161. // by an existing initialization.
  1162. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1163. ParseNode *pnode;
  1164. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1165. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1166. // Just assign one on the fly and re-use it for all initializations.
  1167. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1168. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1169. {
  1170. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1171. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1172. {
  1173. if (sym->IsSpecialSymbol())
  1174. {
  1175. // Special symbols have already had their initial values stored into their registers.
  1176. // In default-argument case we've stored those values into their slot locations, as well.
  1177. // We must do that because a default parameter may access a special symbol through a scope slot.
  1178. // In the non-default-argument case, though, we didn't yet store the values into the
  1179. // slots so let's do that now.
  1180. if (!funcInfo->root->HasNonSimpleParameterList())
  1181. {
  1182. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1183. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1184. {
  1185. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1186. }
  1187. }
  1188. continue;
  1189. }
  1190. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1191. {
  1192. // The init node was bound to the catch object, because it's inside a catch and has the
  1193. // same name as the catch object. But we want to define a user var at function scope,
  1194. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1195. // This also applies to a var declaration in the same scope as a let declaration.
  1196. #if DBG
  1197. if (sym->IsArguments())
  1198. {
  1199. // There is a block scoped var named arguments
  1200. Assert(!funcInfo->GetHasArguments());
  1201. continue;
  1202. }
  1203. else if (!sym->GetIsCatch())
  1204. {
  1205. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1206. Assert(funcInfo->bodyScope != sym->GetScope());
  1207. }
  1208. #endif
  1209. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1210. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1211. }
  1212. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1213. {
  1214. if (fGlobal)
  1215. {
  1216. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1217. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1218. // But we first need to make sure we're not trashing built-ins.
  1219. if (this->flags & fscrEval)
  1220. {
  1221. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1222. {
  1223. // Check/Init the property of the frame object
  1224. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1225. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1226. }
  1227. else
  1228. {
  1229. // The check and the init involve the first element in the scope chain.
  1230. this->m_writer.ElementScopedU(
  1231. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1232. }
  1233. }
  1234. else
  1235. {
  1236. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1237. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1238. }
  1239. }
  1240. else if (!sym->IsArguments())
  1241. {
  1242. if (sym->NeedsSlotAlloc(this, funcInfo))
  1243. {
  1244. if (!sym->GetHasNonCommittedReference() ||
  1245. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1246. {
  1247. // No point in trying to optimize if there are no references before we have to commit to slot.
  1248. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1249. sym->SetIsCommittedToSlot();
  1250. }
  1251. }
  1252. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1253. // is delayed) or a property of an object.
  1254. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1255. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1256. {
  1257. Js::RegSlot reg = sym->GetLocation();
  1258. if (reg == Js::Constants::NoRegister)
  1259. {
  1260. Assert(sym->IsInSlot(this, funcInfo));
  1261. reg = funcInfo->AcquireTmpRegister();
  1262. }
  1263. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1264. this->EmitLocalPropInit(reg, sym, funcInfo);
  1265. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1266. {
  1267. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1268. }
  1269. funcInfo->ReleaseTmpRegister(reg);
  1270. }
  1271. }
  1272. else if (ShouldTrackDebuggerMetadata())
  1273. {
  1274. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1275. {
  1276. Js::RegSlot reg = sym->GetLocation();
  1277. if (reg != Js::Constants::NoRegister)
  1278. {
  1279. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1280. }
  1281. }
  1282. }
  1283. sym->SetHasInit(TRUE);
  1284. }
  1285. }
  1286. }
  1287. if (tmpReg != Js::Constants::NoRegister)
  1288. {
  1289. funcInfo->ReleaseTmpRegister(tmpReg);
  1290. }
  1291. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1292. {
  1293. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1294. }
  1295. }
  1296. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1297. {
  1298. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1299. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1300. // This protects us from, for instance, trying to restore garbage on bailout.
  1301. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1302. // garbage on exit from jitted loop bodies.
  1303. while (pnode)
  1304. {
  1305. switch (pnode->nop)
  1306. {
  1307. case knopFncDecl:
  1308. {
  1309. // If this is a block-scoped function, initialize it.
  1310. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1311. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1312. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1313. {
  1314. Symbol *sym = pnodeName->sym;
  1315. Assert(sym);
  1316. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1317. sym->GetScope()->IsBlockScope(funcInfo) &&
  1318. sym->GetScope()->GetFunc() == funcInfo)
  1319. {
  1320. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1321. }
  1322. }
  1323. // No need to recurse to the nested scopes, as they belong to a nested function.
  1324. pnode = pnodeFnc->pnodeNext;
  1325. break;
  1326. }
  1327. case knopBlock:
  1328. {
  1329. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1330. Scope *scope = pnodeBlock->scope;
  1331. if (scope)
  1332. {
  1333. if (scope->IsBlockScope(funcInfo))
  1334. {
  1335. Js::RegSlot scopeLoc = scope->GetLocation();
  1336. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1337. {
  1338. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1339. }
  1340. }
  1341. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1342. {
  1343. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1344. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1345. {
  1346. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1347. }
  1348. };
  1349. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1350. }
  1351. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1352. pnode = pnodeBlock->pnodeNext;
  1353. break;
  1354. }
  1355. case knopCatch:
  1356. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1357. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1358. break;
  1359. case knopWith:
  1360. {
  1361. Js::RegSlot withLoc = pnode->location;
  1362. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1363. "We should put with objects at known stack locations in debug mode");
  1364. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1365. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1366. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1367. break;
  1368. }
  1369. default:
  1370. Assert(false);
  1371. return;
  1372. }
  1373. }
  1374. }
  1375. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1376. {
  1377. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1378. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1379. {
  1380. return;
  1381. }
  1382. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1383. uint slotCount = currentScope->GetScopeSlotCount();
  1384. uint cachedFuncCount = 0;
  1385. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1386. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1387. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1388. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1389. // Create and fill the array of local property ID's.
  1390. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1391. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1392. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1393. ParseNode *pnode;
  1394. Symbol *sym;
  1395. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1396. {
  1397. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1398. }
  1399. if (funcInfo->GetHasArguments())
  1400. {
  1401. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1402. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1403. Js::PropertyId slot = 0;
  1404. auto initArg = [&](ParseNode *pnode)
  1405. {
  1406. if (pnode->IsVarLetOrConst())
  1407. {
  1408. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1409. Assert(sym);
  1410. if (sym->GetScopeSlot() == slot)
  1411. {
  1412. // This is the last appearance of the formal, so record the ID.
  1413. Symbol::SaveToPropIdArray(sym, propIds, this);
  1414. }
  1415. else
  1416. {
  1417. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1418. // since this slot can't be accessed by name.
  1419. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1420. propIds->elements[slot] = Js::Constants::NoProperty;
  1421. }
  1422. }
  1423. else
  1424. {
  1425. // This is for patterns
  1426. propIds->elements[slot] = Js::Constants::NoProperty;
  1427. }
  1428. slot++;
  1429. };
  1430. MapFormalsWithoutRest(pnodeFnc, initArg);
  1431. // If the rest is in the slot - we need to keep that slot.
  1432. if (pnodeFnc->pnodeRest != nullptr && pnodeFnc->pnodeRest->sym->IsInSlot(this, funcInfo))
  1433. {
  1434. Symbol::SaveToPropIdArray(pnodeFnc->pnodeRest->sym, propIds, this);
  1435. }
  1436. }
  1437. else
  1438. {
  1439. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1440. {
  1441. if (pnode->IsVarLetOrConst())
  1442. {
  1443. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1444. }
  1445. });
  1446. }
  1447. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1448. {
  1449. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1450. {
  1451. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1452. if (pnodeName != nullptr)
  1453. {
  1454. while (pnodeName->nop == knopList)
  1455. {
  1456. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1457. {
  1458. sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1459. if (sym)
  1460. {
  1461. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1462. }
  1463. }
  1464. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1465. }
  1466. if (pnodeName->nop == knopVarDecl)
  1467. {
  1468. sym = pnodeName->AsParseNodeVar()->sym;
  1469. if (sym)
  1470. {
  1471. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1472. cachedFuncCount++;
  1473. }
  1474. }
  1475. }
  1476. }
  1477. };
  1478. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1479. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1480. {
  1481. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1482. {
  1483. sym = pnode->AsParseNodeVar()->sym;
  1484. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1485. {
  1486. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1487. {
  1488. sym = currentScope->FindLocalSymbol(sym->GetName());
  1489. }
  1490. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1491. }
  1492. }
  1493. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1494. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1495. {
  1496. sym = pnode->AsParseNodeVar()->sym;
  1497. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1498. }
  1499. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1500. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1501. {
  1502. sym = pnode->AsParseNodeVar()->sym;
  1503. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1504. }
  1505. }
  1506. else
  1507. {
  1508. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1509. }
  1510. // Write the first func slot and first var slot into the auxiliary data
  1511. Js::PropertyId *slots = propIds->elements + slotCount;
  1512. slots[0] = cachedFuncCount;
  1513. slots[1] = firstFuncSlot;
  1514. slots[2] = firstVarSlot;
  1515. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1516. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1517. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1518. }
  1519. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1520. {
  1521. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1522. {
  1523. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1524. }
  1525. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1526. {
  1527. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1528. byteCodeFunction->SetHasScopeObject(true);
  1529. }
  1530. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1531. {
  1532. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1533. }
  1534. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1535. {
  1536. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1537. }
  1538. }
  1539. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1540. {
  1541. if (byteCodeFunction->IsCoroutine())
  1542. {
  1543. // EmitYield uses 'false' to create the IteratorResult object
  1544. funcInfo->AssignFalseConstRegister();
  1545. }
  1546. if (funcInfo->NeedEnvRegister())
  1547. {
  1548. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1549. funcInfo->AssignEnvRegister(constReg);
  1550. }
  1551. // Set the function body's constant count before emitting anything so that the byte code writer
  1552. // can distinguish constants from variables.
  1553. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1554. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1555. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1556. {
  1557. // Give permanent registers to the inner scopes in debug mode.
  1558. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1559. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1560. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1561. // EmitOneFunction.
  1562. uint innerScopeCount = funcInfo->InnerScopeCount();
  1563. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1564. if (innerScopeCount)
  1565. {
  1566. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1567. for (uint i = 1; i < innerScopeCount; i++)
  1568. {
  1569. funcInfo->NextVarRegister();
  1570. }
  1571. }
  1572. }
  1573. // NOTE: The FB expects the yield reg to be the final non-temp.
  1574. if (byteCodeFunction->IsCoroutine())
  1575. {
  1576. funcInfo->AssignYieldRegister();
  1577. }
  1578. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1579. funcInfo->SetFirstTmpReg(firstTmpReg);
  1580. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1581. }
  1582. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1583. {
  1584. // Record slots info for ScopeSlots/ScopeObject.
  1585. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1586. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1587. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1588. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1589. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1590. {
  1591. return;
  1592. }
  1593. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1594. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1595. {
  1596. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1597. }
  1598. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1599. if (scopeSlotCount)
  1600. {
  1601. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1602. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1603. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1604. "The slot array size is different between debug and non-debug mode");
  1605. #if DEBUG
  1606. for (UINT i = 0; i < scopeSlotCount; i++)
  1607. {
  1608. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1609. }
  1610. #endif
  1611. auto setPropertyIdForScopeSlotArray =
  1612. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1613. (Js::PropertyId slot, Js::PropertyId propId)
  1614. {
  1615. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1616. {
  1617. Js::Throw::FatalInternalError();
  1618. }
  1619. propertyIdsForScopeSlotArray[slot] = propId;
  1620. };
  1621. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1622. {
  1623. if (sym->NeedsSlotAlloc(this, funcInfo))
  1624. {
  1625. // All properties should get correct propertyId here.
  1626. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1627. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1628. }
  1629. };
  1630. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1631. #if DEBUG
  1632. for (UINT i = 0; i < scopeSlotCount; i++)
  1633. {
  1634. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1635. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1636. }
  1637. #endif
  1638. }
  1639. }
  1640. // temporarily load all constants and special registers in a single block
  1641. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1642. {
  1643. Symbol *sym;
  1644. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1645. byteCodeFunction->CreateConstantTable();
  1646. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1647. {
  1648. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1649. }
  1650. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1651. {
  1652. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1653. }
  1654. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1655. {
  1656. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1657. }
  1658. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1659. {
  1660. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1661. }
  1662. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1663. {
  1664. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1665. if (!funcInfo->GetApplyEnclosesArgs())
  1666. {
  1667. this->EmitScopeObjectInit(funcInfo);
  1668. }
  1669. #if DBG
  1670. uint count = 0;
  1671. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1672. {
  1673. if (sym->NeedsSlotAlloc(this, funcInfo))
  1674. {
  1675. // All properties should get correct propertyId here.
  1676. count++;
  1677. }
  1678. });
  1679. if (funcInfo->GetParamScope() != nullptr)
  1680. {
  1681. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1682. {
  1683. if (sym->NeedsSlotAlloc(this, funcInfo))
  1684. {
  1685. // All properties should get correct propertyId here.
  1686. count++;
  1687. }
  1688. });
  1689. }
  1690. // A reparse should result in the same size of the activation object.
  1691. // Exclude functions which were created from the ByteCodeCache.
  1692. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1693. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1694. "The activation object size is different between debug and non-debug mode");
  1695. byteCodeFunction->scopeObjectSize = count;
  1696. #endif
  1697. }
  1698. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1699. {
  1700. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1701. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1702. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1703. {
  1704. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1705. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1706. }
  1707. }
  1708. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1709. {
  1710. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1711. byteCodeFunction->SetEnvDepth((uint16)-1);
  1712. }
  1713. bool thisLoadedFromParams = false;
  1714. if (funcInfo->NeedEnvRegister())
  1715. {
  1716. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1717. if (funcInfo->GetIsTopLevelEventHandler())
  1718. {
  1719. if (funcInfo->GetThisSymbol())
  1720. {
  1721. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1722. }
  1723. // The environment is the namespace hierarchy starting with "this".
  1724. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1725. thisLoadedFromParams = true;
  1726. this->InvalidateCachedOuterScopes(funcInfo);
  1727. }
  1728. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1729. {
  1730. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1731. if (funcInfo->GetIsStrictMode())
  1732. {
  1733. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1734. }
  1735. else
  1736. {
  1737. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1738. }
  1739. }
  1740. else
  1741. {
  1742. // environment may be required to load "this"
  1743. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1744. this->InvalidateCachedOuterScopes(funcInfo);
  1745. }
  1746. }
  1747. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1748. {
  1749. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1750. }
  1751. this->RecordAllIntConstants(funcInfo);
  1752. this->RecordAllStrConstants(funcInfo);
  1753. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1754. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1755. {
  1756. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1757. });
  1758. // WARNING !!!
  1759. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1760. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1761. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1762. if (funcInfo->GetHasArguments())
  1763. {
  1764. sym = funcInfo->GetArgumentsSymbol();
  1765. Assert(sym);
  1766. Assert(funcInfo->GetHasHeapArguments());
  1767. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1768. {
  1769. this->LoadHeapArguments(funcInfo);
  1770. }
  1771. }
  1772. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1773. {
  1774. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1775. if (count != 0)
  1776. {
  1777. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1778. GetFormalArgsArray(this, funcInfo, propIds);
  1779. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1780. }
  1781. }
  1782. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1783. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1784. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1785. if (funcInfo->IsClassConstructor())
  1786. {
  1787. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1788. }
  1789. // new.target may be used to construct the 'this' register so make sure to load it first
  1790. if (funcInfo->GetNewTargetSymbol())
  1791. {
  1792. this->LoadNewTargetObject(funcInfo);
  1793. }
  1794. if (funcInfo->GetThisSymbol())
  1795. {
  1796. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1797. }
  1798. else if (ShouldLoadConstThis(funcInfo))
  1799. {
  1800. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1801. }
  1802. if (funcInfo->GetSuperSymbol())
  1803. {
  1804. this->LoadSuperObject(funcInfo);
  1805. }
  1806. if (funcInfo->GetSuperConstructorSymbol())
  1807. {
  1808. this->LoadSuperConstructorObject(funcInfo);
  1809. }
  1810. //
  1811. // If the function is a function expression with a name,
  1812. // load the function object at runtime to its activation object.
  1813. //
  1814. sym = funcInfo->root->GetFuncSymbol();
  1815. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1816. if (funcExprWithName)
  1817. {
  1818. if (funcInfo->GetFuncExprNameReference() ||
  1819. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1820. {
  1821. //
  1822. // x = function f(...) { ... }
  1823. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1824. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1825. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1826. // scope's register namespace. So use a tmp register.
  1827. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1828. // from it's register namespace, which LdFuncExpr can use.
  1829. //
  1830. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1831. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1832. if (sym->IsInSlot(this, funcInfo))
  1833. {
  1834. Js::RegSlot scopeLocation;
  1835. AnalysisAssert(funcInfo->funcExprScope);
  1836. if (funcInfo->funcExprScope->GetIsObject())
  1837. {
  1838. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1839. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1840. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1841. }
  1842. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1843. {
  1844. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1845. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1846. }
  1847. else
  1848. {
  1849. Assert(sym->HasScopeSlot());
  1850. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1851. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1852. }
  1853. }
  1854. else if (ShouldTrackDebuggerMetadata())
  1855. {
  1856. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1857. }
  1858. }
  1859. }
  1860. }
  1861. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1862. {
  1863. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1864. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1865. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1866. uint32 envIndex = 0;
  1867. while (scope && scope->GetFunc() == funcInfo)
  1868. {
  1869. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1870. scope = scope->GetEnclosingScope();
  1871. }
  1872. for (; scope; scope = scope->GetEnclosingScope())
  1873. {
  1874. FuncInfo *func = scope->GetFunc();
  1875. if (scope == func->GetBodyScope())
  1876. {
  1877. if (func->Escapes() && func->GetHasCachedScope())
  1878. {
  1879. AssertOrFailFast(scope->GetIsObject());
  1880. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1881. }
  1882. }
  1883. if (scope->GetMustInstantiate())
  1884. {
  1885. envIndex++;
  1886. }
  1887. }
  1888. }
  1889. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1890. {
  1891. Symbol* thisSym = funcInfo->GetThisSymbol();
  1892. Assert(thisSym);
  1893. Assert(!funcInfo->IsLambda());
  1894. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1895. {
  1896. // Derived class constructors initialize 'this' to be Undecl
  1897. // - we'll check this value during a super call and during 'this' access
  1898. //
  1899. // Base class constructors initialize 'this' to a new object using new.target
  1900. if (funcInfo->IsBaseClassConstructor())
  1901. {
  1902. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1903. Assert(newTargetSym);
  1904. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1905. }
  1906. else
  1907. {
  1908. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1909. }
  1910. }
  1911. else if (!funcInfo->IsGlobalFunction())
  1912. {
  1913. //
  1914. // thisLoadedFromParams would be true for the event Handler case,
  1915. // "this" would have been loaded from parameters to put in the environment
  1916. //
  1917. if (!thisLoadedFromParams)
  1918. {
  1919. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1920. m_writer.ArgIn0(tmpReg);
  1921. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1922. funcInfo->ReleaseTmpRegister(tmpReg);
  1923. }
  1924. else
  1925. {
  1926. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1927. }
  1928. }
  1929. else
  1930. {
  1931. Assert(funcInfo->IsGlobalFunction());
  1932. Js::RegSlot root = funcInfo->nullConstantRegister;
  1933. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1934. }
  1935. }
  1936. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1937. {
  1938. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1939. Assert(newTargetSym);
  1940. if (funcInfo->IsClassConstructor())
  1941. {
  1942. Assert(!funcInfo->IsLambda());
  1943. m_writer.ArgIn0(newTargetSym->GetLocation());
  1944. }
  1945. else if (funcInfo->IsGlobalFunction())
  1946. {
  1947. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1948. }
  1949. else
  1950. {
  1951. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1952. }
  1953. }
  1954. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1955. {
  1956. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1957. Assert(superConstructorSym);
  1958. Assert(!funcInfo->IsLambda());
  1959. if (funcInfo->IsDerivedClassConstructor())
  1960. {
  1961. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1962. }
  1963. else
  1964. {
  1965. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1966. }
  1967. }
  1968. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1969. {
  1970. Symbol* superSym = funcInfo->GetSuperSymbol();
  1971. Assert(superSym);
  1972. Assert(!funcInfo->IsLambda());
  1973. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1974. }
  1975. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue)
  1976. {
  1977. FuncInfo* nonLambdaFunc = funcInfo;
  1978. bool isResultUsed = pnodeSuperCall->isUsed;
  1979. if (funcInfo->IsLambda())
  1980. {
  1981. nonLambdaFunc = this->FindEnclosingNonLambda();
  1982. }
  1983. if (nonLambdaFunc->IsBaseClassConstructor())
  1984. {
  1985. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  1986. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  1987. return;
  1988. }
  1989. pnodeSuperCall->isUsed = true;
  1990. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  1991. // and the result of the super() expression itself
  1992. funcInfo->AcquireLoc(pnodeSuperCall);
  1993. // 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)
  1994. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  1995. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  1996. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  1997. Assert(pnodeSuperCall->isSuperCall);
  1998. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  1999. //
  2000. // if (super is class constructor) {
  2001. // _this = new.target;
  2002. // } else {
  2003. // _this = NewScObjFull(new.target);
  2004. // }
  2005. //
  2006. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2007. // if (temp is object) {
  2008. // _this = temp;
  2009. // }
  2010. //
  2011. // if (UndeclBlockVar === this) {
  2012. // this = _this;
  2013. // } else {
  2014. // throw ReferenceError;
  2015. // }
  2016. //
  2017. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2018. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2019. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2020. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2021. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2022. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2023. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2024. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2025. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2026. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2027. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2028. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2029. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2030. this->Writer()->MarkLabel(makeCallLabel);
  2031. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2032. // We have to use another temp for the this value before assigning to this register.
  2033. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2034. // Ex:
  2035. // _this = new.target;
  2036. // temp = super.call(_this);
  2037. // if (temp is object) {
  2038. // _this = temp; // creates a new sym for _this as it was previously used
  2039. // }
  2040. // this = _this; // tries to loads a value from the old sym (which is dead)
  2041. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2042. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2043. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2044. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2045. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnodeSuperCall->location);
  2046. this->Writer()->MarkLabel(doneLabel);
  2047. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2048. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2049. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2050. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2051. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2052. this->Writer()->MarkLabel(skipLabel);
  2053. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2054. if (isResultUsed)
  2055. {
  2056. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2057. }
  2058. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2059. this->Writer()->Reg2(Js::OpCode::StrictLdThis, pnodeSuperCall->pnodeThis->location, valueForThis);
  2060. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2061. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2062. funcInfo->ReleaseTmpRegister(valueForThis);
  2063. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2064. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2065. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2066. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2067. }
  2068. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2069. {
  2070. Symbol* thisSym = funcInfo->GetThisSymbol();
  2071. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2072. {
  2073. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2074. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2075. }
  2076. }
  2077. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2078. {
  2079. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2080. {
  2081. m_writer.Reg2(Js::OpCode::StrictLdThis, lhsLocation, fromRegister);
  2082. }
  2083. else
  2084. {
  2085. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2086. }
  2087. }
  2088. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2089. {
  2090. if (pnodeFormal->IsVarLetOrConst())
  2091. {
  2092. // Get the param from its argument position into its assigned register.
  2093. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2094. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2095. if (formal->GetLocation() + 1 == pos)
  2096. {
  2097. // Transfer to the frame object, etc., if necessary.
  2098. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2099. }
  2100. }
  2101. }
  2102. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2103. {
  2104. if (ShouldTrackDebuggerMetadata())
  2105. {
  2106. // Add formals to the debugger propertyidcontainer for reg slots
  2107. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2108. {
  2109. if (pnodeFormal->IsVarLetOrConst())
  2110. {
  2111. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2112. if (!formal->IsInSlot(this, funcInfo))
  2113. {
  2114. Assert(!formal->GetHasInit());
  2115. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2116. }
  2117. }
  2118. };
  2119. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2120. }
  2121. // Transfer formal parameters to their home locations on the local frame.
  2122. if (funcInfo->GetHasArguments())
  2123. {
  2124. if (funcInfo->root->pnodeRest != nullptr)
  2125. {
  2126. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2127. EmitLoadFormalIntoRegister(funcInfo->root->pnodeRest, funcInfo->root->pnodeRest->sym->GetLocation() + 1, funcInfo);
  2128. }
  2129. // The arguments object creation helper does this work for us.
  2130. return;
  2131. }
  2132. Js::ArgSlot pos = 1;
  2133. auto loadFormal = [&](ParseNode *pnodeFormal)
  2134. {
  2135. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2136. pos++;
  2137. };
  2138. MapFormals(funcInfo->root, loadFormal);
  2139. }
  2140. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2141. {
  2142. funcInfo->singleExit = m_writer.DefineLabel();
  2143. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2144. while (iter.Next())
  2145. {
  2146. ParseNodeStmt * node = iter.Data();
  2147. node->breakLabel = m_writer.DefineLabel();
  2148. node->continueLabel = m_writer.DefineLabel();
  2149. node->emitLabels = true;
  2150. }
  2151. }
  2152. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2153. {
  2154. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2155. // return value.
  2156. ParseNode *pnode = funcInfo->root->pnodeBody;
  2157. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2158. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2159. {
  2160. // We're not guaranteed to compute any values, so fix up the return register at the top
  2161. // in case.
  2162. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2163. }
  2164. while (pnode->nop == knopList)
  2165. {
  2166. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2167. if (stmt == pnodeLastVal)
  2168. {
  2169. pnodeLastVal = nullptr;
  2170. }
  2171. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2172. {
  2173. EmitTopLevelStatement(stmt, funcInfo, true);
  2174. }
  2175. else
  2176. {
  2177. // Haven't hit the post-dominating return value yet,
  2178. // so don't bother with the return register.
  2179. EmitTopLevelStatement(stmt, funcInfo, false);
  2180. }
  2181. pnode = pnode->AsParseNodeBin()->pnode2;
  2182. }
  2183. EmitTopLevelStatement(pnode, funcInfo, false);
  2184. }
  2185. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2186. {
  2187. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2188. // get copied to the return register.
  2189. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2190. ParseNode *pnode = pnodeBody;
  2191. while (pnode->nop == knopList)
  2192. {
  2193. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2194. if (stmt->CapturesSyms())
  2195. {
  2196. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2197. SList<Symbol*> *list = map->Item(stmt);
  2198. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2199. {
  2200. if (!sym->GetIsCommittedToSlot())
  2201. {
  2202. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2203. sym->SetIsCommittedToSlot();
  2204. ParseNode *decl = sym->GetDecl();
  2205. Assert(decl);
  2206. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2207. {
  2208. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2209. sym->GetName().GetBuffer());
  2210. Output::Flush();
  2211. }
  2212. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2213. // what is this doing? Why are we assigning sym to itself?
  2214. bool old = sym->GetNeedDeclaration();
  2215. sym->SetNeedDeclaration(false);
  2216. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2217. sym->SetNeedDeclaration(old);
  2218. }
  2219. }
  2220. NEXT_SLIST_ENTRY;
  2221. }
  2222. EmitTopLevelStatement(stmt, funcInfo, false);
  2223. pnode = pnode->AsParseNodeBin()->pnode2;
  2224. }
  2225. Assert(!pnode->CapturesSyms());
  2226. EmitTopLevelStatement(pnode, funcInfo, false);
  2227. }
  2228. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2229. {
  2230. // Indicate that the binding phase is over.
  2231. this->isBinding = false;
  2232. this->trackEnvDepth = true;
  2233. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2234. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2235. // Use the temp allocator in bytecode write temp buffer.
  2236. m_writer.InitData(this->alloc, initSize);
  2237. #ifdef LOG_BYTECODE_AST_RATIO
  2238. // log the max Ast size
  2239. Output::Print(_u("Max Ast size: %d"), initSize);
  2240. #endif
  2241. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2242. if (this->parentScopeInfo)
  2243. {
  2244. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2245. // Start emitting with the nested scope (i.e., the deferred function).
  2246. this->EmitScopeList(pnodeProg->pnodeScopes);
  2247. }
  2248. else
  2249. {
  2250. this->EmitScopeList(pnodeProg);
  2251. }
  2252. }
  2253. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2254. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2255. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2256. {
  2257. Js::DebuggerScope *debuggerScope = nullptr;
  2258. auto processArg = [&](ParseNode *pnodeArg) {
  2259. if (pnodeArg->IsVarLetOrConst())
  2260. {
  2261. if (debuggerScope == nullptr)
  2262. {
  2263. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2264. debuggerScope->SetBegin(beginOffset);
  2265. }
  2266. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2267. }
  2268. };
  2269. MapFormals(pnodeFnc, processArg);
  2270. MapFormalsFromPattern(pnodeFnc, processArg);
  2271. if (debuggerScope != nullptr)
  2272. {
  2273. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2274. {
  2275. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2276. }
  2277. RecordEndScopeObject(pnodeFnc);
  2278. }
  2279. }
  2280. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2281. {
  2282. if (sym)
  2283. {
  2284. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2285. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2286. Js::RegSlot location = sym->GetLocation();
  2287. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2288. {
  2289. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2290. location = funcBody->MapRegSlot(location);
  2291. }
  2292. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2293. }
  2294. }
  2295. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2296. {
  2297. uint beginOffset = m_writer.GetCurrentOffset();
  2298. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2299. {
  2300. if (pnodeArg->nop == knopParamPattern)
  2301. {
  2302. this->StartStatement(pnodeArg);
  2303. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2304. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2305. if (pnode1->IsPattern())
  2306. {
  2307. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2308. }
  2309. else
  2310. {
  2311. Assert(pnode1->nop == knopAsg);
  2312. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2313. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2314. pnodeArg->AsParseNodeParamPattern()->location,
  2315. pnode1->AsParseNodeBin()->pnode2,
  2316. false /*isNonPatternAssignmentTarget*/,
  2317. this,
  2318. funcInfo);
  2319. }
  2320. this->EndStatement(pnodeArg);
  2321. return;
  2322. }
  2323. else if (pnodeArg->IsVarLetOrConst())
  2324. {
  2325. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2326. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2327. {
  2328. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2329. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2330. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2331. return;
  2332. }
  2333. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2334. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2335. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2336. this->StartStatement(pnodeArg);
  2337. // Let us use strict not equal to differentiate between null and undefined
  2338. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2339. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2340. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2341. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2342. {
  2343. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2344. m_writer.Br(endLabel);
  2345. }
  2346. else
  2347. {
  2348. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2349. }
  2350. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2351. m_writer.MarkLabel(noDefaultLabel);
  2352. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2353. {
  2354. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2355. m_writer.MarkLabel(endLabel);
  2356. }
  2357. this->EndStatement(pnodeArg);
  2358. }
  2359. };
  2360. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2361. if (pnodeFnc->IsAsync())
  2362. {
  2363. uint cacheId;
  2364. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2365. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2366. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2367. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2368. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2369. // try
  2370. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2371. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2372. // Rest cannot have a default argument, so we ignore it.
  2373. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2374. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2375. m_writer.Empty(Js::OpCode::Leave);
  2376. m_writer.Br(doneLabel);
  2377. // catch
  2378. m_writer.MarkLabel(catchLabel);
  2379. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2380. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2381. m_writer.Empty(Js::OpCode::Nop);
  2382. // return Promise.reject(error);
  2383. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2384. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2385. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2386. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2387. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2388. m_writer.Empty(Js::OpCode::Leave);
  2389. m_writer.Br(funcInfo->singleExit);
  2390. m_writer.Empty(Js::OpCode::Leave);
  2391. m_writer.MarkLabel(doneLabel);
  2392. this->SetHasTry(true);
  2393. funcInfo->ReleaseTmpRegister(rejectLocation);
  2394. funcInfo->ReleaseTmpRegister(promiseLocation);
  2395. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2396. }
  2397. else
  2398. {
  2399. // Rest cannot have a default argument, so we ignore it.
  2400. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2401. }
  2402. if (m_writer.GetCurrentOffset() > beginOffset)
  2403. {
  2404. PopulateFormalsScope(beginOffset, funcInfo, pnodeFnc);
  2405. }
  2406. }
  2407. void ByteCodeGenerator::EmitOneFunction(ParseNodeFnc *pnodeFnc)
  2408. {
  2409. Assert(pnodeFnc && (pnodeFnc->nop == knopProg || pnodeFnc->nop == knopFncDecl));
  2410. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2411. Assert(funcInfo != nullptr);
  2412. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2413. {
  2414. return;
  2415. }
  2416. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2417. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2418. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2419. funcInfo->root,
  2420. !!(this->flags & fscrEvalCode),
  2421. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2422. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2423. if (pnodeFnc->HasDefaultArguments())
  2424. {
  2425. deferParseFunction->SetReportedInParamsCount(pnodeFnc->firstDefaultArg + 1);
  2426. }
  2427. else
  2428. {
  2429. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2430. }
  2431. // Note: Don't check the actual attributes on the functionInfo here, since CanDefer has been cleared while
  2432. // we're generating byte code.
  2433. if (deferParseFunction->IsDeferred() || funcInfo->canDefer)
  2434. {
  2435. Js::ScopeInfo::SaveEnclosingScopeInfo(this, funcInfo);
  2436. }
  2437. if (funcInfo->root->pnodeBody == nullptr)
  2438. {
  2439. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase) && (this->GetFlags() & fscrCreateParserState) == fscrCreateParserState && deferParseFunction->GetCompileCount() == 0)
  2440. {
  2441. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2442. }
  2443. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2444. return;
  2445. }
  2446. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2447. try
  2448. {
  2449. if (!funcInfo->IsGlobalFunction())
  2450. {
  2451. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2452. // In that case the flag already has the value we want.
  2453. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2454. {
  2455. #if DBG
  2456. byteCodeFunction->SetCanDoStackNestedFunc();
  2457. #endif
  2458. if (funcInfo->root->astSize <= ParseNodeFnc::MaxStackClosureAST)
  2459. {
  2460. byteCodeFunction->SetStackNestedFunc(true);
  2461. }
  2462. }
  2463. }
  2464. if (byteCodeFunction->DoStackNestedFunc())
  2465. {
  2466. uint nestedCount = byteCodeFunction->GetNestedCount();
  2467. for (uint i = 0; i < nestedCount; i++)
  2468. {
  2469. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2470. if (nested->IsFunctionBody())
  2471. {
  2472. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2473. }
  2474. }
  2475. }
  2476. if (byteCodeFunction->GetByteCode() != nullptr)
  2477. {
  2478. // Previously compiled function nested within a re-deferred and re-compiled function.
  2479. return;
  2480. }
  2481. // Bug : 301517
  2482. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2483. // and do operation on 'this' and its property, which may not be defined yet.
  2484. if (funcInfo->root->HasOnlyThisStmts() && !IsInDebugMode())
  2485. {
  2486. byteCodeFunction->SetHasOnlyThisStmts(true);
  2487. }
  2488. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2489. {
  2490. if ((pnodeFnc->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnodeFnc, this))
  2491. {
  2492. bool applyEnclosesArgs = true;
  2493. for (ParseNode* pnodeVar = funcInfo->root->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2494. {
  2495. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2496. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2497. {
  2498. applyEnclosesArgs = false;
  2499. break;
  2500. }
  2501. }
  2502. auto constAndLetCheck = [](ParseNodeBlock *pnodeBlock, bool *applyEnclosesArgs)
  2503. {
  2504. if (*applyEnclosesArgs)
  2505. {
  2506. for (auto lexvar = pnodeBlock->pnodeLexVars; lexvar; lexvar = lexvar->AsParseNodeVar()->pnodeNext)
  2507. {
  2508. Symbol* sym = lexvar->AsParseNodeVar()->sym;
  2509. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2510. {
  2511. *applyEnclosesArgs = false;
  2512. break;
  2513. }
  2514. }
  2515. }
  2516. };
  2517. constAndLetCheck(funcInfo->root->pnodeScopes, &applyEnclosesArgs);
  2518. constAndLetCheck(funcInfo->root->pnodeBodyScope, &applyEnclosesArgs);
  2519. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2520. }
  2521. }
  2522. InitScopeSlotArray(funcInfo);
  2523. FinalizeRegisters(funcInfo, byteCodeFunction);
  2524. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2525. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2526. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2527. // Need to revisit the condition when enabling JitES6Generators.
  2528. uint innerScopeCount = funcInfo->InnerScopeCount();
  2529. if (!this->IsInDebugMode() && !byteCodeFunction->IsCoroutine())
  2530. {
  2531. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2532. if (innerScopeCount)
  2533. {
  2534. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2535. for (uint i = 1; i < innerScopeCount; i++)
  2536. {
  2537. funcInfo->AcquireTmpRegister();
  2538. }
  2539. }
  2540. }
  2541. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2542. alloc,
  2543. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2544. );
  2545. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2546. alloc,
  2547. 10);
  2548. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2549. alloc,
  2550. 10);
  2551. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2552. alloc,
  2553. 10);
  2554. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2555. alloc,
  2556. 10);
  2557. byteCodeFunction->AllocateLiteralRegexArray();
  2558. m_callSiteId = 0;
  2559. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2560. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2561. this->inPrologue = true;
  2562. Scope* paramScope = funcInfo->GetParamScope();
  2563. Scope* bodyScope = funcInfo->GetBodyScope();
  2564. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2565. LoadAllConstants(funcInfo);
  2566. HomeArguments(funcInfo);
  2567. if (!funcInfo->IsBodyAndParamScopeMerged())
  2568. {
  2569. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2570. // Pop the body scope before emitting the default args
  2571. PopScope();
  2572. Assert(this->GetCurrentScope() == paramScope);
  2573. }
  2574. if (funcInfo->root->pnodeRest != nullptr)
  2575. {
  2576. byteCodeFunction->SetHasRestParameter();
  2577. }
  2578. if (funcInfo->IsGlobalFunction())
  2579. {
  2580. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2581. }
  2582. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2583. DefineLabels(funcInfo);
  2584. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2585. // argument expressions reference those special names.
  2586. if (pnodeFnc->HasNonSimpleParameterList())
  2587. {
  2588. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2589. // need to walk over the var list.
  2590. if (funcInfo->IsBodyAndParamScopeMerged())
  2591. {
  2592. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2593. {
  2594. #if DBG
  2595. bool reachedEndOfSpecialSymbols = false;
  2596. #endif
  2597. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2598. if (sym != nullptr && sym->IsSpecialSymbol())
  2599. {
  2600. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2601. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2602. {
  2603. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2604. }
  2605. }
  2606. else
  2607. {
  2608. #if DBG
  2609. reachedEndOfSpecialSymbols = true;
  2610. #else
  2611. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2612. // so we can quit walking at the first non-special one we see.
  2613. break;
  2614. #endif
  2615. }
  2616. #if DBG
  2617. if (reachedEndOfSpecialSymbols)
  2618. {
  2619. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2620. }
  2621. #endif
  2622. }
  2623. }
  2624. else
  2625. {
  2626. paramScope->ForEachSymbol([&](Symbol* sym) {
  2627. if (sym && sym->IsSpecialSymbol())
  2628. {
  2629. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2630. }
  2631. });
  2632. }
  2633. }
  2634. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2635. {
  2636. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2637. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2638. EmitDefaultArgs(funcInfo, pnodeFnc);
  2639. if (!funcInfo->IsBodyAndParamScopeMerged())
  2640. {
  2641. Assert(this->GetCurrentScope() == paramScope);
  2642. // Push the body scope
  2643. PushScope(bodyScope);
  2644. funcInfo->SetCurrentChildScope(bodyScope);
  2645. // Mark the beginning of the body scope so that new scope slots can be created.
  2646. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2647. }
  2648. }
  2649. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2650. // (that is when the function is called). This yield opcode is to mark the begining of the function body.
  2651. // TODO: Inserting a yield should have almost no impact on perf as it is a direct return from the function. But this needs
  2652. // to be verified. Ideally if the function has simple parameter list then we can avoid inserting the opcode and the additional call.
  2653. if (pnodeFnc->IsGenerator())
  2654. {
  2655. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2656. EmitYield(funcInfo->AssignUndefinedConstRegister(), tempReg, this, funcInfo);
  2657. m_writer.Reg1(Js::OpCode::Unused, tempReg);
  2658. funcInfo->ReleaseTmpRegister(tempReg);
  2659. }
  2660. DefineUserVars(funcInfo);
  2661. // Emit all scope-wide function definitions before emitting function bodies
  2662. // so that calls may reference functions they precede lexically.
  2663. // Note, global eval scope is a fake local scope and is handled as if it were
  2664. // a lexical block instead of a true global scope, so do not define the functions
  2665. // here. They will be defined during BeginEmitBlock.
  2666. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2667. {
  2668. // This only handles function declarations, which param scope cannot have any.
  2669. DefineFunctions(funcInfo);
  2670. }
  2671. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2672. {
  2673. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2674. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2675. }
  2676. else
  2677. {
  2678. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2679. }
  2680. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2681. {
  2682. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2683. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2684. }
  2685. // Rest needs to trigger use before declaration until all default args have been processed.
  2686. if (pnodeFnc->pnodeRest != nullptr)
  2687. {
  2688. pnodeFnc->pnodeRest->sym->SetNeedDeclaration(false);
  2689. }
  2690. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2691. if (!funcInfo->IsBodyAndParamScopeMerged())
  2692. {
  2693. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2694. // We have to do this after the rest param is marked as false for need declaration.
  2695. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2696. paramScope->ForEachSymbol([&](Symbol* param) {
  2697. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2698. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2699. // is expected to stay inside the function expression scope
  2700. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2701. {
  2702. if (!varSym->GetNeedDeclaration())
  2703. {
  2704. if (param->IsInSlot(this, funcInfo))
  2705. {
  2706. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2707. // Walking the scope chain is not possible at this time.
  2708. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2709. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2710. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2711. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2712. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2713. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2714. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2715. funcInfo->ReleaseTmpRegister(tempReg);
  2716. }
  2717. else if (param->GetLocation() != Js::Constants::NoRegister)
  2718. {
  2719. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2720. }
  2721. else
  2722. {
  2723. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2724. }
  2725. }
  2726. else
  2727. {
  2728. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2729. // re-declaration error.
  2730. Assert(param->IsArguments());
  2731. }
  2732. }
  2733. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2734. {
  2735. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2736. {
  2737. formalsUpperBound = param->GetLocation();
  2738. }
  2739. }
  2740. });
  2741. }
  2742. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2743. {
  2744. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2745. }
  2746. if (pnodeFnc->pnodeBodyScope != nullptr)
  2747. {
  2748. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2749. }
  2750. this->inPrologue = false;
  2751. if (funcInfo->IsGlobalFunction())
  2752. {
  2753. EmitGlobalBody(funcInfo);
  2754. }
  2755. else
  2756. {
  2757. EmitFunctionBody(funcInfo);
  2758. }
  2759. if (pnodeFnc->pnodeBodyScope != nullptr)
  2760. {
  2761. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2762. }
  2763. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2764. if (!this->IsInDebugMode())
  2765. {
  2766. // Release the temp registers that we reserved for inner scopes above.
  2767. if (innerScopeCount)
  2768. {
  2769. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2770. for (uint i = 0; i < innerScopeCount; i++)
  2771. {
  2772. funcInfo->ReleaseTmpRegister(tmpReg);
  2773. tmpReg--;
  2774. }
  2775. }
  2776. }
  2777. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2778. Assert(funcInfo->curTmpReg == firstTmpReg);
  2779. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2780. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2781. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2782. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2783. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2784. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2785. #if DBG_DUMP
  2786. if (PHASE_STATS1(Js::ByteCodePhase))
  2787. {
  2788. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2789. m_writer.ByteCodeDataSize(),
  2790. m_writer.AuxiliaryDataSize(),
  2791. m_writer.AuxiliaryContextDataSize(),
  2792. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2793. funcInfo->name);
  2794. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2795. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2796. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2797. }
  2798. #endif
  2799. this->MapCacheIdsToPropertyIds(funcInfo);
  2800. this->MapReferencedPropertyIds(funcInfo);
  2801. Assert(this->TopFuncInfo() == funcInfo);
  2802. PopFuncInfo(_u("EmitOneFunction"));
  2803. m_writer.SetCallSiteCount(m_callSiteId);
  2804. #ifdef LOG_BYTECODE_AST_RATIO
  2805. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2806. #else
  2807. m_writer.End();
  2808. #endif
  2809. }
  2810. catch (...)
  2811. {
  2812. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2813. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2814. byteCodeFunction->ResetByteCodeGenState();
  2815. m_writer.Reset();
  2816. throw;
  2817. }
  2818. #ifdef PERF_HINT
  2819. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2820. {
  2821. if (byteCodeFunction->GetHasTry())
  2822. {
  2823. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2824. }
  2825. if (funcInfo->GetCallsEval())
  2826. {
  2827. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2828. }
  2829. else if (funcInfo->GetChildCallsEval())
  2830. {
  2831. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2832. }
  2833. }
  2834. #endif
  2835. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2836. {
  2837. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2838. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2839. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2840. {
  2841. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2842. {
  2843. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2844. }
  2845. return true;
  2846. });
  2847. }
  2848. byteCodeFunction->SetInitialDefaultEntryPoint();
  2849. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2850. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2851. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2852. {
  2853. if (m_utf8SourceInfo->GetIsLibraryCode())
  2854. {
  2855. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2856. }
  2857. else
  2858. {
  2859. Js::Throw::FatalInternalError();
  2860. }
  2861. }
  2862. #endif
  2863. #if DBG_DUMP
  2864. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2865. {
  2866. pnodeFnc->Dump();
  2867. }
  2868. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2869. {
  2870. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2871. }
  2872. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2873. {
  2874. byteCodeFunction->DumpScopes();
  2875. }
  2876. #endif
  2877. #if ENABLE_NATIVE_CODEGEN
  2878. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2879. && !this->forceNoNative
  2880. && !this->scriptContext->GetConfig()->IsNoNative())
  2881. {
  2882. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2883. }
  2884. #endif
  2885. }
  2886. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2887. {
  2888. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2889. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2890. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2891. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2892. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2893. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2894. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2895. if (totalFieldAccessInlineCacheCount == 0)
  2896. {
  2897. return;
  2898. }
  2899. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2900. {
  2901. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2902. {
  2903. if (inlineCacheList)
  2904. {
  2905. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2906. {
  2907. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2908. if (cacheUnit.loadCacheId != -1)
  2909. {
  2910. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2911. }
  2912. if (cacheUnit.loadMethodCacheId != -1)
  2913. {
  2914. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2915. }
  2916. if (cacheUnit.storeCacheId != -1)
  2917. {
  2918. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2919. }
  2920. });
  2921. }
  2922. });
  2923. });
  2924. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2925. {
  2926. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2927. });
  2928. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2929. {
  2930. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2931. });
  2932. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2933. {
  2934. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2935. });
  2936. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2937. while (valueOfIter.Next())
  2938. {
  2939. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2940. }
  2941. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2942. while (toStringIter.Next())
  2943. {
  2944. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2945. }
  2946. #if DBG
  2947. functionBody->VerifyCacheIdToPropertyIdMap();
  2948. #endif
  2949. }
  2950. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2951. {
  2952. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2953. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2954. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2955. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2956. {
  2957. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2958. });
  2959. #if DBG
  2960. functionBody->VerifyReferencedPropertyIdMap();
  2961. #endif
  2962. }
  2963. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2964. {
  2965. while (pnode)
  2966. {
  2967. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2968. {
  2969. break;
  2970. }
  2971. switch (pnode->nop)
  2972. {
  2973. case knopFncDecl:
  2974. #ifdef ASMJS_PLAT
  2975. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2976. {
  2977. Js::ExclusiveContext context(this, GetScriptContext());
  2978. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2979. {
  2980. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2981. break;
  2982. }
  2983. else if (CONFIG_FLAG(AsmJsStopOnError))
  2984. {
  2985. exit(JSERR_AsmJsCompileError);
  2986. }
  2987. else
  2988. {
  2989. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2990. throw Js::AsmJsParseException();
  2991. }
  2992. }
  2993. #endif
  2994. // FALLTHROUGH
  2995. case knopProg:
  2996. if (pnode->AsParseNodeFnc()->funcInfo)
  2997. {
  2998. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  2999. Scope* paramScope = funcInfo->GetParamScope();
  3000. if (!funcInfo->IsBodyAndParamScopeMerged())
  3001. {
  3002. funcInfo->SetCurrentChildScope(paramScope);
  3003. }
  3004. else
  3005. {
  3006. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  3007. }
  3008. this->StartEmitFunction(pnode->AsParseNodeFnc());
  3009. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3010. if (!funcInfo->IsBodyAndParamScopeMerged())
  3011. {
  3012. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  3013. }
  3014. else
  3015. {
  3016. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  3017. }
  3018. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3019. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3020. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3021. funcInfo->SetCurrentChildScope(nullptr);
  3022. }
  3023. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3024. break;
  3025. case knopBlock:
  3026. {
  3027. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3028. this->StartEmitBlock(pnodeBlock);
  3029. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3030. this->EndEmitBlock(pnodeBlock);
  3031. pnode = pnodeBlock->pnodeNext;
  3032. break;
  3033. }
  3034. case knopCatch:
  3035. {
  3036. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3037. this->StartEmitCatch(pnodeCatch);
  3038. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3039. this->EndEmitCatch(pnodeCatch);
  3040. pnode = pnodeCatch->pnodeNext;
  3041. break;
  3042. }
  3043. case knopWith:
  3044. this->StartEmitWith(pnode);
  3045. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3046. this->EndEmitWith(pnode);
  3047. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3048. break;
  3049. default:
  3050. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3051. break;
  3052. }
  3053. }
  3054. }
  3055. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3056. {
  3057. if (pnodeFnc->pnodeName)
  3058. {
  3059. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3060. Symbol *sym = pnodeFnc->pnodeName->sym;
  3061. // If this function is shadowing the arguments symbol in body then skip it.
  3062. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3063. if (sym && !sym->IsArguments())
  3064. {
  3065. sym->EnsureScopeSlot(this, funcInfo);
  3066. }
  3067. }
  3068. }
  3069. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3070. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3071. {
  3072. if (pnodeFnc->pnodeName)
  3073. {
  3074. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3075. Symbol *sym = pnodeFnc->pnodeName->sym;
  3076. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3077. {
  3078. sym->EnsureScopeSlot(this, funcInfo);
  3079. }
  3080. }
  3081. }
  3082. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3083. {
  3084. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3085. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3086. Scope * const bodyScope = funcInfo->GetBodyScope();
  3087. Scope * const paramScope = funcInfo->GetParamScope();
  3088. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3089. {
  3090. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3091. {
  3092. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3093. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3094. }
  3095. if (funcInfo->GetCallsEval())
  3096. {
  3097. funcInfo->byteCodeFunction->SetDontInline(true);
  3098. }
  3099. Scope * const funcExprScope = funcInfo->funcExprScope;
  3100. if (funcExprScope)
  3101. {
  3102. if (funcInfo->GetCallsEval())
  3103. {
  3104. Assert(funcExprScope->GetIsObject());
  3105. }
  3106. if (funcExprScope->GetIsObject())
  3107. {
  3108. funcExprScope->SetCapturesAll(true);
  3109. funcExprScope->SetMustInstantiate(true);
  3110. PushScope(funcExprScope);
  3111. }
  3112. else
  3113. {
  3114. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3115. if (funcInfo->IsBodyAndParamScopeMerged())
  3116. {
  3117. funcInfo->bodyScope->AddSymbol(sym);
  3118. }
  3119. else
  3120. {
  3121. funcInfo->paramScope->AddSymbol(sym);
  3122. }
  3123. sym->EnsureScopeSlot(this, funcInfo);
  3124. if (sym->GetHasNonLocalReference())
  3125. {
  3126. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3127. }
  3128. }
  3129. }
  3130. if (pnodeFnc->nop != knopProg)
  3131. {
  3132. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3133. {
  3134. Assert(bodyScope->GetIsObject());
  3135. }
  3136. if (bodyScope->GetIsObject())
  3137. {
  3138. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3139. }
  3140. else
  3141. {
  3142. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3143. }
  3144. if (!funcInfo->IsBodyAndParamScopeMerged())
  3145. {
  3146. if (paramScope->GetIsObject())
  3147. {
  3148. paramScope->SetLocation(funcInfo->frameObjRegister);
  3149. }
  3150. else
  3151. {
  3152. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3153. }
  3154. }
  3155. if (bodyScope->GetIsObject())
  3156. {
  3157. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3158. funcInfo->SetHasCachedScope(
  3159. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3160. !funcInfo->Escapes() &&
  3161. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3162. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3163. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3164. !pnodeFnc->HasDefaultArguments() &&
  3165. !pnodeFnc->HasDestructuredParams() &&
  3166. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3167. #if ENABLE_TTD
  3168. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3169. #endif
  3170. );
  3171. if (funcInfo->GetHasCachedScope())
  3172. {
  3173. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3174. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3175. if (funcSym && funcSym->GetIsFuncExpr())
  3176. {
  3177. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3178. {
  3179. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3180. }
  3181. else
  3182. {
  3183. funcInfo->funcObjRegister = funcSym->GetLocation();
  3184. }
  3185. }
  3186. else
  3187. {
  3188. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3189. }
  3190. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3191. }
  3192. ParseNode *pnode;
  3193. Symbol *sym;
  3194. if (funcInfo->GetHasArguments())
  3195. {
  3196. // Process function's formal parameters
  3197. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3198. {
  3199. if (pnode->IsVarLetOrConst())
  3200. {
  3201. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3202. }
  3203. });
  3204. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3205. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3206. // doesn't require scope slot for "arguments" because inner functions can't access
  3207. // outer function's arguments directly.
  3208. sym = funcInfo->GetArgumentsSymbol();
  3209. Assert(sym);
  3210. if (sym->NeedsSlotAlloc(this, funcInfo))
  3211. {
  3212. sym->EnsureScopeSlot(this, funcInfo);
  3213. }
  3214. }
  3215. sym = funcInfo->root->GetFuncSymbol();
  3216. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3217. {
  3218. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3219. {
  3220. sym->SetScopeSlot(0);
  3221. }
  3222. else if (funcInfo->GetFuncExprNameReference())
  3223. {
  3224. sym->EnsureScopeSlot(this, funcInfo);
  3225. }
  3226. }
  3227. if (!funcInfo->GetHasArguments())
  3228. {
  3229. Symbol *formal;
  3230. Js::ArgSlot pos = 1;
  3231. auto moveArgToReg = [&](ParseNode *pnode)
  3232. {
  3233. if (pnode->IsVarLetOrConst())
  3234. {
  3235. formal = pnode->AsParseNodeVar()->sym;
  3236. // Get the param from its argument position into its assigned register.
  3237. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3238. if (formal->GetLocation() + 1 == pos)
  3239. {
  3240. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3241. }
  3242. }
  3243. pos++;
  3244. };
  3245. MapFormals(pnodeFnc, moveArgToReg);
  3246. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3247. }
  3248. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3249. {
  3250. sym = pnode->AsParseNodeVar()->sym;
  3251. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3252. {
  3253. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3254. {
  3255. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3256. }
  3257. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3258. {
  3259. sym->EnsureScopeSlot(this, funcInfo);
  3260. }
  3261. }
  3262. }
  3263. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3264. {
  3265. for (pnode = pnodeScope; pnode;)
  3266. {
  3267. switch (pnode->nop)
  3268. {
  3269. case knopFncDecl:
  3270. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3271. {
  3272. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3273. }
  3274. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3275. break;
  3276. case knopBlock:
  3277. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3278. break;
  3279. case knopCatch:
  3280. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3281. break;
  3282. case knopWith:
  3283. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3284. break;
  3285. }
  3286. }
  3287. };
  3288. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3289. if (pnodeFnc->pnodeBody)
  3290. {
  3291. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3292. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3293. }
  3294. }
  3295. else
  3296. {
  3297. ParseNode *pnode;
  3298. Symbol *sym;
  3299. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3300. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3301. {
  3302. sym = pnode->AsParseNodeVar()->sym;
  3303. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3304. {
  3305. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3306. {
  3307. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3308. }
  3309. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3310. {
  3311. sym->EnsureScopeSlot(this, funcInfo);
  3312. }
  3313. }
  3314. }
  3315. auto ensureScopeSlot = [&](ParseNode *pnode)
  3316. {
  3317. if (pnode->IsVarLetOrConst())
  3318. {
  3319. sym = pnode->AsParseNodeVar()->sym;
  3320. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3321. {
  3322. sym->EnsureScopeSlot(this, funcInfo);
  3323. }
  3324. }
  3325. };
  3326. // Process function's formal parameters
  3327. MapFormals(pnodeFnc, ensureScopeSlot);
  3328. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3329. if (funcInfo->GetHasArguments())
  3330. {
  3331. sym = funcInfo->GetArgumentsSymbol();
  3332. Assert(sym);
  3333. // There is no eval so the arguments may be captured in a lambda.
  3334. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3335. sym->EnsureScopeSlot(this, funcInfo);
  3336. }
  3337. if (pnodeFnc->pnodeBody)
  3338. {
  3339. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3340. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3341. }
  3342. }
  3343. // 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.
  3344. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3345. {
  3346. bodyScope->SetMustInstantiate(true);
  3347. }
  3348. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3349. {
  3350. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3351. }
  3352. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3353. {
  3354. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3355. {
  3356. paramScope->SetMustInstantiate(true);
  3357. }
  3358. else
  3359. {
  3360. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3361. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3362. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3363. }
  3364. }
  3365. }
  3366. else
  3367. {
  3368. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3369. if (newScopeForEval)
  3370. {
  3371. Assert(bodyScope->GetIsObject());
  3372. }
  3373. }
  3374. }
  3375. if (!funcInfo->IsBodyAndParamScopeMerged())
  3376. {
  3377. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3378. Assert(paramBlock->blockType == Parameter);
  3379. PushScope(paramScope);
  3380. // While emitting the functions we have to stop when we see the body scope block.
  3381. // Otherwise functions defined in the body scope will not be able to get the right references.
  3382. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3383. Assert(this->GetCurrentScope() == paramScope);
  3384. }
  3385. PushScope(bodyScope);
  3386. }
  3387. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3388. {
  3389. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3390. {
  3391. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3392. }
  3393. else
  3394. {
  3395. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3396. if (opcode == Js::OpCode::LdModuleSlot)
  3397. {
  3398. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3399. }
  3400. }
  3401. }
  3402. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3403. {
  3404. Assert(sym->GetIsModuleExportStorage());
  3405. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3406. {
  3407. return true;
  3408. }
  3409. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3410. library->EnsureModuleRecordList();
  3411. uint moduleIndex = this->GetModuleID();
  3412. uint moduleSlotIndex;
  3413. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3414. if (sym->GetIsModuleImport())
  3415. {
  3416. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3417. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3418. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3419. {
  3420. return false;
  3421. }
  3422. AnalysisAssert(moduleNameRecord != nullptr);
  3423. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3424. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3425. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3426. moduleIndex = resolvedModuleRecord->GetModuleId();
  3427. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3428. }
  3429. else
  3430. {
  3431. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3432. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3433. }
  3434. sym->SetModuleIndex(moduleIndex);
  3435. sym->SetScopeSlot(moduleSlotIndex);
  3436. return true;
  3437. }
  3438. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3439. {
  3440. // We are assigning pnode to the default export of the current module.
  3441. uint moduleIndex = this->GetModuleID();
  3442. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3443. library->EnsureModuleRecordList();
  3444. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3445. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3446. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3447. }
  3448. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3449. {
  3450. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3451. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3452. {
  3453. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3454. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3455. {
  3456. sym->EnsureScopeSlot(this, funcInfo);
  3457. this->ProcessCapturedSym(sym);
  3458. }
  3459. });
  3460. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3461. }
  3462. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3463. {
  3464. while (pnode)
  3465. {
  3466. switch (pnode->nop)
  3467. {
  3468. case knopFncDecl:
  3469. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3470. {
  3471. CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3472. }
  3473. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3474. break;
  3475. case knopBlock:
  3476. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3477. break;
  3478. case knopCatch:
  3479. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3480. break;
  3481. case knopWith:
  3482. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3483. break;
  3484. }
  3485. }
  3486. }
  3487. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3488. {
  3489. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3490. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3491. PopScope(); // function body
  3492. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3493. Scope* paramScope = funcInfo->paramScope;
  3494. if (!funcInfo->IsBodyAndParamScopeMerged())
  3495. {
  3496. Assert(this->GetCurrentScope() == paramScope);
  3497. PopScope(); // Pop the param scope
  3498. }
  3499. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3500. {
  3501. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3502. // TODO: Refactor Start and EndEmitFunction for clarity.
  3503. Scope *scope = funcInfo->funcExprScope;
  3504. if (scope && scope->GetMustInstantiate())
  3505. {
  3506. Assert(currentScope == scope);
  3507. PopScope();
  3508. }
  3509. }
  3510. Assert(funcInfo == this->TopFuncInfo());
  3511. PopFuncInfo(_u("EndEmitFunction"));
  3512. }
  3513. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3514. {
  3515. Assert(pnodeCatch->nop == knopCatch);
  3516. Scope *scope = pnodeCatch->scope;
  3517. FuncInfo *funcInfo = scope->GetFunc();
  3518. // 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).
  3519. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3520. {
  3521. scope->SetIsObject();
  3522. }
  3523. ParseNode * pnodeParam = pnodeCatch->GetParam();
  3524. if (pnodeParam->nop == knopParamPattern)
  3525. {
  3526. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3527. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3528. Parser::MapBindIdentifier(pnodeParam->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  3529. {
  3530. Symbol *sym = item->AsParseNodeVar()->sym;
  3531. if (funcInfo->IsGlobalFunction())
  3532. {
  3533. sym->SetIsGlobalCatch(true);
  3534. }
  3535. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3536. if (sym->NeedsSlotAlloc(this, funcInfo))
  3537. {
  3538. sym->EnsureScopeSlot(this, funcInfo);
  3539. }
  3540. });
  3541. // In the case of pattern we will always going to push the scope.
  3542. PushScope(scope);
  3543. }
  3544. else
  3545. {
  3546. Symbol *sym = pnodeParam->AsParseNodeName()->sym;
  3547. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3548. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3549. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3550. if (funcInfo->IsGlobalFunction())
  3551. {
  3552. sym->SetIsGlobalCatch(true);
  3553. }
  3554. if (scope->GetMustInstantiate())
  3555. {
  3556. if (sym->IsInSlot(this, funcInfo))
  3557. {
  3558. // Since there is only one symbol we are pushing to slot.
  3559. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3560. this->ProcessCapturedSym(sym);
  3561. sym->EnsureScopeSlot(this, funcInfo);
  3562. }
  3563. }
  3564. PushScope(scope);
  3565. }
  3566. }
  3567. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3568. {
  3569. Assert(pnodeCatch->nop == knopCatch);
  3570. Assert(currentScope == pnodeCatch->scope);
  3571. PopScope();
  3572. }
  3573. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3574. {
  3575. if (!BlockHasOwnScope(pnodeBlock, this))
  3576. {
  3577. return;
  3578. }
  3579. Assert(pnodeBlock->nop == knopBlock);
  3580. PushBlock(pnodeBlock);
  3581. Scope *scope = pnodeBlock->scope;
  3582. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3583. {
  3584. Assert(scope->GetIsObject());
  3585. }
  3586. // TODO: Consider nested deferred parsing.
  3587. if (scope->GetMustInstantiate())
  3588. {
  3589. FuncInfo *funcInfo = scope->GetFunc();
  3590. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3591. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3592. PushScope(scope);
  3593. }
  3594. }
  3595. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3596. {
  3597. if (!BlockHasOwnScope(pnodeBlock, this))
  3598. {
  3599. return;
  3600. }
  3601. Assert(pnodeBlock->nop == knopBlock);
  3602. Scope *scope = pnodeBlock->scope;
  3603. if (scope && scope->GetMustInstantiate())
  3604. {
  3605. Assert(currentScope == pnodeBlock->scope);
  3606. PopScope();
  3607. }
  3608. PopBlock();
  3609. }
  3610. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3611. {
  3612. Assert(pnodeWith->nop == knopWith);
  3613. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3614. AssertOrFailFast(scope->GetIsObject());
  3615. PushScope(scope);
  3616. }
  3617. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3618. {
  3619. Assert(pnodeWith->nop == knopWith);
  3620. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3621. PopScope();
  3622. }
  3623. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3624. {
  3625. Scope *currScope = this->currentScope;
  3626. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3627. if (currScope == funcScope)
  3628. {
  3629. return evalEnv;
  3630. }
  3631. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3632. if (acquireTempLoc)
  3633. {
  3634. tempLoc = funcInfo->AcquireTmpRegister();
  3635. }
  3636. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3637. // but the list must first be reversed so that innermost scopes appear first in the list.
  3638. while (currScope != funcScope)
  3639. {
  3640. Scope *innerScope;
  3641. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3642. ;
  3643. if (innerScope->GetMustInstantiate())
  3644. {
  3645. if (!innerScope->HasInnerScopeIndex())
  3646. {
  3647. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3648. {
  3649. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3650. }
  3651. else
  3652. {
  3653. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3654. }
  3655. }
  3656. else
  3657. {
  3658. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3659. {
  3660. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3661. }
  3662. else
  3663. {
  3664. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3665. }
  3666. }
  3667. evalEnv = tempLoc;
  3668. }
  3669. funcScope = innerScope;
  3670. }
  3671. if (acquireTempLoc)
  3672. {
  3673. funcInfo->ReleaseTmpRegister(tempLoc);
  3674. }
  3675. return evalEnv;
  3676. }
  3677. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3678. {
  3679. Js::ByteCodeLabel doneLabel = 0;
  3680. bool fLabelDefined = false;
  3681. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3682. Js::RegSlot thisLocation = *pThisLocation;
  3683. Js::RegSlot instLocation = *pInstLocation;
  3684. Js::PropertyId envIndex = -1;
  3685. Scope *scope = nullptr;
  3686. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3687. Assert(symScope);
  3688. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3689. {
  3690. *pInstLocation = Js::Constants::NoRegister;
  3691. return;
  3692. }
  3693. for (;;)
  3694. {
  3695. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3696. if (scope == this->globalScope)
  3697. {
  3698. break;
  3699. }
  3700. if (scope != symScope)
  3701. {
  3702. // We're not sure where the function is (eval/with/etc).
  3703. // So we're going to need registers to hold the instance where we (dynamically) find
  3704. // the function, and possibly to hold the "this" pointer we will pass to it.
  3705. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3706. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3707. if (instLocation == Js::Constants::NoRegister)
  3708. {
  3709. instLocation = funcInfo->AcquireTmpRegister();
  3710. // The "this" pointer will not be the same as the instance, so give it its own register.
  3711. thisLocation = funcInfo->AcquireTmpRegister();
  3712. }
  3713. }
  3714. if (envIndex == -1)
  3715. {
  3716. Assert(funcInfo == scope->GetFunc());
  3717. scopeLocation = scope->GetLocation();
  3718. }
  3719. if (scope == symScope)
  3720. {
  3721. break;
  3722. }
  3723. // Found a scope to which the property may have been added.
  3724. Assert(scope && scope->GetIsDynamic());
  3725. if (!fLabelDefined)
  3726. {
  3727. fLabelDefined = true;
  3728. doneLabel = this->m_writer.DefineLabel();
  3729. }
  3730. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3731. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3732. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3733. if (envIndex != -1)
  3734. {
  3735. this->m_writer.BrEnvProperty(
  3736. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3737. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3738. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3739. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3740. AssertOrFailFast(scope->GetIsObject());
  3741. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3742. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3743. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3744. this->m_writer.Reg2(op, instLocation, tmpReg);
  3745. if (thisLocation != Js::Constants::NoRegister)
  3746. {
  3747. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3748. }
  3749. funcInfo->ReleaseTmpRegister(tmpReg);
  3750. }
  3751. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3752. {
  3753. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3754. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3755. Assert(!unwrapWithObj);
  3756. AssertOrFailFast(scope->GetIsObject());
  3757. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3758. if (thisLocation != Js::Constants::NoRegister)
  3759. {
  3760. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3761. }
  3762. }
  3763. else
  3764. {
  3765. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3766. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3767. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3768. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3769. if (thisLocation != Js::Constants::NoRegister)
  3770. {
  3771. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3772. }
  3773. }
  3774. this->m_writer.Br(doneLabel);
  3775. this->m_writer.MarkLabel(nextLabel);
  3776. }
  3777. if (sym == nullptr || sym->GetIsGlobal())
  3778. {
  3779. if (this->flags & (fscrEval | fscrImplicitThis))
  3780. {
  3781. // Load of a symbol with unknown scope from within eval.
  3782. // Get it from the closure environment.
  3783. if (instLocation == Js::Constants::NoRegister)
  3784. {
  3785. instLocation = funcInfo->AcquireTmpRegister();
  3786. }
  3787. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3788. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3789. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3790. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3791. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3792. if (thisLocation == Js::Constants::NoRegister)
  3793. {
  3794. thisLocation = funcInfo->AcquireTmpRegister();
  3795. }
  3796. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3797. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3798. }
  3799. else
  3800. {
  3801. if (instLocation == Js::Constants::NoRegister)
  3802. {
  3803. instLocation = ByteCodeGenerator::RootObjectRegister;
  3804. }
  3805. else
  3806. {
  3807. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3808. }
  3809. if (thisLocation == Js::Constants::NoRegister)
  3810. {
  3811. thisLocation = funcInfo->undefinedConstantRegister;
  3812. }
  3813. else
  3814. {
  3815. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3816. }
  3817. }
  3818. }
  3819. else if (instLocation != Js::Constants::NoRegister)
  3820. {
  3821. if (envIndex != -1)
  3822. {
  3823. AssertOrFailFast(scope->GetIsObject());
  3824. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3825. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3826. }
  3827. else if (scope->HasInnerScopeIndex())
  3828. {
  3829. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3830. }
  3831. else if (symScope == funcInfo->GetParamScope())
  3832. {
  3833. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3834. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3835. }
  3836. else if (symScope != funcInfo->GetBodyScope())
  3837. {
  3838. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3839. }
  3840. else
  3841. {
  3842. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3843. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3844. }
  3845. if (thisLocation != Js::Constants::NoRegister)
  3846. {
  3847. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3848. }
  3849. else
  3850. {
  3851. thisLocation = funcInfo->undefinedConstantRegister;
  3852. }
  3853. }
  3854. *pThisLocation = thisLocation;
  3855. *pInstLocation = instLocation;
  3856. if (fLabelDefined)
  3857. {
  3858. this->m_writer.MarkLabel(doneLabel);
  3859. }
  3860. }
  3861. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3862. {
  3863. // Note: declared variables and assignments in the global function go to the root object directly.
  3864. if (this->flags & fscrEval)
  3865. {
  3866. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3867. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3868. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3869. // into one operation). See WOOB 1121763 and 1120973.
  3870. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3871. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3872. }
  3873. else
  3874. {
  3875. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3876. }
  3877. }
  3878. void
  3879. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3880. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3881. {
  3882. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3883. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3884. }
  3885. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3886. {
  3887. Scope *scope = sym->GetScope();
  3888. // Check consistency of sym->IsInSlot.
  3889. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3890. // Arrived at the scope in which the property was defined.
  3891. if (sym->NeedsSlotAlloc(this, funcInfo))
  3892. {
  3893. // The property is in memory rather than register. We'll have to load it from the slots.
  3894. if (scope->GetIsObject())
  3895. {
  3896. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3897. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3898. Js::RegSlot objReg;
  3899. if (scope->HasInnerScopeIndex())
  3900. {
  3901. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3902. }
  3903. else
  3904. {
  3905. objReg = scope->GetLocation();
  3906. }
  3907. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3908. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3909. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3910. {
  3911. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3912. }
  3913. else if (scope->HasInnerScopeIndex())
  3914. {
  3915. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3916. }
  3917. else
  3918. {
  3919. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3920. }
  3921. }
  3922. else
  3923. {
  3924. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3925. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3926. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3927. // Now store the property to its slot.
  3928. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3929. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3930. {
  3931. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3932. }
  3933. else
  3934. {
  3935. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3936. }
  3937. }
  3938. }
  3939. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3940. {
  3941. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3942. }
  3943. }
  3944. Js::OpCode
  3945. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  3946. {
  3947. Js::OpCode op;
  3948. if (envIndex != -1)
  3949. {
  3950. if (scope->GetIsObject())
  3951. {
  3952. op = Js::OpCode::StEnvObjSlot;
  3953. }
  3954. else
  3955. {
  3956. op = Js::OpCode::StEnvSlot;
  3957. }
  3958. }
  3959. else if (scopeLocation != Js::Constants::NoRegister &&
  3960. scopeLocation == funcInfo->frameSlotsRegister)
  3961. {
  3962. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3963. {
  3964. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3965. // We should use the param scope's bytecode now.
  3966. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3967. op = Js::OpCode::StParamSlot;
  3968. }
  3969. else
  3970. {
  3971. op = Js::OpCode::StLocalSlot;
  3972. }
  3973. }
  3974. else if (scopeLocation != Js::Constants::NoRegister &&
  3975. scopeLocation == funcInfo->frameObjRegister)
  3976. {
  3977. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3978. {
  3979. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3980. // We should use the param scope's bytecode now.
  3981. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3982. op = Js::OpCode::StParamObjSlot;
  3983. }
  3984. else
  3985. {
  3986. op = Js::OpCode::StLocalObjSlot;
  3987. }
  3988. }
  3989. else
  3990. {
  3991. Assert(scope->HasInnerScopeIndex());
  3992. if (scope->GetIsObject())
  3993. {
  3994. op = Js::OpCode::StInnerObjSlot;
  3995. }
  3996. else
  3997. {
  3998. op = Js::OpCode::StInnerSlot;
  3999. }
  4000. }
  4001. if (chkBlockVar)
  4002. {
  4003. op = this->ToChkUndeclOp(op);
  4004. }
  4005. return op;
  4006. }
  4007. Js::OpCode
  4008. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4009. {
  4010. Js::OpCode op;
  4011. if (scopeLocation != Js::Constants::NoRegister &&
  4012. scopeLocation == funcInfo->frameObjRegister)
  4013. {
  4014. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4015. }
  4016. else if (scope->HasInnerScopeIndex())
  4017. {
  4018. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4019. }
  4020. else
  4021. {
  4022. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4023. }
  4024. return op;
  4025. }
  4026. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4027. {
  4028. Js::ByteCodeLabel doneLabel = 0;
  4029. bool fLabelDefined = false;
  4030. Js::PropertyId envIndex = -1;
  4031. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4032. Assert(symScope);
  4033. // isFncDeclVar denotes that the symbol being stored to here is the var
  4034. // binding of a function declaration and we know we want to store directly
  4035. // to it, skipping over any dynamic scopes that may lie in between.
  4036. Scope *scope = nullptr;
  4037. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4038. bool scopeAcquired = false;
  4039. Js::OpCode op;
  4040. if (sym && sym->GetIsModuleExportStorage())
  4041. {
  4042. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4043. {
  4044. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4045. }
  4046. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4047. return;
  4048. }
  4049. if (isFncDeclVar)
  4050. {
  4051. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4052. // of the parent function, so we need to calculate envIndex in lieu of the while
  4053. // loop below.
  4054. do
  4055. {
  4056. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4057. } while (scope != symScope);
  4058. Assert(scope == symScope);
  4059. scopeLocation = scope->GetLocation();
  4060. }
  4061. while (!isFncDeclVar)
  4062. {
  4063. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4064. if (scope == this->globalScope)
  4065. {
  4066. break;
  4067. }
  4068. if (envIndex == -1)
  4069. {
  4070. Assert(funcInfo == scope->GetFunc());
  4071. scopeLocation = scope->GetLocation();
  4072. }
  4073. if (scope == symScope)
  4074. {
  4075. break;
  4076. }
  4077. // Found a scope to which the property may have been added.
  4078. Assert(scope && scope->GetIsDynamic());
  4079. if (!fLabelDefined)
  4080. {
  4081. fLabelDefined = true;
  4082. doneLabel = this->m_writer.DefineLabel();
  4083. }
  4084. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4085. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4086. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4087. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4088. if (envIndex != -1)
  4089. {
  4090. this->m_writer.BrEnvProperty(
  4091. Js::OpCode::BrOnNoEnvProperty,
  4092. nextLabel,
  4093. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4094. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4095. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4096. AssertOrFailFast(scope->GetIsObject());
  4097. this->m_writer.SlotI1(
  4098. Js::OpCode::LdEnvObj,
  4099. instLocation,
  4100. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4101. if (unwrapWithObj)
  4102. {
  4103. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4104. }
  4105. this->m_writer.PatchableProperty(
  4106. Js::OpCode::StFld,
  4107. rhsLocation,
  4108. instLocation,
  4109. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4110. funcInfo->ReleaseTmpRegister(instLocation);
  4111. }
  4112. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4113. {
  4114. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4115. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4116. Assert(!unwrapWithObj);
  4117. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4118. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4119. }
  4120. else
  4121. {
  4122. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4123. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4124. if (unwrapWithObj)
  4125. {
  4126. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4127. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4128. scopeLocation = unwrappedScopeLocation;
  4129. }
  4130. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4131. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4132. if (unwrapWithObj)
  4133. {
  4134. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4135. }
  4136. }
  4137. this->m_writer.Br(doneLabel);
  4138. this->m_writer.MarkLabel(nextLabel);
  4139. }
  4140. // Arrived at the scope in which the property was defined.
  4141. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4142. {
  4143. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4144. // Intentionally continue on to do normal EmitPropStore behavior so
  4145. // that the bytecode ends up well-formed for the backend. This is
  4146. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4147. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4148. // of their load and then they skip emitting their own bytecode.
  4149. // Potayto potahto.
  4150. }
  4151. if (sym == nullptr || sym->GetIsGlobal())
  4152. {
  4153. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4154. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4155. if (this->flags & fscrEval)
  4156. {
  4157. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4158. {
  4159. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4160. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4161. }
  4162. else
  4163. {
  4164. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4165. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4166. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4167. }
  4168. }
  4169. else if (this->flags & fscrImplicitThis)
  4170. {
  4171. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4172. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4173. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4174. }
  4175. else
  4176. {
  4177. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false, forceStrictModeForClassComputedPropertyName), rhsLocation, propertyId, false, true, funcInfo);
  4178. }
  4179. }
  4180. else if (sym->GetIsFuncExpr())
  4181. {
  4182. // Store to function expr variable.
  4183. // strict mode: we need to throw type error
  4184. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4185. {
  4186. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4187. // It doesn't matter which register we use, as long as it's valid for this function.
  4188. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4189. }
  4190. }
  4191. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4192. {
  4193. if (!isConstDecl && sym->GetIsConst())
  4194. {
  4195. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4196. // we have to catch it at runtime.
  4197. this->m_writer.W1(
  4198. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4199. }
  4200. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4201. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4202. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4203. // The property is in memory rather than register. We'll have to load it from the slots.
  4204. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4205. if (envIndex != -1)
  4206. {
  4207. this->m_writer.SlotI2(op, rhsLocation,
  4208. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4209. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4210. }
  4211. else if (scopeLocation != Js::Constants::NoRegister &&
  4212. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4213. {
  4214. this->m_writer.SlotI1(op, rhsLocation,
  4215. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4216. }
  4217. else
  4218. {
  4219. Assert(scope->HasInnerScopeIndex());
  4220. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4221. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4222. }
  4223. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4224. {
  4225. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4226. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4227. }
  4228. }
  4229. else if (isConstDecl)
  4230. {
  4231. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4232. if (this->ShouldTrackDebuggerMetadata())
  4233. {
  4234. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4235. }
  4236. }
  4237. else
  4238. {
  4239. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4240. {
  4241. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4242. // we have to catch it at runtime.
  4243. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4244. }
  4245. if (rhsLocation != sym->GetLocation())
  4246. {
  4247. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4248. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4249. {
  4250. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4251. }
  4252. }
  4253. }
  4254. if (fLabelDefined)
  4255. {
  4256. this->m_writer.MarkLabel(doneLabel);
  4257. }
  4258. if (scopeAcquired)
  4259. {
  4260. funcInfo->ReleaseTmpRegister(scopeLocation);
  4261. }
  4262. }
  4263. Js::OpCode
  4264. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4265. {
  4266. Js::OpCode op;
  4267. if (envIndex != -1)
  4268. {
  4269. if (scope->GetIsObject())
  4270. {
  4271. op = Js::OpCode::LdEnvObjSlot;
  4272. }
  4273. else
  4274. {
  4275. op = Js::OpCode::LdEnvSlot;
  4276. }
  4277. }
  4278. else if (scopeLocation != Js::Constants::NoRegister &&
  4279. scopeLocation == funcInfo->frameSlotsRegister)
  4280. {
  4281. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4282. {
  4283. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4284. // We should use the param scope's bytecode now.
  4285. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4286. op = Js::OpCode::LdParamSlot;
  4287. }
  4288. else
  4289. {
  4290. op = Js::OpCode::LdLocalSlot;
  4291. }
  4292. }
  4293. else if (scopeLocation != Js::Constants::NoRegister &&
  4294. scopeLocation == funcInfo->frameObjRegister)
  4295. {
  4296. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4297. {
  4298. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4299. // We should use the param scope's bytecode now.
  4300. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4301. op = Js::OpCode::LdParamObjSlot;
  4302. }
  4303. else
  4304. {
  4305. op = Js::OpCode::LdLocalObjSlot;
  4306. }
  4307. }
  4308. else if (scope->HasInnerScopeIndex())
  4309. {
  4310. if (scope->GetIsObject())
  4311. {
  4312. op = Js::OpCode::LdInnerObjSlot;
  4313. }
  4314. else
  4315. {
  4316. op = Js::OpCode::LdInnerSlot;
  4317. }
  4318. }
  4319. else
  4320. {
  4321. AssertOrFailFast(scope->GetIsObject());
  4322. op = Js::OpCode::LdObjSlot;
  4323. }
  4324. return op;
  4325. }
  4326. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4327. {
  4328. #if DBG
  4329. // We should load a const 'this' binding if the following holds
  4330. // - The function has a 'this' name node
  4331. // - We are in a global or global lambda function
  4332. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4333. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4334. {
  4335. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4336. && !funcInfo->GetThisSymbol()
  4337. && !(this->flags & fscrEval));
  4338. }
  4339. #endif
  4340. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4341. }
  4342. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4343. {
  4344. Symbol* sym = pnodeSpecialName->sym;
  4345. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4346. {
  4347. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4348. }
  4349. else
  4350. {
  4351. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4352. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4353. {
  4354. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4355. }
  4356. }
  4357. }
  4358. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4359. {
  4360. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4361. {
  4362. if (init)
  4363. {
  4364. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4365. }
  4366. else
  4367. {
  4368. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4369. }
  4370. }
  4371. }
  4372. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4373. {
  4374. // If sym belongs to a parent frame, get it from the closure environment.
  4375. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4376. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4377. // Otherwise, just copy the value to the lhsLocation.
  4378. Js::ByteCodeLabel doneLabel = 0;
  4379. bool fLabelDefined = false;
  4380. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4381. Js::PropertyId envIndex = -1;
  4382. Scope *scope = nullptr;
  4383. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4384. Assert(symScope);
  4385. if (sym && sym->GetIsModuleExportStorage())
  4386. {
  4387. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4388. return;
  4389. }
  4390. for (;;)
  4391. {
  4392. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4393. if (scope == this->globalScope)
  4394. {
  4395. break;
  4396. }
  4397. scopeLocation = scope->GetLocation();
  4398. if (scope == symScope)
  4399. {
  4400. break;
  4401. }
  4402. // Found a scope to which the property may have been added.
  4403. Assert(scope && scope->GetIsDynamic());
  4404. if (!fLabelDefined)
  4405. {
  4406. fLabelDefined = true;
  4407. doneLabel = this->m_writer.DefineLabel();
  4408. }
  4409. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4410. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4411. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4412. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4413. if (envIndex != -1)
  4414. {
  4415. this->m_writer.BrEnvProperty(
  4416. Js::OpCode::BrOnNoEnvProperty,
  4417. nextLabel,
  4418. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4419. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4420. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4421. AssertOrFailFast(scope->GetIsObject());
  4422. this->m_writer.SlotI1(
  4423. Js::OpCode::LdEnvObj,
  4424. instLocation,
  4425. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4426. if (unwrapWithObj)
  4427. {
  4428. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4429. }
  4430. this->m_writer.PatchableProperty(
  4431. Js::OpCode::LdFld,
  4432. lhsLocation,
  4433. instLocation,
  4434. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4435. funcInfo->ReleaseTmpRegister(instLocation);
  4436. }
  4437. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4438. {
  4439. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4440. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4441. Assert(!unwrapWithObj);
  4442. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4443. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4444. }
  4445. else
  4446. {
  4447. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4448. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4449. if (unwrapWithObj)
  4450. {
  4451. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4452. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4453. scopeLocation = unwrappedScopeLocation;
  4454. }
  4455. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4456. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4457. if (unwrapWithObj)
  4458. {
  4459. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4460. }
  4461. }
  4462. this->m_writer.Br(doneLabel);
  4463. this->m_writer.MarkLabel(nextLabel);
  4464. }
  4465. // Arrived at the scope in which the property was defined.
  4466. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4467. {
  4468. // Ensure this symbol has a slot if it needs one.
  4469. if (sym->IsInSlot(this, funcInfo))
  4470. {
  4471. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4472. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4473. }
  4474. if (skipUseBeforeDeclarationCheck)
  4475. {
  4476. if (lhsLocation != Js::Constants::NoRegister)
  4477. {
  4478. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4479. }
  4480. }
  4481. else
  4482. {
  4483. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4484. }
  4485. }
  4486. else if (sym == nullptr || sym->GetIsGlobal())
  4487. {
  4488. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4489. if (this->flags & fscrEval)
  4490. {
  4491. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4492. {
  4493. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4494. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4495. }
  4496. else
  4497. {
  4498. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4499. // Load of a symbol with unknown scope from within eval
  4500. // Get it from the closure environment.
  4501. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4502. }
  4503. }
  4504. else if (this->flags & fscrImplicitThis)
  4505. {
  4506. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4507. // Load of a symbol with unknown scope from within event handler.
  4508. // Get it from the closure environment.
  4509. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4510. }
  4511. else
  4512. {
  4513. // Special case non-writable built-ins
  4514. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4515. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4516. // next time we run. May want to catch that in the JIT.
  4517. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4518. // These properties are non-writable
  4519. switch (propertyId)
  4520. {
  4521. case Js::PropertyIds::NaN:
  4522. opcode = Js::OpCode::LdNaN;
  4523. break;
  4524. case Js::PropertyIds::Infinity:
  4525. opcode = Js::OpCode::LdInfinity;
  4526. break;
  4527. case Js::PropertyIds::undefined:
  4528. opcode = Js::OpCode::LdUndef;
  4529. break;
  4530. case Js::PropertyIds::__chakraLibrary:
  4531. if (CONFIG_FLAG(LdChakraLib) || CONFIG_FLAG(TestChakraLib))
  4532. {
  4533. opcode = Js::OpCode::LdChakraLib;
  4534. }
  4535. break;
  4536. }
  4537. if (opcode == Js::OpCode::LdRootFld)
  4538. {
  4539. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4540. }
  4541. else
  4542. {
  4543. this->Writer()->Reg1(opcode, lhsLocation);
  4544. }
  4545. }
  4546. }
  4547. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4548. {
  4549. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4550. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4551. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4552. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4553. Js::OpCode op;
  4554. // Now get the property from its slot.
  4555. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4556. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4557. if (envIndex != -1)
  4558. {
  4559. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4560. }
  4561. else if (scopeLocation != Js::Constants::NoRegister &&
  4562. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4563. {
  4564. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4565. }
  4566. else if (scope->HasInnerScopeIndex())
  4567. {
  4568. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4569. }
  4570. else
  4571. {
  4572. AssertOrFailFast(scope->GetIsObject());
  4573. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4574. }
  4575. if (chkBlockVar)
  4576. {
  4577. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4578. }
  4579. }
  4580. else
  4581. {
  4582. if (lhsLocation != sym->GetLocation())
  4583. {
  4584. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4585. }
  4586. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4587. {
  4588. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4589. }
  4590. }
  4591. if (fLabelDefined)
  4592. {
  4593. this->m_writer.MarkLabel(doneLabel);
  4594. }
  4595. }
  4596. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4597. {
  4598. bool tdz = sym->GetIsBlockVar()
  4599. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4600. return tdz || sym->GetIsNonSimpleParameter();
  4601. }
  4602. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4603. {
  4604. // If sym belongs to a parent frame, delete it from the closure environment.
  4605. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4606. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4607. // Otherwise, just return false.
  4608. Js::ByteCodeLabel doneLabel = 0;
  4609. bool fLabelDefined = false;
  4610. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4611. Js::PropertyId envIndex = -1;
  4612. Scope *scope = nullptr;
  4613. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4614. Assert(symScope);
  4615. for (;;)
  4616. {
  4617. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4618. if (scope == this->globalScope)
  4619. {
  4620. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4621. }
  4622. else if (envIndex == -1)
  4623. {
  4624. Assert(funcInfo == scope->GetFunc());
  4625. scopeLocation = scope->GetLocation();
  4626. }
  4627. if (scope == symScope)
  4628. {
  4629. break;
  4630. }
  4631. // Found a scope to which the property may have been added.
  4632. Assert(scope && scope->GetIsDynamic());
  4633. if (!fLabelDefined)
  4634. {
  4635. fLabelDefined = true;
  4636. doneLabel = this->m_writer.DefineLabel();
  4637. }
  4638. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4639. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4640. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4641. if (envIndex != -1)
  4642. {
  4643. this->m_writer.BrEnvProperty(
  4644. Js::OpCode::BrOnNoEnvProperty,
  4645. nextLabel,
  4646. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4647. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4648. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4649. AssertOrFailFast(scope->GetIsObject());
  4650. this->m_writer.SlotI1(
  4651. Js::OpCode::LdEnvObj,
  4652. instLocation,
  4653. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4654. if (unwrapWithObj)
  4655. {
  4656. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4657. }
  4658. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4659. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4660. funcInfo->ReleaseTmpRegister(instLocation);
  4661. }
  4662. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4663. {
  4664. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4665. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4666. Assert(!unwrapWithObj);
  4667. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4668. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4669. }
  4670. else
  4671. {
  4672. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4673. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4674. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4675. if (unwrapWithObj)
  4676. {
  4677. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4678. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4679. scopeLocation = unwrappedScopeLocation;
  4680. }
  4681. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4682. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4683. if (unwrapWithObj)
  4684. {
  4685. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4686. }
  4687. }
  4688. this->m_writer.Br(doneLabel);
  4689. this->m_writer.MarkLabel(nextLabel);
  4690. }
  4691. // Arrived at the scope in which the property was defined.
  4692. if (sym == nullptr || sym->GetIsGlobal())
  4693. {
  4694. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4695. if (this->flags & (fscrEval | fscrImplicitThis))
  4696. {
  4697. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4698. funcInfo->FindOrAddReferencedPropertyId(propertyId), forceStrictModeForClassComputedPropertyName);
  4699. }
  4700. else
  4701. {
  4702. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4703. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4704. }
  4705. }
  4706. else
  4707. {
  4708. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4709. sym->EnsureScopeSlot(this, funcInfo);
  4710. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4711. }
  4712. if (fLabelDefined)
  4713. {
  4714. this->m_writer.MarkLabel(doneLabel);
  4715. }
  4716. }
  4717. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4718. {
  4719. uint cacheId;
  4720. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4721. switch (ldFldOp)
  4722. {
  4723. case Js::OpCode::LdRootFldForTypeOf:
  4724. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4725. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4726. break;
  4727. case Js::OpCode::LdLocalFld:
  4728. case Js::OpCode::ScopedLdFldForTypeOf:
  4729. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4730. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4731. break;
  4732. default:
  4733. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4734. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4735. break;
  4736. }
  4737. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4738. funcInfo->ReleaseTmpRegister(tmpReg);
  4739. }
  4740. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4741. {
  4742. // If sym belongs to a parent frame, delete it from the closure environment.
  4743. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4744. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4745. // Otherwise, just return false
  4746. Js::ByteCodeLabel doneLabel = 0;
  4747. bool fLabelDefined = false;
  4748. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4749. Js::PropertyId envIndex = -1;
  4750. Scope *scope = nullptr;
  4751. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4752. Assert(symScope);
  4753. if (sym && sym->GetIsModuleExportStorage())
  4754. {
  4755. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4756. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4757. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4758. funcInfo->ReleaseTmpRegister(tmpLocation);
  4759. return;
  4760. }
  4761. for (;;)
  4762. {
  4763. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4764. if (scope == this->globalScope)
  4765. {
  4766. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4767. }
  4768. else if (envIndex == -1)
  4769. {
  4770. Assert(funcInfo == scope->GetFunc());
  4771. scopeLocation = scope->GetLocation();
  4772. }
  4773. if (scope == symScope)
  4774. {
  4775. break;
  4776. }
  4777. // Found a scope to which the property may have been added.
  4778. Assert(scope && scope->GetIsDynamic());
  4779. if (!fLabelDefined)
  4780. {
  4781. fLabelDefined = true;
  4782. doneLabel = this->m_writer.DefineLabel();
  4783. }
  4784. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4785. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4786. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4787. if (envIndex != -1)
  4788. {
  4789. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4790. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4791. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4792. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4793. AssertOrFailFast(scope->GetIsObject());
  4794. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4795. instLocation,
  4796. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4797. if (unwrapWithObj)
  4798. {
  4799. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4800. }
  4801. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4802. funcInfo->ReleaseTmpRegister(instLocation);
  4803. }
  4804. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4805. {
  4806. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4807. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4808. Assert(!unwrapWithObj);
  4809. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4810. }
  4811. else
  4812. {
  4813. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4814. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4815. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4816. if (unwrapWithObj)
  4817. {
  4818. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4819. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4820. scopeLocation = unwrappedScopeLocation;
  4821. }
  4822. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4823. if (unwrapWithObj)
  4824. {
  4825. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4826. }
  4827. }
  4828. this->m_writer.Br(doneLabel);
  4829. this->m_writer.MarkLabel(nextLabel);
  4830. }
  4831. // Arrived at the scope in which the property was defined.
  4832. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4833. {
  4834. // Ensure this symbol has a slot if it needs one.
  4835. if (sym->IsInSlot(this, funcInfo))
  4836. {
  4837. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4838. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4839. }
  4840. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4841. }
  4842. else if (sym == nullptr || sym->GetIsGlobal())
  4843. {
  4844. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4845. if (this->flags & fscrEval)
  4846. {
  4847. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4848. {
  4849. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4850. }
  4851. else
  4852. {
  4853. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4854. }
  4855. }
  4856. else if (this->flags & fscrImplicitThis)
  4857. {
  4858. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4859. }
  4860. else
  4861. {
  4862. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4863. }
  4864. }
  4865. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4866. {
  4867. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4868. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4869. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4870. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4871. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4872. Js::OpCode op;
  4873. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4874. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4875. if (envIndex != -1)
  4876. {
  4877. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4878. }
  4879. else if (scopeLocation != Js::Constants::NoRegister &&
  4880. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4881. {
  4882. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4883. }
  4884. else if (scope->HasInnerScopeIndex())
  4885. {
  4886. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4887. }
  4888. else
  4889. {
  4890. AssertOrFailFast(scope->GetIsObject());
  4891. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4892. }
  4893. if (chkBlockVar)
  4894. {
  4895. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4896. }
  4897. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4898. funcInfo->ReleaseTmpRegister(tmpLocation);
  4899. }
  4900. else
  4901. {
  4902. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4903. }
  4904. if (fLabelDefined)
  4905. {
  4906. this->m_writer.MarkLabel(doneLabel);
  4907. }
  4908. }
  4909. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  4910. {
  4911. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4912. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4913. // remain local to the eval code.
  4914. Assert(pnodeBlock->nop == knopBlock);
  4915. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4916. if (!(this->flags & fscrEvalCode))
  4917. {
  4918. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4919. {
  4920. FuncInfo *funcInfo = this->TopFuncInfo();
  4921. Symbol *sym = pnode->AsParseNodeVar()->sym;
  4922. Assert(sym->GetIsGlobal());
  4923. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4924. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4925. });
  4926. }
  4927. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo, bool isFncDecl = false)
  4928. {
  4929. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4930. // Global function declarations must pass #sec-candeclareglobalfunction
  4931. // which is enforced by EnsureCanDeclGloFunc
  4932. if (isFncDecl)
  4933. {
  4934. this->m_writer.ElementRootU(Js::OpCode::EnsureCanDeclGloFunc, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4935. }
  4936. if (this->flags & fscrEval)
  4937. {
  4938. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4939. {
  4940. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4941. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4942. }
  4943. }
  4944. else
  4945. {
  4946. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4947. }
  4948. };
  4949. // scan for function declarations
  4950. // these behave like "var" declarations
  4951. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  4952. {
  4953. switch (pnode->nop) {
  4954. case knopFncDecl:
  4955. if (pnode->AsParseNodeFnc()->IsDeclaration())
  4956. {
  4957. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo, true);
  4958. }
  4959. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  4960. break;
  4961. case knopBlock:
  4962. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  4963. break;
  4964. case knopCatch:
  4965. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  4966. break;
  4967. case knopWith:
  4968. pnode = pnode->AsParseNodeWith()->pnodeNext;
  4969. break;
  4970. default:
  4971. Assert(UNREACHED);
  4972. }
  4973. }
  4974. // scan for var declarations
  4975. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  4976. {
  4977. Symbol* sym = pnode->AsParseNodeVar()->sym;
  4978. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  4979. continue;
  4980. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4981. {
  4982. // The init node was bound to the catch object, because it's inside a catch and has the
  4983. // same name as the catch object. But we want to define a user var at function scope,
  4984. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4985. // This also applies to a var declaration in the same scope as a let declaration.
  4986. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4987. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  4988. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4989. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4990. }
  4991. Assert(sym->GetIsGlobal());
  4992. if (sym->GetSymbolType() == STVariable)
  4993. {
  4994. emitRedeclCheck(sym, funcInfo);
  4995. }
  4996. }
  4997. }
  4998. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  4999. {
  5000. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5001. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5002. {
  5003. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5004. });
  5005. }
  5006. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5007. {
  5008. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5009. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5010. {
  5011. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  5012. });
  5013. }
  5014. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5015. {
  5016. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5017. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5018. {
  5019. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5020. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5021. rawArray->Freeze();
  5022. Js::RecyclableObject* callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5023. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5024. callsiteObject->Freeze();
  5025. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5026. });
  5027. }
  5028. bool IsApplyArgs(ParseNodeCall* callNode)
  5029. {
  5030. ParseNode* target = callNode->pnodeTarget;
  5031. ParseNode* args = callNode->pnodeArgs;
  5032. if ((target != nullptr) && (target->nop == knopDot))
  5033. {
  5034. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5035. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5036. {
  5037. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5038. if (nameNode != nullptr)
  5039. {
  5040. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5041. if (nameIsApply && args != nullptr && args->nop == knopList)
  5042. {
  5043. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5044. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5045. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5046. {
  5047. return arg2->AsParseNodeName()->sym->IsArguments();
  5048. }
  5049. }
  5050. }
  5051. }
  5052. }
  5053. return false;
  5054. }
  5055. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5056. {
  5057. if ((pnode == nullptr) || (!applyCheck->matches))
  5058. {
  5059. return;
  5060. }
  5061. if (pnode->nop == knopCall)
  5062. {
  5063. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5064. {
  5065. if (!applyCheck->insideApplyCall)
  5066. {
  5067. applyCheck->matches = false;
  5068. }
  5069. applyCheck->insideApplyCall = false;
  5070. }
  5071. }
  5072. }
  5073. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5074. {
  5075. if ((pnode == nullptr) || (!applyCheck->matches))
  5076. {
  5077. return;
  5078. }
  5079. switch (pnode->nop)
  5080. {
  5081. case knopName:
  5082. {
  5083. Symbol* sym = pnode->AsParseNodeName()->sym;
  5084. if (sym != nullptr)
  5085. {
  5086. if (sym->IsArguments())
  5087. {
  5088. if (!applyCheck->insideApplyCall)
  5089. {
  5090. applyCheck->matches = false;
  5091. }
  5092. }
  5093. }
  5094. break;
  5095. }
  5096. case knopCall:
  5097. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5098. {
  5099. // no nested apply calls
  5100. if (applyCheck->insideApplyCall)
  5101. {
  5102. applyCheck->matches = false;
  5103. }
  5104. else
  5105. {
  5106. applyCheck->insideApplyCall = true;
  5107. applyCheck->sawApply = true;
  5108. pnode->AsParseNodeCall()->isApplyCall = true;
  5109. }
  5110. }
  5111. break;
  5112. }
  5113. }
  5114. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5115. {
  5116. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5117. // side-effects in the argument list. We need to know this so that the call target
  5118. // operands can be preserved if necessary.
  5119. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5120. // but we can be more precise if we need to be.
  5121. if (pSideEffect)
  5122. {
  5123. *pSideEffect = FALSE;
  5124. }
  5125. unsigned int argCount = 1;
  5126. if (pnode != nullptr)
  5127. {
  5128. while (pnode->nop == knopList)
  5129. {
  5130. argCount++;
  5131. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5132. {
  5133. *pSideEffect = TRUE;
  5134. }
  5135. pnode = pnode->AsParseNodeBin()->pnode2;
  5136. }
  5137. argCount++;
  5138. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5139. {
  5140. *pSideEffect = TRUE;
  5141. }
  5142. }
  5143. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5144. return argCount;
  5145. }
  5146. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5147. {
  5148. // Save a local name to a register other than its home location.
  5149. // This guards against side-effects in cases like x.foo(x = bar()).
  5150. Symbol *sym = nullptr;
  5151. if (pnode->nop == knopName)
  5152. {
  5153. sym = pnode->AsParseNodeName()->sym;
  5154. }
  5155. else if (pnode->nop == knopComputedName)
  5156. {
  5157. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5158. if (pnode1->nop == knopName)
  5159. {
  5160. sym = pnode1->AsParseNodeName()->sym;
  5161. }
  5162. }
  5163. if (sym == nullptr)
  5164. {
  5165. return;
  5166. }
  5167. // If the target is a local being kept in its home location,
  5168. // protect the target's value in the event the home location is overwritten.
  5169. if (pnode->location != Js::Constants::NoRegister &&
  5170. sym->GetScope()->GetFunc() == funcInfo &&
  5171. pnode->location == sym->GetLocation())
  5172. {
  5173. pnode->location = funcInfo->AcquireTmpRegister();
  5174. }
  5175. }
  5176. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5177. {
  5178. Assert(TopFuncInfo() != nullptr);
  5179. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5180. }
  5181. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5182. {
  5183. m_writer.EndStatement(node);
  5184. }
  5185. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5186. {
  5187. Assert(TopFuncInfo() != nullptr);
  5188. m_writer.StartSubexpression(node);
  5189. }
  5190. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5191. {
  5192. m_writer.EndSubexpression(node);
  5193. }
  5194. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5195. {
  5196. // Generate code for the LHS of an assignment.
  5197. switch (pnode->nop)
  5198. {
  5199. case knopDot:
  5200. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5201. break;
  5202. case knopIndex:
  5203. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5204. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5205. break;
  5206. case knopName:
  5207. break;
  5208. case knopArrayPattern:
  5209. case knopObjectPattern:
  5210. break;
  5211. case knopCall:
  5212. case knopNew:
  5213. // Emit the operands of a call that will be used as a LHS.
  5214. // These have to be emitted before the RHS, but they have to persist until
  5215. // the end of the expression.
  5216. // Emit the call target operands first.
  5217. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5218. {
  5219. case knopDot:
  5220. case knopIndex:
  5221. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5222. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5223. break;
  5224. case knopName:
  5225. {
  5226. Symbol *sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5227. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5228. {
  5229. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5230. }
  5231. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5232. {
  5233. // Can't get the value from the assigned register, so load it here.
  5234. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5235. }
  5236. else
  5237. {
  5238. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5239. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5240. // must manually check here.
  5241. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5242. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5243. }
  5244. break;
  5245. }
  5246. default:
  5247. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5248. break;
  5249. }
  5250. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5251. if (pnode->AsParseNodeCall()->pnodeArgs)
  5252. {
  5253. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5254. while (pnodeArg->nop == knopList)
  5255. {
  5256. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5257. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5258. }
  5259. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5260. }
  5261. if (pnode->AsParseNodeCall()->isSuperCall)
  5262. {
  5263. Emit(pnode->AsParseNodeSuperCall()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5264. Emit(pnode->AsParseNodeSuperCall()->pnodeNewTarget, byteCodeGenerator, funcInfo, false);
  5265. }
  5266. break;
  5267. default:
  5268. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5269. break;
  5270. }
  5271. }
  5272. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5273. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5274. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5275. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5276. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5277. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5278. {
  5279. switch (elem->nop)
  5280. {
  5281. case knopVarDecl:
  5282. case knopLetDecl:
  5283. case knopConstDecl:
  5284. // We manually need to set NeedDeclaration since the node won't be visited.
  5285. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5286. break;
  5287. default:
  5288. EmitReference(elem, byteCodeGenerator, funcInfo);
  5289. }
  5290. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5291. funcInfo->ReleaseReference(elem);
  5292. }
  5293. void EmitDestructuredRestArray(ParseNode *elem,
  5294. Js::RegSlot iteratorLocation,
  5295. Js::RegSlot shouldCallReturnFunctionLocation,
  5296. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5297. ByteCodeGenerator *byteCodeGenerator,
  5298. FuncInfo *funcInfo)
  5299. {
  5300. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5301. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5302. if (isAssignmentTarget)
  5303. {
  5304. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5305. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5306. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5307. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5308. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5309. }
  5310. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5311. Js::OpCode::NewScArray,
  5312. restArrayLocation,
  5313. ByteCodeGenerator::DefaultArraySize);
  5314. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5315. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5316. // convey this is live on the back edge.
  5317. // As a workaround, we have a persistent var reg that is used for the loop counter
  5318. Js::RegSlot counterLocation = elem->location;
  5319. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5320. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5321. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5322. // loopTop:
  5323. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5324. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5325. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5326. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5327. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5328. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5329. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5330. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5331. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5332. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5333. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5334. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5335. byteCodeGenerator->Writer()->Element(
  5336. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5337. valueLocation, restArrayLocation, counterLocation);
  5338. funcInfo->ReleaseTmpRegister(valueLocation);
  5339. funcInfo->ReleaseTmpRegister(doneLocation);
  5340. funcInfo->ReleaseTmpRegister(itemLocation);
  5341. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5342. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5343. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5344. byteCodeGenerator->Writer()->Br(loopTop);
  5345. // iteratorDone:
  5346. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5347. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5348. if (isAssignmentTarget)
  5349. {
  5350. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5351. funcInfo->ReleaseReference(restElem);
  5352. }
  5353. else
  5354. {
  5355. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5356. }
  5357. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5358. }
  5359. void EmitDestructuredArray(
  5360. ParseNode *lhs,
  5361. Js::RegSlot rhsLocation,
  5362. ByteCodeGenerator *byteCodeGenerator,
  5363. FuncInfo *funcInfo);
  5364. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5365. {
  5366. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5367. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5368. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5369. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5370. }
  5371. /*
  5372. EmitDestructuredArray(lhsArray, rhs):
  5373. iterator = rhs[@@iterator]
  5374. if lhsArray empty
  5375. return
  5376. for each element in lhsArray except rest
  5377. value = iterator.next()
  5378. if element is a nested destructured array
  5379. EmitDestructuredArray(element, value)
  5380. else
  5381. if value is undefined and there is an initializer
  5382. evaluate initializer
  5383. evaluate element reference
  5384. element = initializer
  5385. else
  5386. element = value
  5387. if lhsArray has a rest element
  5388. rest = []
  5389. while iterator is not done
  5390. value = iterator.next()
  5391. rest.append(value)
  5392. */
  5393. void EmitDestructuredArrayCore(
  5394. ParseNode *list,
  5395. Js::RegSlot iteratorLocation,
  5396. Js::RegSlot shouldCallReturnFunctionLocation,
  5397. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5398. ByteCodeGenerator *byteCodeGenerator,
  5399. FuncInfo *funcInfo
  5400. )
  5401. {
  5402. Assert(list != nullptr);
  5403. ParseNode *elem = nullptr;
  5404. while (list != nullptr)
  5405. {
  5406. ParseNode *init = nullptr;
  5407. if (list->nop == knopList)
  5408. {
  5409. elem = list->AsParseNodeBin()->pnode1;
  5410. }
  5411. else
  5412. {
  5413. elem = list;
  5414. }
  5415. if (elem->nop == knopEllipsis)
  5416. {
  5417. break;
  5418. }
  5419. switch (elem->nop)
  5420. {
  5421. case knopAsg:
  5422. // An assignment node will always have an initializer
  5423. init = elem->AsParseNodeBin()->pnode2;
  5424. elem = elem->AsParseNodeBin()->pnode1;
  5425. break;
  5426. case knopVarDecl:
  5427. case knopLetDecl:
  5428. case knopConstDecl:
  5429. init = elem->AsParseNodeVar()->pnodeInit;
  5430. break;
  5431. default:
  5432. break;
  5433. }
  5434. byteCodeGenerator->StartStatement(elem);
  5435. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5436. if (isAssignmentTarget)
  5437. {
  5438. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5439. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5440. EmitReference(elem, byteCodeGenerator, funcInfo);
  5441. }
  5442. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5443. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5444. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5445. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5446. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5447. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5448. if (elem->nop == knopEmpty)
  5449. {
  5450. if (list->nop == knopList)
  5451. {
  5452. list = list->AsParseNodeBin()->pnode2;
  5453. funcInfo->ReleaseTmpRegister(doneLocation);
  5454. funcInfo->ReleaseTmpRegister(itemLocation);
  5455. continue;
  5456. }
  5457. else
  5458. {
  5459. Assert(list->nop == knopEmpty);
  5460. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5461. funcInfo->ReleaseTmpRegister(doneLocation);
  5462. funcInfo->ReleaseTmpRegister(itemLocation);
  5463. break;
  5464. }
  5465. }
  5466. // If the iterator hasn't completed, skip assigning undefined.
  5467. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5468. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5469. // We're not done with the iterator, so assign the .next() value.
  5470. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5471. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5472. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5473. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5474. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5475. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5476. // iteratorAlreadyDone:
  5477. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5478. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5479. // beforeDefaultAssign:
  5480. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5481. if (elem->IsPattern())
  5482. {
  5483. // If we get an undefined value and have an initializer, use it in place of undefined.
  5484. if (init != nullptr)
  5485. {
  5486. /*
  5487. the IR builder uses two symbols for a temp register in the if else path
  5488. R9 <- R3
  5489. if (...)
  5490. R9 <- R2
  5491. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5492. hence we have to create a new temp
  5493. TEMP REG USED TO FIX THIS PRODUCES THIS
  5494. R9 <- R3
  5495. if (BrEq_A R9, R3)
  5496. R10 <- R2 :
  5497. else
  5498. R10 <- R9 : skipdefault
  5499. ... = R10[@@iterator] : loadIter
  5500. */
  5501. // Temp Register
  5502. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5503. byteCodeGenerator->StartStatement(init);
  5504. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5505. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5506. // check value is undefined
  5507. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5508. // Evaluate the default expression and assign it.
  5509. Emit(init, byteCodeGenerator, funcInfo, false);
  5510. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5511. funcInfo->ReleaseLoc(init);
  5512. // jmp to loadIter
  5513. byteCodeGenerator->Writer()->Br(loadIter);
  5514. // skipDefault:
  5515. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5516. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5517. // loadIter:
  5518. // @@iterator
  5519. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5520. byteCodeGenerator->EndStatement(init);
  5521. if (elem->nop == knopObjectPattern)
  5522. {
  5523. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5524. }
  5525. else
  5526. {
  5527. // Recursively emit a destructured array using the current .next() as the RHS.
  5528. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5529. }
  5530. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5531. }
  5532. else
  5533. {
  5534. if (elem->nop == knopObjectPattern)
  5535. {
  5536. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5537. }
  5538. else
  5539. {
  5540. // Recursively emit a destructured array using the current .next() as the RHS.
  5541. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5542. }
  5543. }
  5544. }
  5545. else
  5546. {
  5547. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5548. }
  5549. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5550. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5551. if (list->nop != knopList)
  5552. {
  5553. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5554. }
  5555. funcInfo->ReleaseTmpRegister(valueLocation);
  5556. funcInfo->ReleaseTmpRegister(doneLocation);
  5557. funcInfo->ReleaseTmpRegister(itemLocation);
  5558. if (isAssignmentTarget)
  5559. {
  5560. funcInfo->ReleaseReference(elem);
  5561. }
  5562. byteCodeGenerator->EndStatement(elem);
  5563. if (list->nop == knopList)
  5564. {
  5565. list = list->AsParseNodeBin()->pnode2;
  5566. }
  5567. else
  5568. {
  5569. break;
  5570. }
  5571. }
  5572. // If we saw a rest element, emit the rest array.
  5573. if (elem != nullptr && elem->nop == knopEllipsis)
  5574. {
  5575. EmitDestructuredRestArray(elem,
  5576. iteratorLocation,
  5577. shouldCallReturnFunctionLocation,
  5578. shouldCallReturnFunctionLocationFinally,
  5579. byteCodeGenerator,
  5580. funcInfo);
  5581. }
  5582. }
  5583. // Generating
  5584. // try {
  5585. // CallIteratorClose
  5586. // } catch (e) {
  5587. // do nothing
  5588. // }
  5589. void EmitTryCatchAroundClose(
  5590. Js::RegSlot iteratorLocation,
  5591. Js::ByteCodeLabel endLabel,
  5592. ByteCodeGenerator *byteCodeGenerator,
  5593. FuncInfo *funcInfo)
  5594. {
  5595. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5596. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5597. //
  5598. // There is no need to add TryScopeRecord here as we are going to call 'return' function and there is not yield expression here.
  5599. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5600. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5601. byteCodeGenerator->Writer()->Br(endLabel);
  5602. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5603. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5604. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5605. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5606. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5607. }
  5608. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5609. {
  5610. Js::OpCode op;
  5611. Js::ByteCodeLabel label;
  5612. Js::RegSlot reg1;
  5613. Js::RegSlot reg2;
  5614. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5615. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5616. };
  5617. // Generating
  5618. // catch(e) {
  5619. // if (shouldCallReturn)
  5620. // CallReturnWhichWrappedByTryCatch
  5621. // throw e;
  5622. // }
  5623. void EmitTopLevelCatch(Js::ByteCodeLabel catchLabel,
  5624. Js::RegSlot iteratorLocation,
  5625. Js::RegSlot shouldCallReturnLocation,
  5626. Js::RegSlot shouldCallReturnLocationFinally,
  5627. ByteCodeGenerator *byteCodeGenerator,
  5628. FuncInfo *funcInfo)
  5629. {
  5630. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5631. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5632. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5633. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5634. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5635. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5636. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  5637. if (funcInfo->byteCodeFunction->IsCoroutine())
  5638. {
  5639. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  5640. }
  5641. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5642. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5643. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnLocationFinally);
  5644. EmitTryCatchAroundClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo);
  5645. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5646. // Rethrow the exception.
  5647. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5648. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5649. if (funcInfo->byteCodeFunction->IsCoroutine())
  5650. {
  5651. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5652. }
  5653. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5654. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5655. }
  5656. // Generating
  5657. // finally {
  5658. // if (shouldCallReturn)
  5659. // CallReturn
  5660. // }
  5661. void EmitTopLevelFinally(Js::ByteCodeLabel finallyLabel,
  5662. Js::RegSlot iteratorLocation,
  5663. Js::RegSlot shouldCallReturnLocation,
  5664. Js::RegSlot yieldExceptionLocation,
  5665. Js::RegSlot yieldOffsetLocation,
  5666. ByteCodeGenerator *byteCodeGenerator,
  5667. FuncInfo *funcInfo)
  5668. {
  5669. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5670. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5671. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5672. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5673. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5674. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5675. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5676. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5677. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, yieldExceptionLocation, yieldOffsetLocation);
  5678. if (isCoroutine)
  5679. {
  5680. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  5681. }
  5682. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5683. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5684. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5685. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5686. if (isCoroutine)
  5687. {
  5688. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5689. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5690. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5691. }
  5692. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5693. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5694. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5695. }
  5696. void EmitCatchAndFinallyBlocks(Js::ByteCodeLabel catchLabel,
  5697. Js::ByteCodeLabel finallyLabel,
  5698. Js::RegSlot iteratorLocation,
  5699. Js::RegSlot shouldCallReturnFunctionLocation,
  5700. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5701. Js::RegSlot yieldExceptionLocation,
  5702. Js::RegSlot yieldOffsetLocation,
  5703. ByteCodeGenerator *byteCodeGenerator,
  5704. FuncInfo *funcInfo
  5705. )
  5706. {
  5707. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5708. if (isCoroutine)
  5709. {
  5710. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5711. }
  5712. EmitTopLevelCatch(catchLabel,
  5713. iteratorLocation,
  5714. shouldCallReturnFunctionLocation,
  5715. shouldCallReturnFunctionLocationFinally,
  5716. byteCodeGenerator,
  5717. funcInfo);
  5718. if (isCoroutine)
  5719. {
  5720. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5721. }
  5722. EmitTopLevelFinally(finallyLabel,
  5723. iteratorLocation,
  5724. shouldCallReturnFunctionLocationFinally,
  5725. yieldExceptionLocation,
  5726. yieldOffsetLocation,
  5727. byteCodeGenerator,
  5728. funcInfo);
  5729. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  5730. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  5731. }
  5732. // Emit a wrapper try..finaly block around the destructuring elements
  5733. void EmitDestructuredArray(
  5734. ParseNode *lhs,
  5735. Js::RegSlot rhsLocation,
  5736. ByteCodeGenerator *byteCodeGenerator,
  5737. FuncInfo *funcInfo)
  5738. {
  5739. byteCodeGenerator->StartStatement(lhs);
  5740. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5741. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5742. Assert(lhs->nop == knopArrayPattern);
  5743. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  5744. if (list == nullptr)
  5745. { // Handline this case ([] = obj);
  5746. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5747. // No elements to bind or assign.
  5748. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5749. byteCodeGenerator->EndStatement(lhs);
  5750. return;
  5751. }
  5752. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  5753. // this variable will be set to true.
  5754. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  5755. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  5756. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5757. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5758. byteCodeGenerator->SetHasFinally(true);
  5759. byteCodeGenerator->SetHasTry(true);
  5760. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  5761. Js::RegSlot regException = Js::Constants::NoRegister;
  5762. Js::RegSlot regOffset = Js::Constants::NoRegister;
  5763. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5764. if (isCoroutine)
  5765. {
  5766. regException = funcInfo->AcquireTmpRegister();
  5767. regOffset = funcInfo->AcquireTmpRegister();
  5768. }
  5769. // Insert try node here
  5770. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  5771. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5772. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5773. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  5774. if (isCoroutine)
  5775. {
  5776. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  5777. tryRecForTryFinally.reg1 = regException;
  5778. tryRecForTryFinally.reg2 = regOffset;
  5779. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  5780. }
  5781. else
  5782. {
  5783. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  5784. }
  5785. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5786. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  5787. if (isCoroutine)
  5788. {
  5789. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  5790. }
  5791. EmitDestructuredArrayCore(list,
  5792. iteratorLocation,
  5793. shouldCallReturnFunctionLocation,
  5794. shouldCallReturnFunctionLocationFinally,
  5795. byteCodeGenerator,
  5796. funcInfo);
  5797. EmitCatchAndFinallyBlocks(catchLabel,
  5798. finallyLabel,
  5799. iteratorLocation,
  5800. shouldCallReturnFunctionLocation,
  5801. shouldCallReturnFunctionLocationFinally,
  5802. regException,
  5803. regOffset,
  5804. byteCodeGenerator,
  5805. funcInfo);
  5806. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5807. byteCodeGenerator->EndStatement(lhs);
  5808. }
  5809. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5810. Js::RegSlot objectLocation,
  5811. Js::RegSlot computedPropIdArrLocation,
  5812. uint32 *computedIndex,
  5813. bool hasRest,
  5814. ParseNodePtr nameNode,
  5815. ByteCodeGenerator* byteCodeGenerator,
  5816. FuncInfo* funcInfo)
  5817. {
  5818. Assert(nameNode != nullptr);
  5819. if (nameNode->nop == knopComputedName)
  5820. {
  5821. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  5822. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5823. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5824. if (hasRest)
  5825. {
  5826. byteCodeGenerator->Writer()->Slot(Js::OpCode::StPropIdArrFromVar, pnode1->location, computedPropIdArrLocation, *computedIndex);
  5827. (*computedIndex)++;
  5828. }
  5829. funcInfo->ReleaseLoc(pnode1);
  5830. }
  5831. else
  5832. {
  5833. Assert(nameNode->nop == knopStr);
  5834. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5835. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5836. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5837. }
  5838. }
  5839. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5840. Js::RegSlot rhsLocation,
  5841. ParseNodePtr initializer,
  5842. bool isNonPatternAssignmentTarget,
  5843. ByteCodeGenerator *byteCodeGenerator,
  5844. FuncInfo *funcInfo)
  5845. {
  5846. // 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
  5847. Js::ByteCodeLabel useDefault = -1;
  5848. Js::ByteCodeLabel end = -1;
  5849. Js::RegSlot rhsLocationTmp = rhsLocation;
  5850. if (initializer != nullptr)
  5851. {
  5852. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5853. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5854. end = byteCodeGenerator->Writer()->DefineLabel();
  5855. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5856. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5857. byteCodeGenerator->Writer()->Br(end);
  5858. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5859. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5860. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5861. funcInfo->ReleaseLoc(initializer);
  5862. byteCodeGenerator->Writer()->MarkLabel(end);
  5863. }
  5864. if (lhsElementNode->nop == knopArrayPattern)
  5865. {
  5866. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5867. }
  5868. else if (lhsElementNode->nop == knopObjectPattern)
  5869. {
  5870. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5871. }
  5872. else if (isNonPatternAssignmentTarget)
  5873. {
  5874. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5875. }
  5876. else
  5877. {
  5878. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5879. }
  5880. if (initializer != nullptr)
  5881. {
  5882. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5883. }
  5884. }
  5885. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5886. Js::RegSlot rhsLocation,
  5887. Js::RegSlot propIdArrLocation,
  5888. Js::RegSlot computedPropIdArrLocation,
  5889. uint32 *computedIndex,
  5890. bool hasRest,
  5891. ByteCodeGenerator *byteCodeGenerator,
  5892. FuncInfo *funcInfo)
  5893. {
  5894. Assert(memberNode->nop == knopObjectPatternMember || memberNode->nop == knopEllipsis);
  5895. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5896. ParseNodePtr lhsElementNode = nullptr;
  5897. if (memberNode->nop == knopObjectPatternMember)
  5898. {
  5899. EmitNameInvoke(nameLocation, rhsLocation, computedPropIdArrLocation,
  5900. computedIndex, hasRest, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  5901. // Imagine we are transforming
  5902. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5903. lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  5904. }
  5905. else
  5906. {
  5907. // memberNode->nop == knopEllipsis, aka we are performing Rest operation
  5908. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, nameLocation);
  5909. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Restify, rhsLocation, nameLocation, propIdArrLocation, computedPropIdArrLocation);
  5910. lhsElementNode = memberNode->AsParseNodeUni()->pnode1;
  5911. }
  5912. ParseNodePtr init = nullptr;
  5913. if (lhsElementNode->IsVarLetOrConst())
  5914. {
  5915. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  5916. }
  5917. else if (lhsElementNode->nop == knopAsg)
  5918. {
  5919. init = lhsElementNode->AsParseNodeBin()->pnode2;
  5920. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  5921. }
  5922. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  5923. funcInfo->ReleaseTmpRegister(nameLocation);
  5924. }
  5925. void EmitObjectPropertyIdsToArray(ByteCodeGenerator *byteCodeGenerator,
  5926. Js::PropertyId *ids,
  5927. ParseNodePtr memberNodes,
  5928. uint32 staticCount,
  5929. bool *hasComputedProps)
  5930. {
  5931. uint32 index = 0;
  5932. Parser::ForEachItemInList(memberNodes, [&](ParseNodePtr current) {
  5933. if (current->nop != knopEllipsis)
  5934. {
  5935. ParseNodePtr nameNode = current->AsParseNodeBin()->pnode1;
  5936. Assert(nameNode != nullptr);
  5937. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  5938. if (nameNode->nop == knopStr)
  5939. {
  5940. if (index >= staticCount)
  5941. {
  5942. Js::Throw::InternalError();
  5943. return;
  5944. }
  5945. ids[index] = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5946. index++;
  5947. }
  5948. else
  5949. {
  5950. *hasComputedProps = true;
  5951. }
  5952. }
  5953. });
  5954. }
  5955. void EmitDestructuredObject(ParseNode *lhs,
  5956. Js::RegSlot rhsLocationOrig,
  5957. ByteCodeGenerator *byteCodeGenerator,
  5958. FuncInfo *funcInfo)
  5959. {
  5960. Assert(lhs->nop == knopObjectPattern);
  5961. ParseNodeObjLit *pnodeObjLit = lhs->AsParseNodeObjLit();
  5962. ParseNodePtr pnode1 = pnodeObjLit->pnode1;
  5963. uint32 staticCount = pnodeObjLit->staticCount;
  5964. uint32 computedCount = pnodeObjLit->computedCount;
  5965. bool hasRest = pnodeObjLit->hasRest;
  5966. bool hasComputedProps = false;
  5967. byteCodeGenerator->StartStatement(lhs);
  5968. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5969. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  5970. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  5971. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  5972. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  5973. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5974. if (pnode1 != nullptr)
  5975. {
  5976. Js::RegSlot propIdArrLocation = Js::Constants::NoRegister;
  5977. Js::RegSlot computedPropIdArrLocation = Js::Constants::NoRegister;
  5978. if (hasRest)
  5979. {
  5980. uint extraAlloc = UInt32Math::Mul(staticCount, sizeof(Js::PropertyId));
  5981. uint auxSize = UInt32Math::Add(sizeof(Js::PropertyIdArray), extraAlloc);
  5982. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::PropertyIdArray, staticCount, 0);
  5983. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember || pnode1->nop == knopEllipsis);
  5984. EmitObjectPropertyIdsToArray(byteCodeGenerator, propIds->elements, pnode1, staticCount, &hasComputedProps);
  5985. // Load static PropertyIdArray here
  5986. propIdArrLocation = funcInfo->AcquireTmpRegister();
  5987. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::LdPropIds, propIdArrLocation, propIds, auxSize, staticCount);
  5988. if (hasComputedProps)
  5989. {
  5990. computedPropIdArrLocation = funcInfo->AcquireTmpRegister();
  5991. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewPropIdArrForCompProps, computedPropIdArrLocation, computedCount);
  5992. }
  5993. else
  5994. {
  5995. computedPropIdArrLocation = propIdArrLocation;
  5996. }
  5997. }
  5998. uint32 index = 0;
  5999. Parser::ForEachItemInList(pnode1, [&](ParseNodePtr memberNode) {
  6000. EmitDestructuredObjectMember(memberNode, rhsLocation, propIdArrLocation, computedPropIdArrLocation,
  6001. &index, hasRest, byteCodeGenerator, funcInfo);
  6002. });
  6003. if (hasRest)
  6004. {
  6005. if (hasComputedProps)
  6006. {
  6007. funcInfo->ReleaseTmpRegister(computedPropIdArrLocation);
  6008. }
  6009. funcInfo->ReleaseTmpRegister(propIdArrLocation);
  6010. }
  6011. }
  6012. funcInfo->ReleaseTmpRegister(rhsLocation);
  6013. byteCodeGenerator->EndStatement(lhs);
  6014. }
  6015. void EmitAssignment(
  6016. ParseNode *asgnNode,
  6017. ParseNode *lhs,
  6018. Js::RegSlot rhsLocation,
  6019. ByteCodeGenerator *byteCodeGenerator,
  6020. FuncInfo *funcInfo)
  6021. {
  6022. switch (lhs->nop)
  6023. {
  6024. // assignment to a local or global variable
  6025. case knopVarDecl:
  6026. case knopLetDecl:
  6027. case knopConstDecl:
  6028. {
  6029. Symbol *sym = lhs->AsParseNodeVar()->sym;
  6030. Assert(sym != nullptr);
  6031. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  6032. break;
  6033. }
  6034. case knopName:
  6035. {
  6036. // Special names like 'this' or 'new.target' cannot be assigned to
  6037. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  6038. if (pnodeNameLhs->IsSpecialName())
  6039. {
  6040. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6041. }
  6042. else
  6043. {
  6044. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  6045. }
  6046. break;
  6047. }
  6048. // x.y =
  6049. case knopDot:
  6050. {
  6051. // PutValue(x, "y", rhs)
  6052. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6053. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6054. {
  6055. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6056. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  6057. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6058. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  6059. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  6060. }
  6061. else
  6062. {
  6063. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  6064. byteCodeGenerator->Writer()->PatchableProperty(
  6065. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false, byteCodeGenerator->forceStrictModeForClassComputedPropertyName), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6066. }
  6067. break;
  6068. }
  6069. case knopIndex:
  6070. {
  6071. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  6072. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6073. {
  6074. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  6075. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  6076. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  6077. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6078. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6079. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  6080. }
  6081. byteCodeGenerator->Writer()->Element(
  6082. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  6083. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  6084. break;
  6085. }
  6086. case knopObjectPattern:
  6087. {
  6088. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6089. // Copy the rhs value to be the result of the assignment if needed.
  6090. if (asgnNode != nullptr)
  6091. {
  6092. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6093. }
  6094. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6095. }
  6096. case knopArrayPattern:
  6097. {
  6098. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6099. // Copy the rhs value to be the result of the assignment if needed.
  6100. if (asgnNode != nullptr)
  6101. {
  6102. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6103. }
  6104. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6105. }
  6106. case knopArray:
  6107. case knopObject:
  6108. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6109. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6110. // down early vs. runtime errors for destructuring.
  6111. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6112. break;
  6113. default:
  6114. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6115. break;
  6116. }
  6117. if (asgnNode != nullptr)
  6118. {
  6119. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6120. if (asgnNode->location != rhsLocation)
  6121. {
  6122. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6123. }
  6124. }
  6125. }
  6126. void EmitLoad(
  6127. ParseNode *lhs,
  6128. ByteCodeGenerator *byteCodeGenerator,
  6129. FuncInfo *funcInfo)
  6130. {
  6131. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6132. // in the process.
  6133. // We usually get here as part of an op-equiv expression: x.y += z;
  6134. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6135. switch (lhs->nop)
  6136. {
  6137. // load of a local or global variable
  6138. case knopName:
  6139. {
  6140. funcInfo->AcquireLoc(lhs);
  6141. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6142. break;
  6143. }
  6144. // = x.y
  6145. case knopDot:
  6146. {
  6147. // get field id for "y"
  6148. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6149. funcInfo->AcquireLoc(lhs);
  6150. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6151. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6152. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6153. break;
  6154. }
  6155. case knopIndex:
  6156. funcInfo->AcquireLoc(lhs);
  6157. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6158. byteCodeGenerator->Writer()->Element(
  6159. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6160. break;
  6161. // f(x) +=
  6162. case knopCall:
  6163. {
  6164. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6165. if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6166. {
  6167. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6168. Assert(CountArguments(args) == 2); // import() takes one argument
  6169. Emit(args, byteCodeGenerator, funcInfo, false);
  6170. funcInfo->ReleaseLoc(args);
  6171. funcInfo->AcquireLoc(pnodeCallLhs);
  6172. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6173. }
  6174. else
  6175. {
  6176. funcInfo->AcquireLoc(pnodeCallLhs);
  6177. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6178. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6179. }
  6180. break;
  6181. }
  6182. default:
  6183. funcInfo->AcquireLoc(lhs);
  6184. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6185. break;
  6186. }
  6187. }
  6188. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6189. {
  6190. if (pnode != nullptr)
  6191. {
  6192. while (pnode->nop == knopList)
  6193. {
  6194. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6195. pnode = pnode->AsParseNodeBin()->pnode2;
  6196. }
  6197. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6198. }
  6199. }
  6200. void EmitOneArg(
  6201. ParseNode *pnode,
  6202. BOOL fAssignRegs,
  6203. ByteCodeGenerator *byteCodeGenerator,
  6204. FuncInfo *funcInfo,
  6205. Js::ProfileId callSiteId,
  6206. Js::ArgSlot &argIndex,
  6207. Js::ArgSlot &spreadIndex,
  6208. Js::RegSlot argTempLocation,
  6209. bool emitProfiledArgout,
  6210. Js::AuxArray<uint32> *spreadIndices = nullptr
  6211. )
  6212. {
  6213. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6214. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6215. // We just need to emit the ArgOut instructions.
  6216. if (fAssignRegs)
  6217. {
  6218. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6219. }
  6220. if (pnode->nop == knopEllipsis)
  6221. {
  6222. Assert(spreadIndices != nullptr);
  6223. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6224. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6225. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6226. if (noArgOuts)
  6227. {
  6228. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6229. }
  6230. else
  6231. {
  6232. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6233. }
  6234. funcInfo->ReleaseTmpRegister(regVal);
  6235. }
  6236. else
  6237. {
  6238. if (noArgOuts)
  6239. {
  6240. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6241. }
  6242. else
  6243. {
  6244. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6245. }
  6246. }
  6247. argIndex++;
  6248. if (fAssignRegs)
  6249. {
  6250. funcInfo->ReleaseLoc(pnode);
  6251. }
  6252. }
  6253. size_t EmitArgsWithArgOutsAtEnd(
  6254. ParseNode *pnode,
  6255. BOOL fAssignRegs,
  6256. ByteCodeGenerator *byteCodeGenerator,
  6257. FuncInfo *funcInfo,
  6258. Js::ProfileId callSiteId,
  6259. Js::RegSlot thisLocation,
  6260. Js::ArgSlot argsCountForStartCall,
  6261. bool emitProfiledArgouts,
  6262. Js::AuxArray<uint32> *spreadIndices = nullptr
  6263. )
  6264. {
  6265. AssertOrFailFast(pnode != nullptr);
  6266. Js::ArgSlot argIndex = 0;
  6267. Js::ArgSlot spreadIndex = 0;
  6268. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6269. Js::RegSlot firstArgTempLocation = argTempLocation;
  6270. while (pnode->nop == knopList)
  6271. {
  6272. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6273. pnode = pnode->AsParseNodeBin()->pnode2;
  6274. argTempLocation = funcInfo->AcquireTmpRegister();
  6275. }
  6276. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6277. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6278. // Emit all argOuts now
  6279. if (thisLocation != Js::Constants::NoRegister)
  6280. {
  6281. // Emit the "this" object.
  6282. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6283. }
  6284. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6285. {
  6286. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6287. }
  6288. // Now release all those temps register
  6289. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6290. {
  6291. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6292. }
  6293. return argIndex;
  6294. }
  6295. size_t EmitArgs(
  6296. ParseNode *pnode,
  6297. BOOL fAssignRegs,
  6298. ByteCodeGenerator *byteCodeGenerator,
  6299. FuncInfo *funcInfo,
  6300. Js::ProfileId callSiteId,
  6301. bool emitProfiledArgouts,
  6302. Js::AuxArray<uint32> *spreadIndices = nullptr
  6303. )
  6304. {
  6305. Js::ArgSlot argIndex = 0;
  6306. Js::ArgSlot spreadIndex = 0;
  6307. if (pnode != nullptr)
  6308. {
  6309. while (pnode->nop == knopList)
  6310. {
  6311. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6312. pnode = pnode->AsParseNodeBin()->pnode2;
  6313. }
  6314. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6315. }
  6316. return argIndex;
  6317. }
  6318. void EmitArgListStart(
  6319. Js::RegSlot thisLocation,
  6320. ByteCodeGenerator *byteCodeGenerator,
  6321. FuncInfo *funcInfo,
  6322. Js::ProfileId callSiteId)
  6323. {
  6324. if (thisLocation != Js::Constants::NoRegister)
  6325. {
  6326. // Emit the "this" object.
  6327. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6328. }
  6329. }
  6330. Js::ArgSlot EmitArgListEnd(
  6331. ParseNode *pnode,
  6332. Js::RegSlot thisLocation,
  6333. Js::RegSlot evalLocation,
  6334. Js::RegSlot newTargetLocation,
  6335. ByteCodeGenerator *byteCodeGenerator,
  6336. FuncInfo *funcInfo,
  6337. size_t argIndex,
  6338. Js::ProfileId callSiteId)
  6339. {
  6340. BOOL fEvalInModule = false;
  6341. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6342. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6343. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6344. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6345. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6346. Js::ArgSlot evalIndex;
  6347. if (fIsEval && argSlotIndex > 0)
  6348. {
  6349. Assert(!fHasNewTarget);
  6350. // Pass the frame display as an extra argument to "eval".
  6351. // Do this only if eval is called with some args
  6352. Js::RegSlot evalEnv;
  6353. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6354. {
  6355. // Use current environment as the environment for the function being called when:
  6356. // - this is the root global function (not an eval's global function)
  6357. // - this is an eval's global function that is not in strict mode (see else block)
  6358. evalEnv = funcInfo->GetEnvRegister();
  6359. }
  6360. else
  6361. {
  6362. // Use the frame display as the environment for the function being called when:
  6363. // - this is not a global function and thus it will have its own scope
  6364. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6365. // has its own scope
  6366. evalEnv = funcInfo->frameDisplayRegister;
  6367. }
  6368. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6369. // Passing the FrameDisplay as an extra argument
  6370. evalIndex = argSlotIndex + 1;
  6371. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6372. {
  6373. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6374. }
  6375. else
  6376. {
  6377. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6378. }
  6379. }
  6380. if (fHasNewTarget)
  6381. {
  6382. Assert(!fIsEval);
  6383. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6384. }
  6385. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6386. // eval and no args passed, return 1 as argument count
  6387. if (fIsEval && pnode == nullptr)
  6388. {
  6389. return 1;
  6390. }
  6391. return argIntCount;
  6392. }
  6393. Js::ArgSlot EmitArgList(
  6394. ParseNode *pnode,
  6395. Js::RegSlot thisLocation,
  6396. Js::RegSlot newTargetLocation,
  6397. BOOL fIsEval,
  6398. BOOL fAssignRegs,
  6399. ByteCodeGenerator *byteCodeGenerator,
  6400. FuncInfo *funcInfo,
  6401. Js::ProfileId callSiteId,
  6402. Js::ArgSlot argsCountForStartCall,
  6403. bool emitArgOutsAtEnd,
  6404. bool emitProfiledArgouts,
  6405. uint16 spreadArgCount = 0,
  6406. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6407. {
  6408. // This function emits the arguments for a call.
  6409. // ArgOut's with uses immediately following defs.
  6410. if (!emitArgOutsAtEnd)
  6411. {
  6412. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6413. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6414. }
  6415. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6416. //
  6417. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6418. // This would be used while generating frameDisplay in EmitArgListEnd.
  6419. //
  6420. if (fIsEval)
  6421. {
  6422. evalLocation = funcInfo->AcquireTmpRegister();
  6423. }
  6424. if (spreadArgCount > 0)
  6425. {
  6426. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6427. Assert(spreadIndices != nullptr);
  6428. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6429. }
  6430. size_t argIndex = 0;
  6431. if (emitArgOutsAtEnd)
  6432. {
  6433. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6434. }
  6435. else
  6436. {
  6437. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6438. }
  6439. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6440. if (fIsEval)
  6441. {
  6442. funcInfo->ReleaseTmpRegister(evalLocation);
  6443. }
  6444. return argumentsCount;
  6445. }
  6446. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6447. {
  6448. uint index = 0;
  6449. while (args->nop == knopList && index < argCount)
  6450. {
  6451. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6452. {
  6453. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6454. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6455. }
  6456. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6457. {
  6458. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6459. #if ! FLOATVAR
  6460. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6461. #endif
  6462. vars[index++] = number;
  6463. }
  6464. else
  6465. {
  6466. AnalysisAssert(false);
  6467. }
  6468. args = args->AsParseNodeBin()->pnode2;
  6469. }
  6470. if (index == argCount)
  6471. {
  6472. Assert(false);
  6473. Js::Throw::InternalError();
  6474. return;
  6475. }
  6476. if (args->nop == knopInt)
  6477. {
  6478. int value = args->AsParseNodeInt()->lw;
  6479. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6480. }
  6481. else if (args->nop == knopFlt)
  6482. {
  6483. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6484. #if ! FLOATVAR
  6485. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6486. #endif
  6487. vars[index++] = number;
  6488. }
  6489. else
  6490. {
  6491. AnalysisAssert(false);
  6492. }
  6493. }
  6494. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6495. {
  6496. uint index = 0;
  6497. while (args->nop == knopList && index < argCount)
  6498. {
  6499. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6500. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6501. args = args->AsParseNodeBin()->pnode2;
  6502. }
  6503. if (index >= argCount)
  6504. {
  6505. Js::Throw::InternalError();
  6506. return;
  6507. }
  6508. Assert(args->nop == knopInt);
  6509. vars[index++] = args->AsParseNodeInt()->lw;
  6510. Assert(index == argCount);
  6511. }
  6512. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6513. {
  6514. uint index = 0;
  6515. while (args->nop == knopList && index < argCount)
  6516. {
  6517. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6518. if (nop == knopInt)
  6519. {
  6520. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6521. }
  6522. else
  6523. {
  6524. Assert(nop == knopFlt);
  6525. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6526. }
  6527. args = args->AsParseNodeBin()->pnode2;
  6528. }
  6529. if (index >= argCount)
  6530. {
  6531. Js::Throw::InternalError();
  6532. return;
  6533. }
  6534. if (args->nop == knopInt)
  6535. {
  6536. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6537. }
  6538. else
  6539. {
  6540. Assert(args->nop == knopFlt);
  6541. vars[index++] = args->AsParseNodeFloat()->dbl;
  6542. }
  6543. Assert(index == argCount);
  6544. }
  6545. //
  6546. // Called when we have new Ctr(constant, constant...)
  6547. //
  6548. Js::ArgSlot EmitNewObjectOfConstants(
  6549. ParseNode *pnode,
  6550. ByteCodeGenerator *byteCodeGenerator,
  6551. FuncInfo *funcInfo,
  6552. unsigned int argCount)
  6553. {
  6554. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6555. // Create the vars array
  6556. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6557. // Emit all constants to the vars array
  6558. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6559. // Finish the arg list
  6560. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6561. pnode->AsParseNodeCall()->pnodeArgs,
  6562. Js::Constants::NoRegister,
  6563. Js::Constants::NoRegister,
  6564. Js::Constants::NoRegister,
  6565. byteCodeGenerator,
  6566. funcInfo,
  6567. argCount - 1,
  6568. Js::Constants::NoProfileId);
  6569. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6570. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6571. // Generate the opcode with vars
  6572. byteCodeGenerator->Writer()->AuxiliaryContext(
  6573. Js::OpCode::NewScObject_A,
  6574. funcInfo->AcquireLoc(pnode),
  6575. vars,
  6576. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6577. pnode->AsParseNodeCall()->pnodeTarget->location);
  6578. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6579. return actualArgCount;
  6580. }
  6581. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6582. {
  6583. Js::OpCode opcode;
  6584. if (!isRoot)
  6585. {
  6586. if (callObjLocation == funcInfo->frameObjRegister)
  6587. {
  6588. opcode = Js::OpCode::LdLocalMethodFld;
  6589. }
  6590. else
  6591. {
  6592. opcode = Js::OpCode::LdMethodFld;
  6593. }
  6594. }
  6595. else if (isScoped)
  6596. {
  6597. opcode = Js::OpCode::ScopedLdMethodFld;
  6598. }
  6599. else
  6600. {
  6601. opcode = Js::OpCode::LdRootMethodFld;
  6602. }
  6603. if (isScoped || !isRoot)
  6604. {
  6605. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6606. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6607. if (callObjLocation == funcInfo->frameObjRegister)
  6608. {
  6609. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6610. }
  6611. else
  6612. {
  6613. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6614. }
  6615. }
  6616. else
  6617. {
  6618. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6619. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6620. }
  6621. }
  6622. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6623. {
  6624. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6625. // the global object, etc.)
  6626. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6627. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6628. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6629. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6630. }
  6631. // lhs.apply(this, arguments);
  6632. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6633. {
  6634. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6635. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6636. Assert(applyNode->nop == knopDot);
  6637. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6638. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6639. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6640. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6641. Assert(applyNode->nop == knopDot);
  6642. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6643. funcInfo->AcquireLoc(applyNode);
  6644. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6645. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6646. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6647. // call for apply, we won't remove the entry for "apply" cacheId from
  6648. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6649. // have removed an entry from a map upon seeing its corresponding call.
  6650. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6651. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6652. Assert(argSym && argSym->IsArguments());
  6653. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6654. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6655. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6656. // If apply is overridden, bail to slow path.
  6657. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6658. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6659. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6660. // may crash if we try to unbox it on the store.
  6661. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6662. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6663. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6664. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6665. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6666. funcInfo->ReleaseTmpRegister(argCountLocation);
  6667. funcInfo->ReleaseTmpRegister(stackArgReg);
  6668. funcInfo->ReleaseLoc(applyNode);
  6669. funcInfo->ReleaseLoc(funcNode);
  6670. // Clear these nodes as they are going to be used to re-generate the slow path.
  6671. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6672. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6673. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6674. // slow path
  6675. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6676. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6677. {
  6678. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6679. }
  6680. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6681. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6682. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6683. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6684. }
  6685. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6686. {
  6687. // Load a call target of the form x[y]().
  6688. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6689. }
  6690. void EmitCallTargetNoEvalComponents(
  6691. ParseNode *pnodeTarget,
  6692. BOOL fSideEffectArgs,
  6693. Js::RegSlot *thisLocation,
  6694. bool *releaseThisLocation,
  6695. Js::RegSlot *callObjLocation,
  6696. ByteCodeGenerator *byteCodeGenerator,
  6697. FuncInfo *funcInfo)
  6698. {
  6699. // We first get a reference to the call target, then evaluate the arguments, then
  6700. // evaluate the call target.
  6701. // - emit reference to target
  6702. // - copy instance to scratch reg if necessary.
  6703. // - assign this
  6704. // - assign instance for dynamic/global name
  6705. // - emit args
  6706. // - do call (CallFld/Elem/I)
  6707. *releaseThisLocation = true;
  6708. switch (pnodeTarget->nop)
  6709. {
  6710. case knopDot:
  6711. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6712. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6713. break;
  6714. case knopIndex:
  6715. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6716. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6717. break;
  6718. case knopName:
  6719. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6720. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  6721. if (*thisLocation == Js::Constants::NoRegister)
  6722. {
  6723. *thisLocation = funcInfo->undefinedConstantRegister;
  6724. }
  6725. break;
  6726. default:
  6727. *thisLocation = funcInfo->undefinedConstantRegister;
  6728. break;
  6729. }
  6730. }
  6731. void EmitCallTarget(
  6732. ParseNode *pnodeTarget,
  6733. BOOL fSideEffectArgs,
  6734. Js::RegSlot *thisLocation,
  6735. bool *releaseThisLocation,
  6736. Js::RegSlot *callObjLocation,
  6737. ByteCodeGenerator *byteCodeGenerator,
  6738. FuncInfo *funcInfo)
  6739. {
  6740. // - emit target
  6741. // - assign this
  6742. // - emit args
  6743. // - do call
  6744. // The call target is fully evaluated before the argument list. Note that we're not handling
  6745. // put-call cases here currently, as such cases only apply to host objects
  6746. // and are very unlikely to behave differently depending on the order of evaluation.
  6747. *releaseThisLocation = true;
  6748. switch (pnodeTarget->nop)
  6749. {
  6750. case knopDot:
  6751. {
  6752. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  6753. funcInfo->AcquireLoc(pnodeBinTarget);
  6754. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6755. // them from side-effects.
  6756. if (fSideEffectArgs)
  6757. {
  6758. // Though we're done with target evaluation after this point, still protect opnd1 from
  6759. // arg side-effects as it's the "this" pointer.
  6760. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  6761. }
  6762. Assert(pnodeBinTarget->pnode2->nop == knopName);
  6763. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  6764. {
  6765. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  6766. }
  6767. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  6768. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6769. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  6770. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  6771. {
  6772. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6773. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6774. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  6775. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  6776. // Function calls on the 'super' object should maintain current 'this' pointer.
  6777. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6778. *releaseThisLocation = false;
  6779. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  6780. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld,
  6781. pnodeTarget->location, protoLocation, *thisLocation, cacheId, false);
  6782. }
  6783. else
  6784. {
  6785. *thisLocation = pnodeBinTarget->pnode1->location;
  6786. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6787. }
  6788. break;
  6789. }
  6790. case knopIndex:
  6791. {
  6792. funcInfo->AcquireLoc(pnodeTarget);
  6793. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6794. // them from side-effects.
  6795. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  6796. {
  6797. // Though we're done with target evaluation after this point, still protect opnd1 from
  6798. // arg or opnd2 side-effects as it's the "this" pointer.
  6799. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  6800. }
  6801. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  6802. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  6803. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  6804. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6805. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6806. {
  6807. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6808. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6809. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  6810. // Function calls on the 'super' object should maintain current 'this' pointer
  6811. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6812. *releaseThisLocation = false;
  6813. }
  6814. else
  6815. {
  6816. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6817. }
  6818. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6819. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  6820. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6821. {
  6822. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  6823. }
  6824. break;
  6825. }
  6826. case knopName:
  6827. {
  6828. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  6829. if (!pnodeNameTarget->IsSpecialName())
  6830. {
  6831. funcInfo->AcquireLoc(pnodeNameTarget);
  6832. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6833. // them from side-effects.
  6834. if (fSideEffectArgs)
  6835. {
  6836. SaveOpndValue(pnodeNameTarget, funcInfo);
  6837. }
  6838. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  6839. if (*callObjLocation != Js::Constants::NoRegister)
  6840. {
  6841. // Load the call target as a property of the instance.
  6842. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  6843. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6844. break;
  6845. }
  6846. }
  6847. // FALL THROUGH to evaluate call target.
  6848. }
  6849. default:
  6850. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6851. // them from side-effects.
  6852. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6853. *thisLocation = funcInfo->undefinedConstantRegister;
  6854. break;
  6855. }
  6856. // "This" pointer should have been assigned by the above.
  6857. Assert(*thisLocation != Js::Constants::NoRegister);
  6858. }
  6859. void EmitCallI(
  6860. ParseNodeCall *pnodeCall,
  6861. BOOL fEvaluateComponents,
  6862. BOOL fIsEval,
  6863. BOOL fHasNewTarget,
  6864. uint32 actualArgCount,
  6865. ByteCodeGenerator *byteCodeGenerator,
  6866. FuncInfo *funcInfo,
  6867. Js::ProfileId callSiteId,
  6868. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6869. {
  6870. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6871. // already evaluated.
  6872. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6873. Js::OpCode op;
  6874. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6875. uint spreadExtraAlloc = 0;
  6876. bool isSuperCall = pnodeCall->isSuperCall;
  6877. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6878. // check for integer overflow
  6879. if ((size_t)actualArgSlotCount != actualArgCount)
  6880. {
  6881. Js::Throw::OutOfMemory();
  6882. }
  6883. if (fEvaluateComponents && !isSuperCall)
  6884. {
  6885. // Release the call target operands we assigned above. If we didn't assign them here,
  6886. // we'll need them later, so we can't re-use them for the result of the call.
  6887. funcInfo->ReleaseLoc(pnodeTarget);
  6888. }
  6889. // Grab a register for the call result.
  6890. if (pnodeCall->isUsed)
  6891. {
  6892. funcInfo->AcquireLoc(pnodeCall);
  6893. }
  6894. if (fIsEval)
  6895. {
  6896. op = Js::OpCode::CallIExtendedFlags;
  6897. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6898. }
  6899. else
  6900. {
  6901. if (isSuperCall)
  6902. {
  6903. callFlags = Js::CallFlags_New;
  6904. }
  6905. if (fHasNewTarget)
  6906. {
  6907. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6908. }
  6909. if (pnodeCall->spreadArgCount > 0)
  6910. {
  6911. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6912. }
  6913. else
  6914. {
  6915. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6916. }
  6917. }
  6918. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6919. {
  6920. if (isSuperCall)
  6921. {
  6922. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6923. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  6924. }
  6925. else
  6926. {
  6927. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6928. }
  6929. }
  6930. else
  6931. {
  6932. uint spreadIndicesSize = 0;
  6933. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6934. if (pnodeCall->spreadArgCount > 0)
  6935. {
  6936. Assert(spreadIndices != nullptr);
  6937. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  6938. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  6939. options = Js::CallIExtended_SpreadArgs;
  6940. }
  6941. if (isSuperCall)
  6942. {
  6943. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6944. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6945. }
  6946. else
  6947. {
  6948. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6949. }
  6950. }
  6951. if (pnodeCall->spreadArgCount > 0)
  6952. {
  6953. Assert(spreadExtraAlloc != 0);
  6954. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6955. }
  6956. }
  6957. void EmitCallInstrNoEvalComponents(
  6958. ParseNodeCall *pnodeCall,
  6959. BOOL fIsEval,
  6960. Js::RegSlot thisLocation,
  6961. Js::RegSlot callObjLocation,
  6962. uint32 actualArgCount,
  6963. ByteCodeGenerator *byteCodeGenerator,
  6964. FuncInfo *funcInfo,
  6965. Js::ProfileId callSiteId,
  6966. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6967. {
  6968. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6969. // it as part of doing the actual call.
  6970. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6971. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6972. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6973. switch (pnodeTarget->nop)
  6974. {
  6975. case knopDot:
  6976. {
  6977. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  6978. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6979. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6980. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6981. }
  6982. break;
  6983. case knopIndex:
  6984. {
  6985. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  6986. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6987. }
  6988. break;
  6989. case knopName:
  6990. {
  6991. if (callObjLocation != Js::Constants::NoRegister)
  6992. {
  6993. // We still have to get the property from its instance, so emit CallFld.
  6994. if (thisLocation != callObjLocation)
  6995. {
  6996. funcInfo->ReleaseTmpRegister(thisLocation);
  6997. }
  6998. funcInfo->ReleaseTmpRegister(callObjLocation);
  6999. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  7000. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7001. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7002. break;
  7003. }
  7004. }
  7005. // FALL THROUGH
  7006. default:
  7007. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7008. break;
  7009. }
  7010. }
  7011. void EmitCallInstr(
  7012. ParseNodeCall *pnodeCall,
  7013. BOOL fIsEval,
  7014. BOOL fHasNewTarget,
  7015. Js::RegSlot thisLocation,
  7016. Js::RegSlot callObjLocation,
  7017. uint32 actualArgCount,
  7018. ByteCodeGenerator *byteCodeGenerator,
  7019. FuncInfo *funcInfo,
  7020. Js::ProfileId callSiteId,
  7021. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7022. {
  7023. // Emit a call instruction. The call target has been fully evaluated already, so we always
  7024. // emit a CallI through the register that holds the target value.
  7025. // Note that we don't handle !fEvaluateComponents cases at this point.
  7026. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  7027. if (thisLocation != Js::Constants::NoRegister)
  7028. {
  7029. funcInfo->ReleaseTmpRegister(thisLocation);
  7030. }
  7031. if (callObjLocation != Js::Constants::NoRegister &&
  7032. callObjLocation != thisLocation)
  7033. {
  7034. funcInfo->ReleaseTmpRegister(callObjLocation);
  7035. }
  7036. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7037. }
  7038. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7039. {
  7040. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  7041. argCount++; // include "this"
  7042. BOOL fSideEffectArgs = FALSE;
  7043. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  7044. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  7045. byteCodeGenerator->StartStatement(pnode);
  7046. // Start call, allocate out param space
  7047. funcInfo->StartRecordingOutArgs(argCount);
  7048. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7049. // them from side-effects.
  7050. if (fSideEffectArgs)
  7051. {
  7052. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  7053. }
  7054. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  7055. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  7056. {
  7057. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7058. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  7059. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  7060. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  7061. Assert(argCount == 1);
  7062. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7063. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7064. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  7065. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  7066. }
  7067. else
  7068. {
  7069. uint32 actualArgCount = 0;
  7070. if (IsCallOfConstants(pnode))
  7071. {
  7072. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7073. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7074. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  7075. }
  7076. else
  7077. {
  7078. Js::OpCode op;
  7079. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  7080. {
  7081. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  7082. }
  7083. else
  7084. {
  7085. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  7086. }
  7087. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7088. // Only emit profiled argouts if we're going to profile this call.
  7089. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7090. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7091. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7092. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, pnode->AsParseNodeCall()->hasDestructuring, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  7093. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7094. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  7095. {
  7096. Assert(spreadIndices != nullptr);
  7097. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7098. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7099. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7100. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7101. spreadIndices, spreadIndicesSize, callSiteId);
  7102. }
  7103. else
  7104. {
  7105. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7106. (uint16)actualArgCount, callSiteId);
  7107. }
  7108. }
  7109. Assert(argCount == actualArgCount);
  7110. }
  7111. // End call, pop param space
  7112. funcInfo->EndRecordingOutArgs(argCount);
  7113. return;
  7114. }
  7115. void EmitCall(
  7116. ParseNodeCall * pnodeCall,
  7117. ByteCodeGenerator* byteCodeGenerator,
  7118. FuncInfo* funcInfo,
  7119. BOOL fReturnValue,
  7120. BOOL fEvaluateComponents,
  7121. Js::RegSlot overrideThisLocation,
  7122. Js::RegSlot newTargetLocation)
  7123. {
  7124. // If the call returns a float, we'll note this in the byte code.
  7125. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7126. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7127. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7128. BOOL fSideEffectArgs = FALSE;
  7129. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7130. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7131. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7132. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7133. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7134. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7135. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7136. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7137. // "new" path, since then our native array handling can kick in.
  7138. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7139. return;*/
  7140. }
  7141. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7142. BOOL fIsEval = pnodeCall->isEvalCall;
  7143. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7144. if (fIsEval)
  7145. {
  7146. Assert(!fHasNewTarget);
  7147. //
  7148. // "eval" takes the closure environment as an extra argument
  7149. // Pass the closure env only if some argument is passed
  7150. // For just eval(), don't pass the closure environment
  7151. //
  7152. if (argCount > 1)
  7153. {
  7154. argCount++;
  7155. }
  7156. }
  7157. else if (fHasNewTarget)
  7158. {
  7159. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7160. // This is similar to how eval passes an extra argument for the frame display and is
  7161. // used to support cases where we need to pass both 'this' and new.target as part of
  7162. // a function call.
  7163. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7164. argCount++;
  7165. }
  7166. // argCount indicates the total arguments count including the extra arguments.
  7167. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7168. if (argCount < (unsigned int)argSlotCount)
  7169. {
  7170. Js::Throw::OutOfMemory();
  7171. }
  7172. if (fReturnValue)
  7173. {
  7174. pnodeCall->isUsed = true;
  7175. }
  7176. //
  7177. // Set up the call.
  7178. //
  7179. bool releaseThisLocation = true;
  7180. // We already emit the call target for super calls in EmitSuperCall
  7181. if (!fIsSuperCall)
  7182. {
  7183. if (!fEvaluateComponents)
  7184. {
  7185. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7186. }
  7187. else
  7188. {
  7189. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7190. }
  7191. }
  7192. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7193. if (overrideThisLocation != Js::Constants::NoRegister)
  7194. {
  7195. thisLocation = overrideThisLocation;
  7196. releaseThisLocation = false;
  7197. }
  7198. // Evaluate the arguments (nothing mode-specific here).
  7199. // Start call, allocate out param space
  7200. // 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
  7201. funcInfo->StartRecordingOutArgs(argCount);
  7202. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7203. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7204. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7205. Js::AuxArray<uint32> *spreadIndices;
  7206. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, pnodeCall->hasDestructuring, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7207. if (!fEvaluateComponents)
  7208. {
  7209. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7210. }
  7211. else
  7212. {
  7213. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7214. }
  7215. // End call, pop param space
  7216. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7217. }
  7218. void EmitInvoke(
  7219. Js::RegSlot location,
  7220. Js::RegSlot callObjLocation,
  7221. Js::PropertyId propertyId,
  7222. ByteCodeGenerator* byteCodeGenerator,
  7223. FuncInfo* funcInfo)
  7224. {
  7225. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7226. funcInfo->StartRecordingOutArgs(1);
  7227. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7228. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7229. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7230. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7231. }
  7232. void EmitInvoke(
  7233. Js::RegSlot location,
  7234. Js::RegSlot callObjLocation,
  7235. Js::PropertyId propertyId,
  7236. ByteCodeGenerator* byteCodeGenerator,
  7237. FuncInfo* funcInfo,
  7238. Js::RegSlot arg1Location)
  7239. {
  7240. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7241. funcInfo->StartRecordingOutArgs(2);
  7242. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7243. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7244. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7245. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7246. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7247. }
  7248. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNodeFnc *exprNode, ByteCodeGenerator *byteCodeGenerator)
  7249. {
  7250. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  7251. Assert(exprNode->HasComputedName());
  7252. if (nameNode == nullptr)
  7253. {
  7254. return;
  7255. }
  7256. if (exprNode->pnodeName == nullptr)
  7257. {
  7258. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  7259. }
  7260. }
  7261. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7262. {
  7263. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7264. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7265. bool isFncDecl = exprNode->nop == knopFncDecl;
  7266. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7267. if (isFncDecl)
  7268. {
  7269. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7270. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7271. }
  7272. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7273. // which makes this bytecode too late to influence the function.name.
  7274. if (nameNode->nop == knopComputedName)
  7275. {
  7276. // Computed property name
  7277. // Transparently pass the name expr
  7278. // The Emit will replace this with a temp register if necessary to preserve the value.
  7279. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7280. // Save the previous value of the flag to be restored later.
  7281. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7282. // Strict mode must be enforced on the evaluation of computed property names inside
  7283. // classes, thus enable the flag if the computed property name is a class member.
  7284. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7285. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  7286. // Restore the flag's previous value.
  7287. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7288. if (isFncDecl && !exprNode->AsParseNodeFnc()->IsClassConstructor())
  7289. {
  7290. EmitComputedFunctionNameVar(nameNode, exprNode->AsParseNodeFnc(), byteCodeGenerator);
  7291. }
  7292. }
  7293. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  7294. // but if we don't have any members then we don't need to load the prototype.
  7295. Assert(isClassMember == (isObjectEmpty != nullptr));
  7296. if (isClassMember && *isObjectEmpty)
  7297. {
  7298. *isObjectEmpty = false;
  7299. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  7300. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  7301. }
  7302. if (nameNode->nop == knopComputedName)
  7303. {
  7304. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7305. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7306. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7307. memberNode->nop == knopSetMember ?
  7308. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7309. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7310. // Save the previous value of the flag to be restored later.
  7311. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7312. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7313. // Strict mode must be enforced on the evaluation of computed property names inside
  7314. // classes, thus enable the flag if the computed property name is a class member.
  7315. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true,
  7316. byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  7317. // Restore the flag's previous value.
  7318. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7319. funcInfo->ReleaseLoc(exprNode);
  7320. funcInfo->ReleaseLoc(nameNode);
  7321. return;
  7322. }
  7323. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7324. if (useStore)
  7325. {
  7326. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7327. }
  7328. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7329. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7330. if (Js::PropertyIds::name == propertyId
  7331. && exprNode->nop == knopFncDecl
  7332. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7333. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7334. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7335. {
  7336. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7337. nameFunc->SetIsStaticNameFunction(true);
  7338. }
  7339. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7340. {
  7341. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7342. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7343. {
  7344. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7345. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7346. }
  7347. else
  7348. {
  7349. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7350. Js::OpCode patchablePropertyOpCode;
  7351. if (useStore)
  7352. {
  7353. patchablePropertyOpCode = stFldOpCode;
  7354. }
  7355. else if (isClassMember)
  7356. {
  7357. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7358. }
  7359. else
  7360. {
  7361. patchablePropertyOpCode = Js::OpCode::InitFld;
  7362. }
  7363. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7364. }
  7365. }
  7366. else
  7367. {
  7368. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7369. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7370. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7371. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7372. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7373. }
  7374. funcInfo->ReleaseLoc(exprNode);
  7375. if (propertyId == Js::PropertyIds::valueOf)
  7376. {
  7377. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7378. }
  7379. else if (propertyId == Js::PropertyIds::toString)
  7380. {
  7381. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7382. }
  7383. }
  7384. void EmitObjectSpreadNode(ParseNode *spreadNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7385. {
  7386. Js::RegSlot fromObjectLocation;
  7387. ParseNode *exprNode = spreadNode->AsParseNodeUni()->pnode1;
  7388. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7389. fromObjectLocation = exprNode->location;
  7390. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SpreadObjectLiteral, fromObjectLocation, objectLocation);
  7391. funcInfo->ReleaseLoc(exprNode);
  7392. }
  7393. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7394. {
  7395. if (memberList != nullptr)
  7396. {
  7397. while (memberList->nop == knopList)
  7398. {
  7399. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7400. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7401. memberList = memberList->AsParseNodeBin()->pnode2;
  7402. }
  7403. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7404. }
  7405. }
  7406. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7407. {
  7408. ParseNode *pmemberList = memberList;
  7409. unsigned int argCount = 0;
  7410. uint32 value;
  7411. Js::PropertyId propertyId;
  7412. //
  7413. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7414. // 2. Get the count of propertyIds
  7415. // 3. Create a propertyId array of size count
  7416. // 4. Put the propIds in the auxiliary area
  7417. // 5. Get the objectLiteralCacheId
  7418. // 6. Generate propId inits with values
  7419. //
  7420. // Handle propertyId collision
  7421. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7422. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7423. bool hasComputedNameOrSpread = false;
  7424. if (memberList != nullptr)
  7425. {
  7426. while (memberList->nop == knopList)
  7427. {
  7428. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7429. {
  7430. hasComputedNameOrSpread = true;
  7431. break;
  7432. }
  7433. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7434. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7435. {
  7436. propertyIds->Item(propertyId);
  7437. }
  7438. memberList = memberList->AsParseNodeBin()->pnode2;
  7439. }
  7440. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7441. {
  7442. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7443. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7444. {
  7445. propertyIds->Item(propertyId);
  7446. }
  7447. }
  7448. }
  7449. argCount = propertyIds->Count();
  7450. memberList = pmemberList;
  7451. if ((memberList == nullptr) || (argCount == 0))
  7452. {
  7453. // Empty literal or numeric property only object literal
  7454. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7455. }
  7456. else
  7457. {
  7458. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7459. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7460. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7461. {
  7462. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7463. // or not, in case the bytecode is later run with __proto__ enabled.
  7464. propIds->has__proto__ = true;
  7465. }
  7466. unsigned int argIndex = 0;
  7467. while (memberList->nop == knopList)
  7468. {
  7469. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7470. {
  7471. break;
  7472. }
  7473. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7474. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7475. {
  7476. propIds->elements[argIndex] = propertyId;
  7477. argIndex++;
  7478. }
  7479. memberList = memberList->AsParseNodeBin()->pnode2;
  7480. }
  7481. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7482. {
  7483. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7484. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7485. {
  7486. propIds->elements[argIndex] = propertyId;
  7487. argIndex++;
  7488. }
  7489. }
  7490. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7491. // Generate the opcode with propIds and cacheId
  7492. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7493. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7494. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7495. }
  7496. memberList = pmemberList;
  7497. bool useStore = false;
  7498. // Generate the actual assignment to those properties
  7499. if (memberList != nullptr)
  7500. {
  7501. while (memberList->nop == knopList)
  7502. {
  7503. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7504. if (memberNode->nop == knopEllipsis)
  7505. {
  7506. byteCodeGenerator->StartSubexpression(memberNode);
  7507. EmitObjectSpreadNode(memberNode, objectLocation, byteCodeGenerator, funcInfo);
  7508. byteCodeGenerator->EndSubexpression(memberNode);
  7509. }
  7510. else
  7511. {
  7512. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7513. {
  7514. useStore = true;
  7515. }
  7516. byteCodeGenerator->StartSubexpression(memberNode);
  7517. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7518. byteCodeGenerator->EndSubexpression(memberNode);
  7519. }
  7520. memberList = memberList->AsParseNodeBin()->pnode2;
  7521. }
  7522. byteCodeGenerator->StartSubexpression(memberList);
  7523. if (memberList->nop == knopEllipsis)
  7524. {
  7525. EmitObjectSpreadNode(memberList, objectLocation, byteCodeGenerator, funcInfo);
  7526. }
  7527. else
  7528. {
  7529. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7530. }
  7531. byteCodeGenerator->EndSubexpression(memberList);
  7532. }
  7533. }
  7534. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7535. {
  7536. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7537. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7538. // We only need to emit code for non-tagged string templates here.
  7539. if (!pnodeStrTemplate->isTaggedTemplate)
  7540. {
  7541. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7542. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7543. {
  7544. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7545. funcInfo->AcquireLoc(pnodeStrTemplate);
  7546. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7547. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7548. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7549. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7550. }
  7551. else
  7552. {
  7553. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7554. funcInfo->AcquireLoc(pnodeStrTemplate);
  7555. // First string must be a list node since we have substitutions.
  7556. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7557. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7558. // Emit the first string and load that into the pnode location.
  7559. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7560. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7561. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7562. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7563. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7564. ParseNode* stringNode;
  7565. ParseNode* expressionNode;
  7566. // Now append the substitution expressions and remaining string constants via normal add operator
  7567. // We will always have one more string constant than substitution expression
  7568. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7569. //
  7570. // strcon1 --- step 1 (above)
  7571. // expr1 \__ step 2
  7572. // strcon2 /
  7573. // expr2 \__ step 3
  7574. // strcon3 /
  7575. while (stringNodeList->nop == knopList)
  7576. {
  7577. // If the current head of the expression list is a list, fetch the node and walk the list.
  7578. if (expressionNodeList->nop == knopList)
  7579. {
  7580. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7581. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7582. }
  7583. else
  7584. {
  7585. // This is the last element of the expression list.
  7586. expressionNode = expressionNodeList;
  7587. }
  7588. // Emit the expression and append it to the string we're building.
  7589. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7590. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7591. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7592. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7593. funcInfo->ReleaseTmpRegister(toStringLocation);
  7594. funcInfo->ReleaseLoc(expressionNode);
  7595. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7596. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7597. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7598. if (stringNodeList->nop == knopList)
  7599. {
  7600. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7601. }
  7602. else
  7603. {
  7604. // This is the last element of the string literal list.
  7605. stringNode = stringNodeList;
  7606. }
  7607. // Emit the string node following the previous expression and append it to the string.
  7608. // This is either just some string in the list or it is the last string.
  7609. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7610. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7611. funcInfo->ReleaseLoc(stringNode);
  7612. }
  7613. }
  7614. }
  7615. }
  7616. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7617. {
  7618. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7619. uint argCount = pnode->AsParseNodeArrLit()->count;
  7620. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7621. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7622. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7623. if (arrayIntOpt)
  7624. {
  7625. int extraAlloc = 0, auxSize = 0;
  7626. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7627. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7628. {
  7629. ::Math::DefaultOverflowPolicy();
  7630. }
  7631. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7632. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7633. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7634. byteCodeGenerator->Writer()->Auxiliary(
  7635. Js::OpCode::NewScIntArray,
  7636. pnode->location,
  7637. ints,
  7638. auxSize,
  7639. argCount);
  7640. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7641. return;
  7642. }
  7643. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7644. if (arrayNumOpt)
  7645. {
  7646. int extraAlloc = 0, auxSize = 0;
  7647. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7648. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7649. {
  7650. ::Math::DefaultOverflowPolicy();
  7651. }
  7652. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7653. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7654. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7655. byteCodeGenerator->Writer()->Auxiliary(
  7656. Js::OpCode::NewScFltArray,
  7657. pnode->location,
  7658. doubles,
  7659. auxSize,
  7660. argCount);
  7661. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7662. return;
  7663. }
  7664. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7665. Assert(!arrayLitOpt || !nativeArrays);
  7666. Js::RegSlot spreadArrLoc = arrayLocation;
  7667. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7668. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7669. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7670. {
  7671. arrayLocation = funcInfo->AcquireTmpRegister();
  7672. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7673. }
  7674. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7675. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7676. arrayLocation,
  7677. argCount);
  7678. if (args != nullptr)
  7679. {
  7680. Js::OpCode opcode;
  7681. Js::RegSlot arrLoc;
  7682. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7683. {
  7684. opcode = Js::OpCode::StArrItemC_CI4;
  7685. arrLoc = arrayLocation;
  7686. }
  7687. else if (arrayLitOpt)
  7688. {
  7689. opcode = Js::OpCode::StArrSegItem_A;
  7690. arrLoc = funcInfo->AcquireTmpRegister();
  7691. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7692. }
  7693. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7694. {
  7695. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7696. // should be done relative to the array header to keep it alive (instead of the array segment).
  7697. opcode = Js::OpCode::StArrInlineItem_CI4;
  7698. arrLoc = arrayLocation;
  7699. }
  7700. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7701. {
  7702. opcode = Js::OpCode::StArrSegItem_CI4;
  7703. arrLoc = funcInfo->AcquireTmpRegister();
  7704. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7705. }
  7706. else
  7707. {
  7708. opcode = Js::OpCode::StArrItemI_CI4;
  7709. arrLoc = arrayLocation;
  7710. }
  7711. if (arrayLitOpt)
  7712. {
  7713. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  7714. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  7715. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7716. // Generate the opcode with vars
  7717. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  7718. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  7719. }
  7720. else
  7721. {
  7722. uint i = 0;
  7723. unsigned spreadIndex = 0;
  7724. Js::RegSlot rhsLocation;
  7725. while (args->nop == knopList)
  7726. {
  7727. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  7728. {
  7729. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7730. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  7731. Js::RegSlot regVal = rhsLocation;
  7732. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7733. {
  7734. AnalysisAssert(spreadIndices);
  7735. regVal = funcInfo->AcquireTmpRegister();
  7736. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7737. spreadIndices->elements[spreadIndex++] = i;
  7738. }
  7739. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7740. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7741. {
  7742. funcInfo->ReleaseTmpRegister(regVal);
  7743. }
  7744. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  7745. }
  7746. args = args->AsParseNodeBin()->pnode2;
  7747. i++;
  7748. }
  7749. if (args->nop != knopEmpty)
  7750. {
  7751. Emit(args, byteCodeGenerator, funcInfo, false);
  7752. rhsLocation = args->location;
  7753. Js::RegSlot regVal = rhsLocation;
  7754. if (args->nop == knopEllipsis)
  7755. {
  7756. regVal = funcInfo->AcquireTmpRegister();
  7757. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7758. AnalysisAssert(spreadIndices);
  7759. spreadIndices->elements[spreadIndex] = i;
  7760. }
  7761. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7762. if (args->nop == knopEllipsis)
  7763. {
  7764. funcInfo->ReleaseTmpRegister(regVal);
  7765. }
  7766. funcInfo->ReleaseLoc(args);
  7767. i++;
  7768. }
  7769. Assert(i <= argCount);
  7770. }
  7771. if (arrLoc != arrayLocation)
  7772. {
  7773. funcInfo->ReleaseTmpRegister(arrLoc);
  7774. }
  7775. }
  7776. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7777. {
  7778. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  7779. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7780. funcInfo->ReleaseTmpRegister(arrayLocation);
  7781. }
  7782. }
  7783. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7784. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7785. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7786. // with special case for single-branch style.
  7787. void EmitBooleanExpression(
  7788. _In_ ParseNode* expr,
  7789. Js::ByteCodeLabel trueLabel,
  7790. Js::ByteCodeLabel falseLabel,
  7791. _In_ ByteCodeGenerator* byteCodeGenerator,
  7792. _In_ FuncInfo* funcInfo,
  7793. bool trueFallthrough,
  7794. bool falseFallthrough)
  7795. {
  7796. Assert(!trueFallthrough || !falseFallthrough);
  7797. byteCodeGenerator->StartStatement(expr);
  7798. switch (expr->nop)
  7799. {
  7800. case knopLogOr:
  7801. {
  7802. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7803. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  7804. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7805. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7806. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7807. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7808. break;
  7809. }
  7810. case knopLogAnd:
  7811. {
  7812. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7813. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  7814. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7815. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7816. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7817. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7818. break;
  7819. }
  7820. case knopLogNot:
  7821. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  7822. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7823. break;
  7824. case knopEq:
  7825. case knopEqv:
  7826. case knopNEqv:
  7827. case knopNe:
  7828. case knopLt:
  7829. case knopLe:
  7830. case knopGe:
  7831. case knopGt:
  7832. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7833. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7834. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7835. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  7836. expr->AsParseNodeBin()->pnode2->location);
  7837. if (!falseFallthrough)
  7838. {
  7839. byteCodeGenerator->Writer()->Br(falseLabel);
  7840. }
  7841. break;
  7842. case knopTrue:
  7843. if (!trueFallthrough)
  7844. {
  7845. byteCodeGenerator->Writer()->Br(trueLabel);
  7846. }
  7847. break;
  7848. case knopFalse:
  7849. if (!falseFallthrough)
  7850. {
  7851. byteCodeGenerator->Writer()->Br(falseLabel);
  7852. }
  7853. break;
  7854. default:
  7855. // Note: we usually release the temp assigned to a node after we Emit it.
  7856. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7857. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7858. Emit(expr, byteCodeGenerator, funcInfo, false);
  7859. if (trueFallthrough)
  7860. {
  7861. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7862. }
  7863. else
  7864. {
  7865. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7866. if (!falseFallthrough)
  7867. {
  7868. byteCodeGenerator->Writer()->Br(falseLabel);
  7869. }
  7870. }
  7871. break;
  7872. }
  7873. byteCodeGenerator->EndStatement(expr);
  7874. }
  7875. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  7876. ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7877. {
  7878. switch (expr->nop)
  7879. {
  7880. case knopLogOr:
  7881. {
  7882. byteCodeGenerator->StartStatement(expr);
  7883. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7884. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, byteCodeGenerator, funcInfo);
  7885. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7886. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7887. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7888. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7889. byteCodeGenerator->EndStatement(expr);
  7890. break;
  7891. }
  7892. case knopLogAnd:
  7893. {
  7894. byteCodeGenerator->StartStatement(expr);
  7895. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7896. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, byteCodeGenerator, funcInfo);
  7897. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7898. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7899. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7900. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7901. byteCodeGenerator->EndStatement(expr);
  7902. break;
  7903. }
  7904. case knopLogNot:
  7905. {
  7906. byteCodeGenerator->StartStatement(expr);
  7907. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  7908. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  7909. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  7910. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  7911. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  7912. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7913. byteCodeGenerator->Writer()->Br(trueLabel);
  7914. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  7915. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7916. if (!falsefallthrough)
  7917. {
  7918. byteCodeGenerator->Writer()->Br(falseLabel);
  7919. }
  7920. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7921. byteCodeGenerator->EndStatement(expr);
  7922. break;
  7923. }
  7924. case knopEq:
  7925. case knopEqv:
  7926. case knopNEqv:
  7927. case knopNe:
  7928. case knopLt:
  7929. case knopLe:
  7930. case knopGe:
  7931. case knopGt:
  7932. byteCodeGenerator->StartStatement(expr);
  7933. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7934. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7935. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7936. funcInfo->AcquireLoc(expr);
  7937. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  7938. expr->AsParseNodeBin()->pnode2->location);
  7939. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7940. // The inliner likes small bytecode
  7941. if (!(truefallthrough || falsefallthrough))
  7942. {
  7943. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7944. byteCodeGenerator->Writer()->Br(falseLabel);
  7945. }
  7946. else if (truefallthrough && !falsefallthrough) {
  7947. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7948. }
  7949. else if (falsefallthrough && !truefallthrough) {
  7950. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7951. }
  7952. byteCodeGenerator->EndStatement(expr);
  7953. break;
  7954. case knopTrue:
  7955. byteCodeGenerator->StartStatement(expr);
  7956. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7957. if (!truefallthrough)
  7958. {
  7959. byteCodeGenerator->Writer()->Br(trueLabel);
  7960. }
  7961. byteCodeGenerator->EndStatement(expr);
  7962. break;
  7963. case knopFalse:
  7964. byteCodeGenerator->StartStatement(expr);
  7965. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7966. if (!falsefallthrough)
  7967. {
  7968. byteCodeGenerator->Writer()->Br(falseLabel);
  7969. }
  7970. byteCodeGenerator->EndStatement(expr);
  7971. break;
  7972. default:
  7973. // Note: we usually release the temp assigned to a node after we Emit it.
  7974. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7975. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7976. // For diagnostics purposes, register the name and dot to the statement list.
  7977. if (expr->nop == knopName || expr->nop == knopDot)
  7978. {
  7979. byteCodeGenerator->StartStatement(expr);
  7980. Emit(expr, byteCodeGenerator, funcInfo, false);
  7981. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7982. // The inliner likes small bytecode
  7983. if (!(truefallthrough || falsefallthrough))
  7984. {
  7985. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7986. byteCodeGenerator->Writer()->Br(falseLabel);
  7987. }
  7988. else if (truefallthrough && !falsefallthrough) {
  7989. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7990. }
  7991. else if (falsefallthrough && !truefallthrough) {
  7992. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7993. }
  7994. byteCodeGenerator->EndStatement(expr);
  7995. }
  7996. else
  7997. {
  7998. Emit(expr, byteCodeGenerator, funcInfo, false);
  7999. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  8000. // The inliner likes small bytecode
  8001. if (!(truefallthrough || falsefallthrough))
  8002. {
  8003. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8004. byteCodeGenerator->Writer()->Br(falseLabel);
  8005. }
  8006. else if (truefallthrough && !falsefallthrough) {
  8007. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8008. }
  8009. else if (falsefallthrough && !truefallthrough) {
  8010. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8011. }
  8012. }
  8013. break;
  8014. }
  8015. }
  8016. // used by while and for loops
  8017. void EmitLoop(
  8018. ParseNodeLoop *loopNode,
  8019. ParseNode *cond,
  8020. ParseNode *body,
  8021. ParseNode *incr,
  8022. ByteCodeGenerator *byteCodeGenerator,
  8023. FuncInfo *funcInfo,
  8024. BOOL fReturnValue,
  8025. BOOL doWhile = FALSE,
  8026. ParseNodeBlock *forLoopBlock = nullptr)
  8027. {
  8028. // Need to increment loop count whether we are going to profile or not for HasLoop()
  8029. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8030. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8031. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8032. loopNode->loopId = loopId;
  8033. if (doWhile)
  8034. {
  8035. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8036. funcInfo->ReleaseLoc(body);
  8037. if (loopNode->emitLabels)
  8038. {
  8039. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8040. }
  8041. if (!ByteCodeGenerator::IsFalse(cond) ||
  8042. byteCodeGenerator->IsInDebugMode())
  8043. {
  8044. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  8045. }
  8046. funcInfo->ReleaseLoc(cond);
  8047. }
  8048. else
  8049. {
  8050. if (cond)
  8051. {
  8052. if (!(cond->nop == knopInt &&
  8053. cond->AsParseNodeInt()->lw != 0))
  8054. {
  8055. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8056. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  8057. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8058. }
  8059. funcInfo->ReleaseLoc(cond);
  8060. }
  8061. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8062. funcInfo->ReleaseLoc(body);
  8063. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8064. forLoopBlock != nullptr)
  8065. {
  8066. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  8067. }
  8068. if (loopNode->emitLabels)
  8069. {
  8070. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8071. }
  8072. if (incr != nullptr)
  8073. {
  8074. Emit(incr, byteCodeGenerator, funcInfo, false);
  8075. funcInfo->ReleaseLoc(incr);
  8076. }
  8077. byteCodeGenerator->Writer()->Br(loopEntrance);
  8078. }
  8079. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8080. if (loopNode->emitLabels)
  8081. {
  8082. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8083. }
  8084. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8085. }
  8086. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeLoop* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  8087. {
  8088. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  8089. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  8090. // emit branch around original
  8091. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  8092. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  8093. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  8094. // emit original
  8095. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  8096. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  8097. // clear temporary registers since inverted loop may share nodes with
  8098. // emitted original loop
  8099. VisitClearTmpRegs(outerLoop, this, funcInfo);
  8100. // emit branch around inverted
  8101. this->m_writer.Br(afterInvertedLoop);
  8102. this->m_writer.MarkLabel(invertedLoopLabel);
  8103. // Emit a zero trip test for the original outer-loop if the outer-loop
  8104. // has a condition
  8105. if (outerLoop->AsParseNodeFor()->pnodeCond)
  8106. {
  8107. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  8108. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  8109. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  8110. this->m_writer.MarkLabel(zeroTrip);
  8111. funcInfo->ReleaseLoc(testNode);
  8112. }
  8113. // emit inverted
  8114. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  8115. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  8116. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  8117. invertedLoop->pnodeIncr, this, funcInfo, false);
  8118. this->m_writer.MarkLabel(afterInvertedLoop);
  8119. }
  8120. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8121. {
  8122. // get iterator object from the iterable
  8123. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  8124. // throw TypeError if the result is not an object
  8125. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8126. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  8127. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8128. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8129. }
  8130. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8131. {
  8132. // invoke next() on the iterator
  8133. if (nextInputLocation == Js::Constants::NoRegister)
  8134. {
  8135. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  8136. }
  8137. else
  8138. {
  8139. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  8140. }
  8141. // throw TypeError if the result is not an object
  8142. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8143. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  8144. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8145. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8146. }
  8147. // Generating
  8148. // if (hasReturnFunction) {
  8149. // value = Call Retrun;
  8150. // if (value != Object)
  8151. // throw TypeError;
  8152. // }
  8153. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8154. {
  8155. Js::RegSlot returnLocation = funcInfo->AcquireTmpRegister();
  8156. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8157. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8158. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorLocation, Js::PropertyIds::return_, false, false);
  8159. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, returnLocation, iteratorLocation, cacheId);
  8160. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, noReturn, returnLocation, funcInfo->undefinedConstantRegister);
  8161. EmitInvoke(returnLocation, iteratorLocation, Js::PropertyIds::return_, byteCodeGenerator, funcInfo);
  8162. // throw TypeError if the result is not an Object
  8163. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, returnLocation);
  8164. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8165. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8166. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8167. funcInfo->ReleaseTmpRegister(returnLocation);
  8168. }
  8169. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8170. {
  8171. // get the iterator result's "done" property
  8172. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  8173. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  8174. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  8175. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  8176. }
  8177. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8178. {
  8179. // get the iterator result's "value" property
  8180. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  8181. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  8182. }
  8183. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8184. Js::ByteCodeLabel loopEntrance,
  8185. Js::ByteCodeLabel continuePastLoop,
  8186. ByteCodeGenerator *byteCodeGenerator,
  8187. FuncInfo *funcInfo,
  8188. BOOL fReturnValue)
  8189. {
  8190. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8191. loopNode->pnodeLval->nop != knopLetDecl &&
  8192. loopNode->pnodeLval->nop != knopConstDecl)
  8193. {
  8194. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8195. }
  8196. else
  8197. {
  8198. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8199. sym->SetNeedDeclaration(false);
  8200. }
  8201. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8202. {
  8203. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8204. }
  8205. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8206. // The StartStatement is already done in the caller of this function.
  8207. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8208. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8209. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8210. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8211. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8212. {
  8213. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8214. }
  8215. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8216. if (loopNode->emitLabels)
  8217. {
  8218. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8219. }
  8220. byteCodeGenerator->Writer()->Br(loopEntrance);
  8221. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8222. if (loopNode->emitLabels)
  8223. {
  8224. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8225. }
  8226. }
  8227. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8228. Js::ByteCodeLabel loopEntrance,
  8229. Js::ByteCodeLabel continuePastLoop,
  8230. ByteCodeGenerator *byteCodeGenerator,
  8231. FuncInfo *funcInfo,
  8232. BOOL fReturnValue)
  8233. {
  8234. Assert(loopNode->nop == knopForIn);
  8235. Assert(loopNode->location == Js::Constants::NoRegister);
  8236. // Grab registers for the enumerator and for the current enumerated item.
  8237. // The enumerator register will be released after this call returns.
  8238. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8239. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8240. // get enumerator from the collection
  8241. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8242. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8243. byteCodeGenerator->EndStatement(loopNode);
  8244. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8245. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8246. loopNode->loopId = loopId;
  8247. // The EndStatement will happen in the EmitForInOfLoopBody function
  8248. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8249. // branch past loop when MoveAndGetNext returns nullptr
  8250. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8251. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8252. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8253. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8254. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8255. {
  8256. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8257. }
  8258. }
  8259. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8260. {
  8261. bool isForIn = (loopNode->nop == knopForIn);
  8262. Assert(isForIn || loopNode->nop == knopForOf);
  8263. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8264. byteCodeGenerator->StartStatement(loopNode);
  8265. if (!isForIn)
  8266. {
  8267. funcInfo->AcquireLoc(loopNode);
  8268. }
  8269. // Record the branch bytecode offset.
  8270. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8271. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8272. // otherwise use offset of next stmt.
  8273. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8274. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8275. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8276. // See WinBlue 231880 for details.
  8277. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8278. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8279. loopNode->pnodeBlock->HasBlockScopedContent())
  8280. {
  8281. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8282. }
  8283. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8284. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8285. if (loopNode->pnodeLval->nop == knopVarDecl)
  8286. {
  8287. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8288. }
  8289. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8290. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8291. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8292. {
  8293. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8294. if (loopNode->pnodeBlock->scope != nullptr)
  8295. {
  8296. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8297. sym->SetIsTrackedForDebugger(false);
  8298. });
  8299. }
  8300. }
  8301. if (isForIn)
  8302. {
  8303. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8304. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8305. {
  8306. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8307. }
  8308. return;
  8309. }
  8310. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8311. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8312. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8313. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8314. Js::RegSlot regException = Js::Constants::NoRegister;
  8315. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8316. // These two temp variables store the information of return function to be called or not.
  8317. // one variable is used for catch block and one is used for finally block. These variable will be set to true when we think that return function
  8318. // to be called on abrupt loop break.
  8319. // Why two variables? since these are temps and JIT does like not flow if single variable is used in multiple blocks.
  8320. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  8321. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  8322. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8323. if (isCoroutine)
  8324. {
  8325. regException = funcInfo->AcquireTmpRegister();
  8326. regOffset = funcInfo->AcquireTmpRegister();
  8327. }
  8328. // Grab registers for the enumerator and for the current enumerated item.
  8329. // The enumerator register will be released after this call returns.
  8330. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8331. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8332. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8333. // to the profiler and JIT.
  8334. byteCodeGenerator->SetHasFinally(true);
  8335. byteCodeGenerator->SetHasTry(true);
  8336. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8337. // do a ToObject on the collection
  8338. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8339. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8340. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8341. funcInfo->ReleaseTmpRegister(tmpObj);
  8342. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8343. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8344. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8345. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8346. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8347. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8348. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  8349. if (isCoroutine)
  8350. {
  8351. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8352. tryRecForTryFinally.reg1 = regException;
  8353. tryRecForTryFinally.reg2 = regOffset;
  8354. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  8355. }
  8356. else
  8357. {
  8358. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8359. }
  8360. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8361. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  8362. if (isCoroutine)
  8363. {
  8364. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  8365. }
  8366. byteCodeGenerator->EndStatement(loopNode);
  8367. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8368. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8369. loopNode->loopId = loopId;
  8370. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8371. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8372. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8373. EmitIteratorNext(loopNode->itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  8374. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8375. EmitIteratorComplete(doneLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8376. // branch past loop if the result's done property is truthy
  8377. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8378. funcInfo->ReleaseTmpRegister(doneLocation);
  8379. // otherwise put result's value property in itemLocation
  8380. EmitIteratorValue(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8381. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8382. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8383. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8384. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8385. EmitCatchAndFinallyBlocks(catchLabel,
  8386. finallyLabel,
  8387. loopNode->location,
  8388. shouldCallReturnFunctionLocation,
  8389. shouldCallReturnFunctionLocationFinally,
  8390. regException,
  8391. regOffset,
  8392. byteCodeGenerator,
  8393. funcInfo);
  8394. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8395. {
  8396. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8397. }
  8398. }
  8399. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8400. {
  8401. funcInfo->AcquireLoc(pnode);
  8402. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8403. if (args == nullptr)
  8404. {
  8405. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8406. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8407. pnode->location,
  8408. ByteCodeGenerator::DefaultArraySize);
  8409. }
  8410. else
  8411. {
  8412. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8413. }
  8414. }
  8415. void EmitJumpCleanup(ParseNodeStmt *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  8416. {
  8417. for (; pnode != pnodeTarget; pnode = pnode->pnodeOuter)
  8418. {
  8419. switch (pnode->nop)
  8420. {
  8421. case knopTry:
  8422. case knopCatch:
  8423. case knopFinally:
  8424. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8425. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  8426. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  8427. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8428. break;
  8429. case knopForOf:
  8430. #if ENABLE_PROFILE_INFO
  8431. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8432. {
  8433. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8434. }
  8435. #endif
  8436. // The ForOf loop code is wrapped around try..catch..finally - Forcing couple Leave bytecode over here
  8437. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8438. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8439. break;
  8440. #if ENABLE_PROFILE_INFO
  8441. case knopWhile:
  8442. case knopDoWhile:
  8443. case knopFor:
  8444. case knopForIn:
  8445. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8446. {
  8447. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8448. }
  8449. break;
  8450. #endif
  8451. }
  8452. }
  8453. }
  8454. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8455. {
  8456. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8457. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8458. {
  8459. SaveOpndValue(pnode1, funcInfo);
  8460. }
  8461. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8462. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  8463. (pnode2->AsParseNodeClass()->pnodeConstructor == nullptr || pnode2->AsParseNodeClass()->pnodeConstructor->nop != knopVarDecl))
  8464. {
  8465. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  8466. }
  8467. else
  8468. {
  8469. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8470. }
  8471. }
  8472. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8473. {
  8474. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8475. switch (pnode1->nop)
  8476. {
  8477. case knopName:
  8478. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8479. {
  8480. // Given x op y, y may kill x, so stash x.
  8481. // Note that this only matters if we're loading x prior to the op.
  8482. SaveOpndValue(pnode1, funcInfo);
  8483. }
  8484. break;
  8485. case knopDot:
  8486. if (fLoadLhs)
  8487. {
  8488. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8489. funcInfo->AcquireLoc(pnode1);
  8490. }
  8491. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator))
  8492. {
  8493. // Given x.y op z, z may kill x, so stash x away.
  8494. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8495. }
  8496. break;
  8497. case knopIndex:
  8498. if (fLoadLhs)
  8499. {
  8500. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8501. funcInfo->AcquireLoc(pnode1);
  8502. }
  8503. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator) ||
  8504. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2, byteCodeGenerator))
  8505. {
  8506. // Given x[y] op z, y or z may kill x, so stash x away.
  8507. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8508. }
  8509. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2, byteCodeGenerator))
  8510. {
  8511. // Given x[y] op z, z may kill y, so stash y away.
  8512. // But make sure that x gets a register before y.
  8513. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8514. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8515. }
  8516. break;
  8517. }
  8518. if (fLoadLhs)
  8519. {
  8520. // Emit code to load the value of the LHS.
  8521. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8522. }
  8523. else
  8524. {
  8525. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8526. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8527. }
  8528. // Evaluate the RHS.
  8529. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8530. }
  8531. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8532. {
  8533. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8534. if (location != Js::Constants::NoRegister)
  8535. {
  8536. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8537. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8538. }
  8539. }
  8540. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8541. {
  8542. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8543. // if necessary.
  8544. if (sym != nullptr &&
  8545. !sym->GetIsModuleExportStorage() &&
  8546. sym->GetNeedDeclaration() &&
  8547. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8548. sym->GetScope()->GetFunc() == funcInfo)
  8549. {
  8550. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8551. }
  8552. }
  8553. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8554. {
  8555. byteCodeGenerator->StartStatement(pnode);
  8556. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8557. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8558. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8559. funcInfo->AcquireLoc(pnode);
  8560. byteCodeGenerator->Writer()->Reg3(opcode,
  8561. pnode->location,
  8562. pnode->AsParseNodeBin()->pnode1->location,
  8563. pnode->AsParseNodeBin()->pnode2->location);
  8564. byteCodeGenerator->EndStatement(pnode);
  8565. }
  8566. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  8567. {
  8568. Assert(pnodeAdd->nop == knopAdd);
  8569. Assert(pnodeAdd->CanFlattenConcatExpr());
  8570. bool doConcatString = false;
  8571. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8572. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8573. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8574. while (true)
  8575. {
  8576. if (!pnode->CanFlattenConcatExpr())
  8577. {
  8578. concatOpnds.Append(pnode);
  8579. }
  8580. else if (pnode->nop == knopStr)
  8581. {
  8582. concatOpnds.Append(pnode);
  8583. // Detect if there are any string larger then the append size limit.
  8584. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8585. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8586. }
  8587. else
  8588. {
  8589. Assert(pnode->nop == knopAdd);
  8590. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8591. pnode = pnode->AsParseNodeBin()->pnode1;
  8592. continue;
  8593. }
  8594. if (pnodeStack.Empty())
  8595. {
  8596. break;
  8597. }
  8598. pnode = pnodeStack.Head();
  8599. pnodeStack.RemoveHead();
  8600. }
  8601. return doConcatString;
  8602. }
  8603. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8604. {
  8605. byteCodeGenerator->StartStatement(pnode);
  8606. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator) || MayHaveSideEffectOnNode(pnode1, pnode3, byteCodeGenerator))
  8607. {
  8608. SaveOpndValue(pnode1, funcInfo);
  8609. }
  8610. if (MayHaveSideEffectOnNode(pnode2, pnode3, byteCodeGenerator))
  8611. {
  8612. SaveOpndValue(pnode2, funcInfo);
  8613. }
  8614. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8615. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8616. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8617. funcInfo->ReleaseLoc(pnode3);
  8618. funcInfo->ReleaseLoc(pnode2);
  8619. funcInfo->ReleaseLoc(pnode1);
  8620. funcInfo->AcquireLoc(pnode);
  8621. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8622. pnode->location,
  8623. pnode1->location,
  8624. pnode2->location,
  8625. pnode3->location);
  8626. byteCodeGenerator->EndStatement(pnode);
  8627. }
  8628. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8629. {
  8630. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8631. funcInfo->ReleaseLoc(pnode2);
  8632. funcInfo->ReleaseLoc(pnode1);
  8633. funcInfo->AcquireLoc(pnode);
  8634. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8635. pnode->location,
  8636. pnode1->location,
  8637. pnode2->location,
  8638. count);
  8639. }
  8640. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8641. {
  8642. Assert(pnode->nop == knopAdd);
  8643. if (pnode->CanFlattenConcatExpr())
  8644. {
  8645. // We should only have a string concat if the feature is on.
  8646. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8647. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8648. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8649. if (doConcatString)
  8650. {
  8651. uint concatCount = concatOpnds.Count();
  8652. Assert(concatCount >= 2);
  8653. // Don't do concatN if the number is too high
  8654. // CONSIDER: although we could have done multiple ConcatNs
  8655. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8656. {
  8657. #if DBG
  8658. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  8659. #endif
  8660. ParseNode * pnode1 = concatOpnds.Head();
  8661. concatOpnds.RemoveHead();
  8662. ParseNode * pnode2 = concatOpnds.Head();
  8663. concatOpnds.RemoveHead();
  8664. if (concatCount == 3)
  8665. {
  8666. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  8667. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8668. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8669. byteCodeGenerator->Writer()->ByteCodeDataSize());
  8670. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  8671. return;
  8672. }
  8673. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  8674. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8675. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8676. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  8677. byteCodeGenerator->StartStatement(pnode);
  8678. funcInfo->AcquireLoc(pnode);
  8679. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  8680. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  8681. uint i = 2;
  8682. do
  8683. {
  8684. ParseNode * currNode = concatOpnds.Head();
  8685. concatOpnds.RemoveHead();
  8686. ParseNode * currNode2 = concatOpnds.Head();
  8687. concatOpnds.RemoveHead();
  8688. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8689. funcInfo->ReleaseLoc(currNode2);
  8690. funcInfo->ReleaseLoc(currNode);
  8691. byteCodeGenerator->Writer()->Reg3B1(
  8692. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  8693. i += 2;
  8694. } while (concatOpnds.Count() > 1);
  8695. if (!concatOpnds.Empty())
  8696. {
  8697. ParseNode * currNode = concatOpnds.Head();
  8698. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8699. funcInfo->ReleaseLoc(currNode);
  8700. byteCodeGenerator->Writer()->Reg2B1(
  8701. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  8702. i++;
  8703. }
  8704. Assert(concatCount == i);
  8705. byteCodeGenerator->EndStatement(pnode);
  8706. return;
  8707. }
  8708. }
  8709. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  8710. byteCodeGenerator->StartStatement(pnode);
  8711. ParseNode * currNode = concatOpnds.Head();
  8712. concatOpnds.RemoveHead();
  8713. ParseNode * currNode2 = concatOpnds.Head();
  8714. concatOpnds.RemoveHead();
  8715. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8716. funcInfo->ReleaseLoc(currNode2);
  8717. funcInfo->ReleaseLoc(currNode);
  8718. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  8719. byteCodeGenerator->Writer()->Reg3(
  8720. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  8721. while (!concatOpnds.Empty())
  8722. {
  8723. currNode = concatOpnds.Head();
  8724. concatOpnds.RemoveHead();
  8725. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8726. funcInfo->ReleaseLoc(currNode);
  8727. byteCodeGenerator->Writer()->Reg3(
  8728. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  8729. }
  8730. byteCodeGenerator->EndStatement(pnode);
  8731. }
  8732. else
  8733. {
  8734. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  8735. }
  8736. }
  8737. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  8738. {
  8739. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  8740. {
  8741. switch (node->op)
  8742. {
  8743. case Js::OpCode::TryFinallyWithYield:
  8744. this->Writer()->Empty(Js::OpCode::LeaveNull);
  8745. break;
  8746. case Js::OpCode::TryCatch:
  8747. case Js::OpCode::ResumeFinally:
  8748. case Js::OpCode::ResumeCatch:
  8749. this->Writer()->Empty(Js::OpCode::Leave);
  8750. break;
  8751. default:
  8752. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8753. break;
  8754. }
  8755. }
  8756. }
  8757. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8758. {
  8759. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8760. {
  8761. switch (node->op)
  8762. {
  8763. case Js::OpCode::TryCatch:
  8764. this->Writer()->Br(node->op, node->label);
  8765. break;
  8766. case Js::OpCode::TryFinallyWithYield:
  8767. case Js::OpCode::ResumeFinally:
  8768. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8769. break;
  8770. case Js::OpCode::ResumeCatch:
  8771. this->Writer()->Empty(node->op);
  8772. break;
  8773. default:
  8774. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8775. break;
  8776. }
  8777. }
  8778. }
  8779. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator)
  8780. {
  8781. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8782. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8783. if (yieldStarIterator == Js::Constants::NoRegister)
  8784. {
  8785. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8786. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8787. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8788. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8789. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8790. }
  8791. else
  8792. {
  8793. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8794. }
  8795. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8796. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8797. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8798. if (yieldStarIterator == Js::Constants::NoRegister)
  8799. {
  8800. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8801. }
  8802. else
  8803. {
  8804. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8805. }
  8806. }
  8807. void EmitYieldStar(ParseNodeUni* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8808. {
  8809. funcInfo->AcquireLoc(yieldStarNode);
  8810. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8811. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8812. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8813. // Evaluate operand
  8814. Emit(yieldStarNode->pnode1, byteCodeGenerator, funcInfo, false);
  8815. funcInfo->ReleaseLoc(yieldStarNode->pnode1);
  8816. EmitGetIterator(iteratorLocation, yieldStarNode->pnode1->location, byteCodeGenerator, funcInfo);
  8817. // Call the iterator's next()
  8818. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8819. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8820. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8821. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8822. // remember the loopId like the loop statements do.
  8823. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8824. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8825. // branch past the loop if the done property is truthy
  8826. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8827. funcInfo->ReleaseTmpRegister(doneLocation);
  8828. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8829. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8830. byteCodeGenerator->Writer()->Br(loopEntrance);
  8831. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8832. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8833. // Put the iterator result's value in yieldStarNode->location.
  8834. // It will be used as the result value of the yield* operator expression.
  8835. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8836. }
  8837. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8838. {
  8839. if (isSymGlobalAndSingleAssignment)
  8840. {
  8841. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8842. }
  8843. }
  8844. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8845. {
  8846. if (isSymGlobalAndSingleAssignment)
  8847. {
  8848. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8849. }
  8850. }
  8851. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8852. {
  8853. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8854. {
  8855. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8856. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8857. }
  8858. }
  8859. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8860. {
  8861. Assert(objNode->nop == knopObject);
  8862. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  8863. while (memberList != nullptr)
  8864. {
  8865. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  8866. if (memberNode->nop != knopEllipsis)
  8867. {
  8868. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  8869. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  8870. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8871. {
  8872. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  8873. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8874. }
  8875. }
  8876. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  8877. }
  8878. }
  8879. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8880. {
  8881. Assert(knopDotNode->nop == knopDot);
  8882. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  8883. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  8884. bool isSymGlobalAndSingleAssignment = false;
  8885. if (objectNode->nop == knopName)
  8886. {
  8887. if (ByteCodeGenerator::IsThis(objectNode))
  8888. {
  8889. // Assume 'this' always refer to GlobalObject
  8890. // Cases like "this.a = "
  8891. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  8892. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8893. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8894. }
  8895. else
  8896. {
  8897. Symbol * sym = objectNode->AsParseNodeName()->sym;
  8898. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  8899. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8900. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8901. }
  8902. }
  8903. }
  8904. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8905. {
  8906. // Track the Global Int Constant properties' assignments here.
  8907. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8908. if (nodeType & fnopAsg)
  8909. {
  8910. if (nodeType & fnopBin)
  8911. {
  8912. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  8913. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  8914. Assert(lhs && rhs);
  8915. // Don't track other than integers and objects with member nodes.
  8916. if (rhs->nop == knopObject)
  8917. {
  8918. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8919. }
  8920. else if (rhs->nop != knopInt &&
  8921. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  8922. {
  8923. return;
  8924. }
  8925. if (lhs->nop == knopName)
  8926. {
  8927. // Handle "a = <Integer>" cases here
  8928. Symbol * sym = lhs->AsParseNodeName()->sym;
  8929. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8930. }
  8931. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8932. {
  8933. // Cases like "obj.a = <Integer>"
  8934. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8935. }
  8936. }
  8937. else if (nodeType & fnopUni)
  8938. {
  8939. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  8940. if (lhs->nop == knopName)
  8941. {
  8942. // Cases like "a++"
  8943. Symbol * sym = lhs->AsParseNodeName()->sym;
  8944. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8945. }
  8946. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8947. {
  8948. // Cases like "obj.a++"
  8949. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8950. }
  8951. }
  8952. }
  8953. }
  8954. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode, bool isTopLevel)
  8955. {
  8956. if (pnode == nullptr)
  8957. {
  8958. return;
  8959. }
  8960. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8961. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8962. // printNop(pnode->nop);
  8963. switch (pnode->nop)
  8964. {
  8965. case knopList:
  8966. EmitList(pnode, byteCodeGenerator, funcInfo);
  8967. break;
  8968. case knopInt:
  8969. // currently, these are loaded at the top
  8970. break;
  8971. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8972. case knopFlt:
  8973. // currently, these are loaded at the top
  8974. break;
  8975. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8976. case knopStr:
  8977. // TODO: protocol for combining string constants
  8978. break;
  8979. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8980. case knopRegExp:
  8981. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  8982. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  8983. break;
  8984. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8985. case knopNull:
  8986. // enregistered
  8987. break;
  8988. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  8989. case knopFalse:
  8990. // enregistered
  8991. break;
  8992. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  8993. case knopTrue:
  8994. // enregistered
  8995. break;
  8996. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  8997. case knopEmpty:
  8998. break;
  8999. // Unary operators.
  9000. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  9001. case knopNot:
  9002. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9003. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9004. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9005. byteCodeGenerator->Writer()->Reg2(
  9006. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9007. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9008. break;
  9009. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  9010. case knopNeg:
  9011. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9012. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9013. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9014. funcInfo->AcquireLoc(pnode);
  9015. byteCodeGenerator->Writer()->Reg2(
  9016. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9017. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9018. break;
  9019. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  9020. case knopPos:
  9021. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9022. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9023. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9024. byteCodeGenerator->Writer()->Reg2(
  9025. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9026. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9027. break;
  9028. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  9029. case knopLogNot:
  9030. {
  9031. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9032. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9033. // For boolean expressions that compute a result, we have to burn a register for the result
  9034. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9035. // full-on renaming in the back end.
  9036. funcInfo->AcquireLoc(pnode);
  9037. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  9038. {
  9039. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  9040. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  9041. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  9042. }
  9043. else
  9044. {
  9045. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9046. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  9047. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  9048. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9049. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9050. }
  9051. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9052. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9053. break;
  9054. }
  9055. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  9056. case knopEllipsis:
  9057. {
  9058. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9059. // Transparently pass the location of the object or array.
  9060. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9061. break;
  9062. }
  9063. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  9064. case knopIncPost:
  9065. case knopDecPost:
  9066. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  9067. if (pnode->isUsed || fReturnValue)
  9068. {
  9069. byteCodeGenerator->StartStatement(pnode);
  9070. const Js::OpCode op = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  9071. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9072. // Grab a register for the expression result.
  9073. funcInfo->AcquireLoc(pnode);
  9074. // Load the initial value, convert it (this is the expression result), and increment it.
  9075. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9076. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode1->location);
  9077. // Use temporary register if lhs cannot be assigned
  9078. Js::RegSlot incDecResult = pnode1->location;
  9079. if (funcInfo->RegIsConst(incDecResult) ||
  9080. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  9081. {
  9082. incDecResult = funcInfo->AcquireTmpRegister();
  9083. }
  9084. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  9085. Assert(oneReg != Js::Constants::NoRegister);
  9086. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  9087. // Store the incremented value.
  9088. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9089. // Release the incremented value and the l-value.
  9090. if (incDecResult != pnode1->location)
  9091. {
  9092. funcInfo->ReleaseTmpRegister(incDecResult);
  9093. }
  9094. funcInfo->ReleaseLoad(pnode1);
  9095. byteCodeGenerator->EndStatement(pnode);
  9096. break;
  9097. }
  9098. else
  9099. {
  9100. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  9101. }
  9102. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  9103. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  9104. case knopIncPre:
  9105. case knopDecPre:
  9106. {
  9107. byteCodeGenerator->StartStatement(pnode);
  9108. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  9109. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9110. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9111. // (i.e., is a constant).
  9112. const bool need_result_location =
  9113. pnode->isUsed
  9114. || fReturnValue
  9115. || funcInfo->RegIsConst(pnode1->location)
  9116. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  9117. if (need_result_location)
  9118. {
  9119. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9120. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9121. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  9122. // Store the incremented value and release the l-value.
  9123. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  9124. }
  9125. else
  9126. {
  9127. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9128. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  9129. // Store the incremented value and release the l-value.
  9130. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  9131. }
  9132. funcInfo->ReleaseLoad(pnode1);
  9133. byteCodeGenerator->EndStatement(pnode);
  9134. break;
  9135. }
  9136. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  9137. case knopTypeof:
  9138. {
  9139. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9140. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  9141. switch (pnodeOpnd->nop)
  9142. {
  9143. case knopDot:
  9144. {
  9145. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9146. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9147. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  9148. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9149. funcInfo->AcquireLoc(pnode);
  9150. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  9151. break;
  9152. }
  9153. case knopIndex:
  9154. {
  9155. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9156. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9157. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9158. funcInfo->AcquireLoc(pnode);
  9159. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9160. break;
  9161. }
  9162. case knopName:
  9163. {
  9164. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9165. if (pnodeNameOpnd->IsUserIdentifier())
  9166. {
  9167. funcInfo->AcquireLoc(pnode);
  9168. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9169. break;
  9170. }
  9171. // Special names should fallthrough to default case
  9172. }
  9173. default:
  9174. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9175. funcInfo->ReleaseLoc(pnodeOpnd);
  9176. byteCodeGenerator->Writer()->Reg2(
  9177. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9178. break;
  9179. }
  9180. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9181. break;
  9182. }
  9183. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9184. case knopVoid:
  9185. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9186. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9187. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9188. break;
  9189. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9190. case knopArray:
  9191. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9192. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9193. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9194. break;
  9195. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9196. case knopObject:
  9197. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9198. funcInfo->AcquireLoc(pnode);
  9199. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9200. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9201. break;
  9202. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9203. case knopComputedName:
  9204. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9205. if (pnode->location == Js::Constants::NoRegister)
  9206. {
  9207. // The name is some expression with no home location. We can just re-use the register.
  9208. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9209. }
  9210. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9211. {
  9212. // The name had to be protected from side-effects of the RHS.
  9213. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9214. }
  9215. break;
  9216. // Binary and Ternary Operators
  9217. case knopAdd:
  9218. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9219. break;
  9220. case knopSub:
  9221. case knopMul:
  9222. case knopExpo:
  9223. case knopDiv:
  9224. case knopMod:
  9225. case knopOr:
  9226. case knopXor:
  9227. case knopAnd:
  9228. case knopLsh:
  9229. case knopRsh:
  9230. case knopRs2:
  9231. case knopIn:
  9232. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9233. break;
  9234. case knopInstOf:
  9235. {
  9236. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9237. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9238. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9239. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9240. funcInfo->AcquireLoc(pnode);
  9241. uint cacheId = funcInfo->NewIsInstInlineCache();
  9242. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9243. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9244. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9245. }
  9246. break;
  9247. case knopEq:
  9248. case knopEqv:
  9249. case knopNEqv:
  9250. case knopNe:
  9251. case knopLt:
  9252. case knopLe:
  9253. case knopGe:
  9254. case knopGt:
  9255. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9256. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9257. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9258. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9259. funcInfo->AcquireLoc(pnode);
  9260. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9261. pnode->AsParseNodeBin()->pnode2->location);
  9262. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9263. break;
  9264. case knopNew:
  9265. {
  9266. EmitNew(pnode, byteCodeGenerator, funcInfo);
  9267. byteCodeGenerator->EndStatement(pnode);
  9268. break;
  9269. }
  9270. case knopDelete:
  9271. {
  9272. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  9273. byteCodeGenerator->StartStatement(pnode);
  9274. switch (pexpr->nop)
  9275. {
  9276. case knopName:
  9277. {
  9278. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  9279. if (pnodeName->IsSpecialName())
  9280. {
  9281. funcInfo->AcquireLoc(pnode);
  9282. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9283. }
  9284. else
  9285. {
  9286. funcInfo->AcquireLoc(pnode);
  9287. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  9288. }
  9289. break;
  9290. }
  9291. case knopDot:
  9292. {
  9293. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  9294. {
  9295. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  9296. funcInfo->AcquireLoc(pnode);
  9297. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  9298. }
  9299. else
  9300. {
  9301. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9302. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9303. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9304. funcInfo->AcquireLoc(pnode);
  9305. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  9306. funcInfo->FindOrAddReferencedPropertyId(propertyId), byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  9307. }
  9308. break;
  9309. }
  9310. case knopIndex:
  9311. {
  9312. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9313. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  9314. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9315. funcInfo->AcquireLoc(pnode);
  9316. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  9317. break;
  9318. }
  9319. default:
  9320. {
  9321. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  9322. funcInfo->ReleaseLoc(pexpr);
  9323. byteCodeGenerator->Writer()->Reg2(
  9324. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  9325. break;
  9326. }
  9327. }
  9328. byteCodeGenerator->EndStatement(pnode);
  9329. break;
  9330. }
  9331. case knopCall:
  9332. {
  9333. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  9334. byteCodeGenerator->StartStatement(pnodeCall);
  9335. if (pnodeCall->isSuperCall)
  9336. {
  9337. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue);
  9338. }
  9339. else if (pnodeCall->pnodeTarget->nop == knopImport)
  9340. {
  9341. ParseNodePtr args = pnodeCall->pnodeArgs;
  9342. Assert(CountArguments(args) == 2); // import() takes one argument
  9343. Emit(args, byteCodeGenerator, funcInfo, false);
  9344. funcInfo->ReleaseLoc(args);
  9345. funcInfo->AcquireLoc(pnodeCall);
  9346. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  9347. }
  9348. else
  9349. {
  9350. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  9351. {
  9352. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  9353. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  9354. }
  9355. else
  9356. {
  9357. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  9358. }
  9359. }
  9360. byteCodeGenerator->EndStatement(pnode);
  9361. break;
  9362. }
  9363. case knopIndex:
  9364. {
  9365. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9366. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9367. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9368. Js::RegSlot protoLocation = callObjLocation;
  9369. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9370. {
  9371. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9372. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9373. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9374. }
  9375. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9376. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9377. funcInfo->AcquireLoc(pnode);
  9378. byteCodeGenerator->Writer()->Element(
  9379. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  9380. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9381. break;
  9382. }
  9383. // this is MemberExpression as rvalue
  9384. case knopDot:
  9385. {
  9386. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9387. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9388. funcInfo->AcquireLoc(pnode);
  9389. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9390. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9391. Js::RegSlot protoLocation = callObjLocation;
  9392. if (propertyId == Js::PropertyIds::length)
  9393. {
  9394. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9395. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  9396. }
  9397. else if (pnode->IsCallApplyTargetLoad())
  9398. {
  9399. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9400. {
  9401. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9402. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9403. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9404. }
  9405. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9406. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  9407. }
  9408. else
  9409. {
  9410. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9411. {
  9412. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9413. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9414. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9415. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9416. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  9417. }
  9418. else
  9419. {
  9420. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  9421. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  9422. }
  9423. }
  9424. break;
  9425. }
  9426. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  9427. case knopAsg:
  9428. {
  9429. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9430. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9431. byteCodeGenerator->StartStatement(pnode);
  9432. if (pnode->isUsed || fReturnValue)
  9433. {
  9434. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  9435. // which will copy the assigned value there.
  9436. funcInfo->AcquireLoc(pnode);
  9437. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9438. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9439. }
  9440. else
  9441. {
  9442. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9443. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9444. }
  9445. funcInfo->ReleaseLoc(rhs);
  9446. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  9447. {
  9448. funcInfo->ReleaseReference(lhs);
  9449. }
  9450. byteCodeGenerator->EndStatement(pnode);
  9451. break;
  9452. }
  9453. case knopName:
  9454. funcInfo->AcquireLoc(pnode);
  9455. if (ByteCodeGenerator::IsThis(pnode))
  9456. {
  9457. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  9458. }
  9459. else
  9460. {
  9461. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  9462. }
  9463. break;
  9464. case knopComma:
  9465. {
  9466. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9467. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  9468. // Easier to correct this here than to check every binary op in the parser.
  9469. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  9470. pnode1->isUsed = false;
  9471. if (pnode1->nop == knopComma)
  9472. {
  9473. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  9474. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  9475. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  9476. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  9477. SList<ParseNode *> rhsStack(alloc);
  9478. do
  9479. {
  9480. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  9481. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  9482. pnode1->isUsed = false;
  9483. } while (pnode1->nop == knopComma);
  9484. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9485. if (funcInfo->IsTmpReg(pnode1->location))
  9486. {
  9487. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9488. }
  9489. while (!rhsStack.Empty())
  9490. {
  9491. ParseNode *pnodeRhs = rhsStack.Pop();
  9492. pnodeRhs->isUsed = false;
  9493. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  9494. if (funcInfo->IsTmpReg(pnodeRhs->location))
  9495. {
  9496. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  9497. }
  9498. funcInfo->ReleaseLoc(pnodeRhs);
  9499. }
  9500. }
  9501. else
  9502. {
  9503. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9504. if (funcInfo->IsTmpReg(pnode1->location))
  9505. {
  9506. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9507. }
  9508. }
  9509. funcInfo->ReleaseLoc(pnode1);
  9510. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  9511. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  9512. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9513. funcInfo->AcquireLoc(pnode);
  9514. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  9515. {
  9516. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  9517. }
  9518. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9519. }
  9520. break;
  9521. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  9522. // boolean value short-circuits the operation, and to the value of the right-hand expression
  9523. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  9524. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  9525. case knopLogOr:
  9526. {
  9527. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9528. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9529. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9530. // optimizing the previous version where we had a dest for each level
  9531. funcInfo->AcquireLoc(pnode);
  9532. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9533. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9534. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9535. break;
  9536. }
  9537. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  9538. case knopLogAnd:
  9539. {
  9540. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9541. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9542. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9543. // optimizing the previous version where we had a dest for each level
  9544. funcInfo->AcquireLoc(pnode);
  9545. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9546. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9547. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9548. break;
  9549. }
  9550. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  9551. case knopQmark:
  9552. {
  9553. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9554. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9555. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9556. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9557. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9558. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  9559. // For boolean expressions that compute a result, we have to burn a register for the result
  9560. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9561. // full-on renaming in the back end.
  9562. funcInfo->AcquireLoc(pnode);
  9563. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  9564. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  9565. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  9566. // Record the branch bytecode offset
  9567. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9568. byteCodeGenerator->Writer()->Br(skipLabel);
  9569. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9570. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  9571. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  9572. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  9573. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9574. break;
  9575. }
  9576. case knopAsgAdd:
  9577. case knopAsgSub:
  9578. case knopAsgMul:
  9579. case knopAsgDiv:
  9580. case knopAsgExpo:
  9581. case knopAsgMod:
  9582. case knopAsgAnd:
  9583. case knopAsgXor:
  9584. case knopAsgOr:
  9585. case knopAsgLsh:
  9586. case knopAsgRsh:
  9587. case knopAsgRs2:
  9588. {
  9589. byteCodeGenerator->StartStatement(pnode);
  9590. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9591. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9592. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9593. // (i.e., is a constant).
  9594. const bool need_result_location =
  9595. pnode->isUsed
  9596. || fReturnValue
  9597. || funcInfo->RegIsConst(lhs->location)
  9598. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  9599. if (need_result_location)
  9600. {
  9601. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9602. // Grab a register for the initial value and load it.
  9603. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9604. funcInfo->ReleaseLoc(rhs);
  9605. // Do the arithmetic, store the result, and release the l-value.
  9606. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  9607. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  9608. }
  9609. else
  9610. {
  9611. // Grab a register for the initial value and load it. Might modify lhs->location.
  9612. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9613. funcInfo->ReleaseLoc(rhs);
  9614. // Do the arithmetic, store the result, and release the l-value.
  9615. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  9616. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  9617. }
  9618. funcInfo->ReleaseLoad(lhs);
  9619. byteCodeGenerator->EndStatement(pnode);
  9620. break;
  9621. }
  9622. // General nodes.
  9623. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  9624. case knopTempRef:
  9625. // TODO: check whether mov is necessary
  9626. funcInfo->AcquireLoc(pnode);
  9627. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9628. break;
  9629. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  9630. case knopTemp:
  9631. // Emit initialization code
  9632. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  9633. {
  9634. byteCodeGenerator->StartStatement(pnode);
  9635. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  9636. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  9637. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  9638. byteCodeGenerator->EndStatement(pnode);
  9639. }
  9640. break;
  9641. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9642. case knopVarDecl:
  9643. case knopConstDecl:
  9644. case knopLetDecl:
  9645. {
  9646. // Emit initialization code
  9647. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  9648. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  9649. if (initNode != nullptr || pnode->nop == knopLetDecl)
  9650. {
  9651. Symbol *sym = pnode->AsParseNodeVar()->sym;
  9652. Js::RegSlot rhsLocation;
  9653. byteCodeGenerator->StartStatement(pnode);
  9654. if (initNode != nullptr)
  9655. {
  9656. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9657. rhsLocation = initNode->location;
  9658. if (initNode->nop == knopObject)
  9659. {
  9660. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  9661. }
  9662. else if (initNode->nop == knopInt)
  9663. {
  9664. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9665. }
  9666. }
  9667. else
  9668. {
  9669. Assert(pnode->nop == knopLetDecl);
  9670. rhsLocation = funcInfo->AcquireTmpRegister();
  9671. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9672. }
  9673. if (pnode->nop != knopVarDecl)
  9674. {
  9675. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  9676. sym->SetNeedDeclaration(false);
  9677. }
  9678. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  9679. funcInfo->ReleaseTmpRegister(rhsLocation);
  9680. byteCodeGenerator->EndStatement(pnode);
  9681. }
  9682. break;
  9683. }
  9684. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9685. case knopFncDecl:
  9686. // The "function declarations" were emitted in DefineFunctions()
  9687. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  9688. {
  9689. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  9690. }
  9691. break;
  9692. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9693. case knopClassDecl:
  9694. {
  9695. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  9696. funcInfo->AcquireLoc(pnodeClass);
  9697. Assert(pnodeClass->pnodeConstructor);
  9698. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9699. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9700. // Extends
  9701. if (pnodeClass->pnodeExtends)
  9702. {
  9703. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9704. // defer and nondefer parse modes.
  9705. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9706. }
  9707. // Constructor
  9708. Emit(pnodeClass->pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9709. EmitComputedFunctionNameVar(bindPnode, pnodeClass->pnodeConstructor, byteCodeGenerator);
  9710. if (pnodeClass->pnodeExtends)
  9711. {
  9712. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9713. byteCodeGenerator->Writer()->InitClass(pnodeClass->location, pnodeClass->pnodeExtends->location);
  9714. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9715. }
  9716. else
  9717. {
  9718. byteCodeGenerator->Writer()->InitClass(pnodeClass->location);
  9719. }
  9720. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9721. int cacheId = funcInfo->FindOrAddInlineCacheId(pnodeClass->location, Js::PropertyIds::prototype, false, false);
  9722. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnodeClass->location, cacheId);
  9723. // Static Methods
  9724. EmitClassInitializers(pnodeClass->pnodeStaticMembers, pnodeClass->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9725. // Instance Methods
  9726. EmitClassInitializers(pnodeClass->pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9727. funcInfo->ReleaseTmpRegister(protoLoc);
  9728. // Emit name binding.
  9729. if (pnodeClass->pnodeName)
  9730. {
  9731. Symbol * sym = pnodeClass->pnodeName->sym;
  9732. sym->SetNeedDeclaration(false);
  9733. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9734. }
  9735. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9736. if (pnodeClass->pnodeExtends)
  9737. {
  9738. funcInfo->ReleaseLoc(pnodeClass->pnodeExtends);
  9739. }
  9740. if (pnodeClass->pnodeDeclName)
  9741. {
  9742. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9743. sym->SetNeedDeclaration(false);
  9744. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9745. }
  9746. if (pnodeClass->IsDefaultModuleExport())
  9747. {
  9748. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9749. }
  9750. break;
  9751. }
  9752. case knopStrTemplate:
  9753. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9754. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  9755. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9756. break;
  9757. case knopEndCode:
  9758. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9759. // load undefined for the fallthrough case:
  9760. if (!funcInfo->IsGlobalFunction())
  9761. {
  9762. if (funcInfo->IsClassConstructor())
  9763. {
  9764. // For class constructors, we need to explicitly load 'this' into the return register.
  9765. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9766. }
  9767. else
  9768. {
  9769. // In the global function, implicit return values are copied to the return register, and if
  9770. // necessary the return register is initialized at the top. Don't clobber the value here.
  9771. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9772. }
  9773. }
  9774. // Label for non-fall-through return
  9775. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9776. if (funcInfo->GetHasCachedScope())
  9777. {
  9778. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  9779. }
  9780. byteCodeGenerator->StartStatement(pnode);
  9781. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9782. byteCodeGenerator->EndStatement(pnode);
  9783. break;
  9784. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9785. case knopDebugger:
  9786. byteCodeGenerator->StartStatement(pnode);
  9787. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9788. byteCodeGenerator->EndStatement(pnode);
  9789. break;
  9790. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9791. case knopFor:
  9792. {
  9793. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  9794. if (pnodeFor->pnodeInverted != nullptr)
  9795. {
  9796. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  9797. }
  9798. else
  9799. {
  9800. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9801. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  9802. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  9803. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9804. {
  9805. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9806. }
  9807. EmitLoop(pnodeFor,
  9808. pnodeFor->pnodeCond,
  9809. pnodeFor->pnodeBody,
  9810. pnodeFor->pnodeIncr,
  9811. byteCodeGenerator,
  9812. funcInfo,
  9813. fReturnValue,
  9814. FALSE,
  9815. pnodeFor->pnodeBlock);
  9816. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9817. }
  9818. break;
  9819. }
  9820. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9821. case knopIf:
  9822. {
  9823. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  9824. byteCodeGenerator->StartStatement(pnodeIf);
  9825. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9826. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9827. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9828. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  9829. byteCodeGenerator->EndStatement(pnodeIf);
  9830. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9831. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9832. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  9833. if (pnodeIf->pnodeFalse != nullptr)
  9834. {
  9835. // has else clause
  9836. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9837. // Record the branch bytecode offset
  9838. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9839. // then clause skips else clause
  9840. byteCodeGenerator->Writer()->Br(skipLabel);
  9841. // generate code for else clause
  9842. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9843. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9844. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  9845. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9846. }
  9847. else
  9848. {
  9849. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9850. }
  9851. if (pnodeIf->emitLabels)
  9852. {
  9853. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  9854. }
  9855. break;
  9856. }
  9857. case knopWhile:
  9858. {
  9859. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9860. EmitLoop(pnodeWhile,
  9861. pnodeWhile->pnodeCond,
  9862. pnodeWhile->pnodeBody,
  9863. nullptr,
  9864. byteCodeGenerator,
  9865. funcInfo,
  9866. fReturnValue);
  9867. break;
  9868. }
  9869. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9870. case knopDoWhile:
  9871. {
  9872. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9873. EmitLoop(pnodeWhile,
  9874. pnodeWhile->pnodeCond,
  9875. pnodeWhile->pnodeBody,
  9876. nullptr,
  9877. byteCodeGenerator,
  9878. funcInfo,
  9879. fReturnValue,
  9880. true);
  9881. break;
  9882. }
  9883. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9884. case knopForIn:
  9885. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9886. break;
  9887. case knopForOf:
  9888. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9889. break;
  9890. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9891. case knopReturn:
  9892. {
  9893. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  9894. byteCodeGenerator->StartStatement(pnodeReturn);
  9895. if (pnodeReturn->pnodeExpr != nullptr)
  9896. {
  9897. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  9898. {
  9899. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9900. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9901. }
  9902. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9903. if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9904. {
  9905. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  9906. }
  9907. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9908. }
  9909. else
  9910. {
  9911. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9912. }
  9913. if (funcInfo->IsClassConstructor())
  9914. {
  9915. // return expr; // becomes like below:
  9916. //
  9917. // if (IsObject(expr)) {
  9918. // return expr;
  9919. // } else if (IsBaseClassConstructor) {
  9920. // return this;
  9921. // } else if (!IsUndefined(expr)) {
  9922. // throw TypeError;
  9923. // }
  9924. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9925. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9926. if (funcInfo->IsBaseClassConstructor())
  9927. {
  9928. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  9929. }
  9930. else
  9931. {
  9932. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9933. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9934. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9935. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9936. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9937. }
  9938. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9939. }
  9940. if (pnodeReturn->grfnop & fnopCleanup)
  9941. {
  9942. EmitJumpCleanup(pnodeReturn, nullptr, byteCodeGenerator, funcInfo);
  9943. }
  9944. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9945. byteCodeGenerator->EndStatement(pnodeReturn);
  9946. break;
  9947. }
  9948. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9949. case knopBlock:
  9950. {
  9951. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  9952. if (pnodeBlock->pnodeStmt != nullptr)
  9953. {
  9954. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  9955. if (pnodeBlock->emitLabels)
  9956. {
  9957. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  9958. }
  9959. }
  9960. break;
  9961. }
  9962. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9963. case knopWith:
  9964. {
  9965. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  9966. Assert(pnodeWith->pnodeObj != nullptr);
  9967. byteCodeGenerator->StartStatement(pnodeWith);
  9968. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9969. // is overwritten in the body, the lookups are not affected.
  9970. funcInfo->AcquireLoc(pnodeWith);
  9971. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  9972. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnodeWith->location;
  9973. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  9974. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9975. {
  9976. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewWithObject, pnodeWith->location, regVal);
  9977. }
  9978. byteCodeGenerator->EndStatement(pnodeWith);
  9979. #ifdef PERF_HINT
  9980. if (PHASE_TRACE1(Js::PerfHintPhase))
  9981. {
  9982. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9983. }
  9984. #endif
  9985. if (pnodeWith->pnodeBody != nullptr)
  9986. {
  9987. Scope *scope = pnodeWith->scope;
  9988. scope->SetLocation(pnodeWith->location);
  9989. byteCodeGenerator->PushScope(scope);
  9990. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9991. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9992. {
  9993. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9994. }
  9995. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9996. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  9997. byteCodeGenerator->PopScope();
  9998. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  9999. }
  10000. if (pnodeWith->emitLabels)
  10001. {
  10002. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  10003. }
  10004. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  10005. {
  10006. funcInfo->ReleaseTmpRegister(regVal);
  10007. }
  10008. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  10009. break;
  10010. }
  10011. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10012. case knopBreak:
  10013. {
  10014. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10015. Assert(pnodeJump->pnodeTarget->emitLabels);
  10016. byteCodeGenerator->StartStatement(pnodeJump);
  10017. if (pnodeJump->grfnop & fnopCleanup)
  10018. {
  10019. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  10020. }
  10021. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  10022. if (pnodeJump->emitLabels)
  10023. {
  10024. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  10025. }
  10026. byteCodeGenerator->EndStatement(pnodeJump);
  10027. break;
  10028. }
  10029. case knopContinue:
  10030. {
  10031. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10032. Assert(pnodeJump->pnodeTarget->emitLabels);
  10033. byteCodeGenerator->StartStatement(pnodeJump);
  10034. if (pnodeJump->grfnop & fnopCleanup)
  10035. {
  10036. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  10037. }
  10038. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  10039. byteCodeGenerator->EndStatement(pnodeJump);
  10040. break;
  10041. }
  10042. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10043. case knopSwitch:
  10044. {
  10045. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  10046. BOOL fHasDefault = false;
  10047. Assert(pnodeSwitch->pnodeVal != nullptr);
  10048. byteCodeGenerator->StartStatement(pnodeSwitch);
  10049. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  10050. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10051. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  10052. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10053. byteCodeGenerator->EndStatement(pnodeSwitch);
  10054. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  10055. // code so the BE can optimize it.
  10056. ParseNodeCase *pnodeCase;
  10057. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10058. {
  10059. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  10060. // expression take place regardless.
  10061. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  10062. if (pnodeCase == pnodeSwitch->pnodeDefault)
  10063. {
  10064. fHasDefault = true;
  10065. continue;
  10066. }
  10067. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10068. byteCodeGenerator->Writer()->BrReg2(
  10069. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  10070. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  10071. }
  10072. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  10073. if (fHasDefault)
  10074. {
  10075. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  10076. }
  10077. else
  10078. {
  10079. if (!pnodeSwitch->emitLabels)
  10080. {
  10081. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  10082. }
  10083. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  10084. }
  10085. // Now emit the case arms to which we jump on matching a case value.
  10086. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10087. {
  10088. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  10089. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10090. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  10091. }
  10092. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10093. funcInfo->ReleaseTmpRegister(regVal);
  10094. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  10095. if (!fHasDefault || pnodeSwitch->emitLabels)
  10096. {
  10097. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  10098. }
  10099. break;
  10100. }
  10101. case knopTryCatch:
  10102. {
  10103. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  10104. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  10105. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  10106. Assert(pnodeTry);
  10107. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  10108. Assert(pnodeCatch);
  10109. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  10110. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  10111. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  10112. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  10113. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  10114. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  10115. if (funcInfo->byteCodeFunction->IsCoroutine())
  10116. {
  10117. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10118. }
  10119. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10120. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10121. if (funcInfo->byteCodeFunction->IsCoroutine())
  10122. {
  10123. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10124. }
  10125. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  10126. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10127. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  10128. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  10129. ParseNode *pnodeObj = pnodeCatch->GetParam();
  10130. Assert(pnodeObj);
  10131. Js::RegSlot location;
  10132. bool acquiredTempLocation = false;
  10133. Js::DebuggerScope *debuggerScope = nullptr;
  10134. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  10135. bool isPattern = pnodeObj->nop == knopParamPattern;
  10136. if (isPattern)
  10137. {
  10138. location = pnodeObj->AsParseNodeParamPattern()->location;
  10139. }
  10140. else
  10141. {
  10142. location = pnodeObj->AsParseNodeName()->sym->GetLocation();
  10143. }
  10144. if (location == Js::Constants::NoRegister)
  10145. {
  10146. location = funcInfo->AcquireLoc(pnodeObj);
  10147. acquiredTempLocation = true;
  10148. }
  10149. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10150. Scope *scope = pnodeCatch->scope;
  10151. byteCodeGenerator->PushScope(scope);
  10152. if (scope->GetMustInstantiate())
  10153. {
  10154. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10155. if (scope->GetIsObject())
  10156. {
  10157. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10158. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10159. }
  10160. else
  10161. {
  10162. int index = Js::DebuggerScope::InvalidScopeIndex;
  10163. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10164. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10165. }
  10166. }
  10167. else
  10168. {
  10169. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10170. }
  10171. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10172. {
  10173. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10174. {
  10175. Assert(scope->GetMustInstantiate());
  10176. if (scope->GetIsObject())
  10177. {
  10178. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10179. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10180. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10181. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10182. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10183. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10184. }
  10185. else
  10186. {
  10187. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10188. if (initializeParam)
  10189. {
  10190. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10191. }
  10192. else
  10193. {
  10194. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10195. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10196. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10197. funcInfo->ReleaseTmpRegister(tmpReg);
  10198. }
  10199. }
  10200. }
  10201. else
  10202. {
  10203. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10204. if (initializeParam)
  10205. {
  10206. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10207. }
  10208. else
  10209. {
  10210. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10211. }
  10212. }
  10213. };
  10214. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10215. if (isPattern)
  10216. {
  10217. Parser::MapBindIdentifier(pnodeObj->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  10218. {
  10219. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10220. if (itemLocation == Js::Constants::NoRegister)
  10221. {
  10222. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10223. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10224. itemLocation = ByteCodeGenerator::ReturnRegister;
  10225. }
  10226. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10227. });
  10228. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10229. // Now emitting bytecode for destructuring pattern
  10230. byteCodeGenerator->StartStatement(pnodeCatch);
  10231. ParseNodePtr pnode1 = pnodeObj->AsParseNodeParamPattern()->pnode1;
  10232. Assert(pnode1->IsPattern());
  10233. if (funcInfo->byteCodeFunction->IsCoroutine())
  10234. {
  10235. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10236. }
  10237. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10238. byteCodeGenerator->EndStatement(pnodeCatch);
  10239. }
  10240. else
  10241. {
  10242. ParamTrackAndInitialization(pnodeObj->AsParseNodeName()->sym, true /*initializeParam*/, location);
  10243. if (scope->GetMustInstantiate())
  10244. {
  10245. pnodeObj->AsParseNodeName()->sym->SetIsGlobalCatch(true);
  10246. }
  10247. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10248. // Allow a debugger to stop on the 'catch (e)'
  10249. byteCodeGenerator->StartStatement(pnodeCatch);
  10250. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10251. byteCodeGenerator->EndStatement(pnodeCatch);
  10252. if (funcInfo->byteCodeFunction->IsCoroutine())
  10253. {
  10254. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10255. }
  10256. }
  10257. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10258. if (funcInfo->byteCodeFunction->IsCoroutine())
  10259. {
  10260. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10261. }
  10262. byteCodeGenerator->PopScope();
  10263. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10264. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10265. if (acquiredTempLocation)
  10266. {
  10267. funcInfo->ReleaseLoc(pnodeObj);
  10268. }
  10269. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10270. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10271. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10272. break;
  10273. }
  10274. case knopTryFinally:
  10275. {
  10276. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10277. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10278. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10279. Assert(pnodeTry);
  10280. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10281. Assert(pnodeFinally);
  10282. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10283. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10284. Js::RegSlot regException = Js::Constants::NoRegister;
  10285. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10286. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10287. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10288. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10289. // For now, if the function is generator we are using the TryFinallyWithYield.
  10290. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  10291. if (funcInfo->byteCodeFunction->IsCoroutine())
  10292. {
  10293. regException = funcInfo->AcquireTmpRegister();
  10294. regOffset = funcInfo->AcquireTmpRegister();
  10295. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10296. tryRecForTry.reg1 = regException;
  10297. tryRecForTry.reg2 = regOffset;
  10298. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10299. }
  10300. else
  10301. {
  10302. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10303. }
  10304. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10305. funcInfo->StartRecordingOutArgs(1);
  10306. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10307. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10308. if (funcInfo->byteCodeFunction->IsCoroutine())
  10309. {
  10310. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10311. }
  10312. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10313. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10314. // Note: although we don't use OpCode::Leave for finally block,
  10315. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10316. // This has to be on offset prior to offset of 1st statement of finally.
  10317. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10318. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10319. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10320. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10321. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  10322. if (funcInfo->byteCodeFunction->IsCoroutine())
  10323. {
  10324. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  10325. }
  10326. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10327. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  10328. if (funcInfo->byteCodeFunction->IsCoroutine())
  10329. {
  10330. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10331. funcInfo->ReleaseTmpRegister(regOffset);
  10332. funcInfo->ReleaseTmpRegister(regException);
  10333. }
  10334. funcInfo->EndRecordingOutArgs(1);
  10335. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10336. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  10337. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  10338. break;
  10339. }
  10340. case knopThrow:
  10341. byteCodeGenerator->StartStatement(pnode);
  10342. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10343. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  10344. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10345. byteCodeGenerator->EndStatement(pnode);
  10346. break;
  10347. case knopYieldLeaf:
  10348. byteCodeGenerator->StartStatement(pnode);
  10349. funcInfo->AcquireLoc(pnode);
  10350. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  10351. byteCodeGenerator->EndStatement(pnode);
  10352. break;
  10353. case knopAwait:
  10354. case knopYield:
  10355. byteCodeGenerator->StartStatement(pnode);
  10356. funcInfo->AcquireLoc(pnode);
  10357. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10358. EmitYield(pnode->AsParseNodeUni()->pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  10359. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10360. byteCodeGenerator->EndStatement(pnode);
  10361. break;
  10362. case knopYieldStar:
  10363. byteCodeGenerator->StartStatement(pnode);
  10364. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  10365. byteCodeGenerator->EndStatement(pnode);
  10366. break;
  10367. case knopExportDefault:
  10368. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10369. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  10370. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  10371. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  10372. break;
  10373. default:
  10374. AssertMsg(0, "emit unhandled pnode op");
  10375. break;
  10376. }
  10377. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  10378. {
  10379. // If this statement may produce the global function's return value, copy its result to the return register.
  10380. // fReturnValue implies global function, which implies that "return" is a parse error.
  10381. Assert(funcInfo->IsGlobalFunction());
  10382. Assert(pnode->nop != knopReturn);
  10383. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  10384. }
  10385. }