ByteCodeGenerator.cpp 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286
  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 "Library/StackScriptFunction.h"
  8. #if DBG
  9. #include "pnodewalk.h"
  10. #endif
  11. void PreVisitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  12. void PostVisitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  13. bool IsCallOfConstants(ParseNode *pnode)
  14. {
  15. return pnode->AsParseNodeCall()->callOfConstants && pnode->AsParseNodeCall()->argCount > ByteCodeGenerator::MinArgumentsForCallOptimization;
  16. }
  17. template <class PrefixFn, class PostfixFn>
  18. void Visit(ParseNode *pnode, ByteCodeGenerator* byteCodeGenerator, PrefixFn prefix, PostfixFn postfix, ParseNode * pnodeParent = nullptr);
  19. //the only point of this type (as opposed to using a lambda) is to provide a named type in code coverage
  20. template <typename TContext> class ParseNodeVisitor
  21. {
  22. TContext* m_context;
  23. void(*m_fn)(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, TContext* context);
  24. public:
  25. ParseNodeVisitor(TContext* ctx, void(*prefixParam)(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, TContext* context)) :
  26. m_context(ctx), m_fn(prefixParam)
  27. {
  28. }
  29. void operator () (ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator)
  30. {
  31. if (m_fn)
  32. {
  33. m_fn(pnode, byteCodeGenerator, m_context);
  34. }
  35. }
  36. };
  37. template<class TContext>
  38. void VisitIndirect(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, TContext* context,
  39. void (*prefix)(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, TContext* context),
  40. void (*postfix)(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, TContext* context))
  41. {
  42. ParseNodeVisitor<TContext> prefixHelper(context, prefix);
  43. ParseNodeVisitor<TContext> postfixHelper(context, postfix);
  44. Visit(pnode, byteCodeGenerator, prefixHelper, postfixHelper, nullptr);
  45. }
  46. template <class PrefixFn, class PostfixFn>
  47. void VisitList(ParseNode *pnode, ByteCodeGenerator* byteCodeGenerator, PrefixFn prefix, PostfixFn postfix)
  48. {
  49. Assert(pnode != nullptr);
  50. Assert(pnode->nop == knopList);
  51. do
  52. {
  53. ParseNode * pnode1 = pnode->AsParseNodeBin()->pnode1;
  54. Visit(pnode1, byteCodeGenerator, prefix, postfix);
  55. pnode = pnode->AsParseNodeBin()->pnode2;
  56. }
  57. while (pnode->nop == knopList);
  58. Visit(pnode, byteCodeGenerator, prefix, postfix);
  59. }
  60. template <class PrefixFn, class PostfixFn>
  61. void VisitWithStmt(ParseNode *pnode, Js::RegSlot loc, ByteCodeGenerator* byteCodeGenerator, PrefixFn prefix, PostfixFn postfix, ParseNode *pnodeParent)
  62. {
  63. // Note the fact that we're visiting the body of a with statement. This allows us to optimize register assignment
  64. // in the normal case of calls not requiring that their "this" objects be found dynamically.
  65. Scope *scope = pnode->AsParseNodeWith()->scope;
  66. byteCodeGenerator->PushScope(scope);
  67. Visit(pnode->AsParseNodeWith()->pnodeBody, byteCodeGenerator, prefix, postfix, pnodeParent);
  68. scope->SetIsObject();
  69. scope->SetMustInstantiate(true);
  70. byteCodeGenerator->PopScope();
  71. }
  72. bool BlockHasOwnScope(ParseNodeBlock* pnodeBlock, ByteCodeGenerator *byteCodeGenerator)
  73. {
  74. Assert(pnodeBlock->nop == knopBlock);
  75. return pnodeBlock->scope != nullptr &&
  76. (!(pnodeBlock->grfpn & fpnSyntheticNode) ||
  77. (pnodeBlock->blockType == PnodeBlockType::Global && byteCodeGenerator->IsEvalWithNoParentScopeInfo()));
  78. }
  79. void BeginVisitBlock(ParseNodeBlock *pnode, ByteCodeGenerator *byteCodeGenerator)
  80. {
  81. if (BlockHasOwnScope(pnode, byteCodeGenerator))
  82. {
  83. Scope *scope = pnode->scope;
  84. FuncInfo *func = scope->GetFunc();
  85. if (scope->IsInnerScope())
  86. {
  87. // Give this scope an index so its slots can be accessed via the index in the byte code,
  88. // not a register.
  89. scope->SetInnerScopeIndex(func->AcquireInnerScopeIndex());
  90. }
  91. byteCodeGenerator->PushBlock(pnode);
  92. byteCodeGenerator->PushScope(pnode->scope);
  93. }
  94. }
  95. void EndVisitBlock(ParseNodeBlock *pnode, ByteCodeGenerator *byteCodeGenerator)
  96. {
  97. if (BlockHasOwnScope(pnode, byteCodeGenerator))
  98. {
  99. Scope *scope = pnode->scope;
  100. FuncInfo *func = scope->GetFunc();
  101. if (!(byteCodeGenerator->IsInDebugMode() || func->byteCodeFunction->IsCoroutine())
  102. && scope->HasInnerScopeIndex())
  103. {
  104. // In debug mode (or for the generator/async function), don't release the current index, as we're giving each scope a unique index, regardless
  105. // of nesting.
  106. Assert(scope->GetInnerScopeIndex() == func->CurrentInnerScopeIndex());
  107. func->ReleaseInnerScopeIndex();
  108. }
  109. Assert(byteCodeGenerator->GetCurrentScope() == scope);
  110. byteCodeGenerator->PopScope();
  111. byteCodeGenerator->PopBlock();
  112. }
  113. }
  114. void BeginVisitCatch(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  115. {
  116. Scope *scope = pnode->AsParseNodeCatch()->scope;
  117. FuncInfo *func = scope->GetFunc();
  118. if (func->GetCallsEval() || func->GetChildCallsEval() ||
  119. (byteCodeGenerator->GetFlags() & (fscrEval | fscrImplicitThis)))
  120. {
  121. scope->SetIsObject();
  122. }
  123. // Give this scope an index so its slots can be accessed via the index in the byte code,
  124. // not a register.
  125. scope->SetInnerScopeIndex(func->AcquireInnerScopeIndex());
  126. byteCodeGenerator->PushScope(pnode->AsParseNodeCatch()->scope);
  127. }
  128. void EndVisitCatch(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  129. {
  130. Scope *scope = pnode->AsParseNodeCatch()->scope;
  131. FuncInfo *func = scope->GetFunc();
  132. if (scope->HasInnerScopeIndex() && !(byteCodeGenerator->IsInDebugMode() || func->byteCodeFunction->IsCoroutine()))
  133. {
  134. // In debug mode (or for the generator/async function), don't release the current index, as we're giving each scope a unique index,
  135. // regardless of nesting.
  136. Assert(scope->GetInnerScopeIndex() == func->CurrentInnerScopeIndex());
  137. func->ReleaseInnerScopeIndex();
  138. }
  139. byteCodeGenerator->PopScope();
  140. }
  141. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  142. {
  143. #if ENABLE_PROFILE_INFO
  144. Js::FunctionBody *functionBody = funcInfo ? funcInfo->GetParsedFunctionBody() : nullptr;
  145. return
  146. !PHASE_OFF_OPTFUNC(Js::NativeArrayPhase, functionBody) &&
  147. !byteCodeGenerator->IsInDebugMode() &&
  148. (
  149. functionBody
  150. ? Js::DynamicProfileInfo::IsEnabled(Js::NativeArrayPhase, functionBody)
  151. : Js::DynamicProfileInfo::IsEnabledForAtLeastOneFunction(
  152. Js::NativeArrayPhase,
  153. byteCodeGenerator->GetScriptContext())
  154. );
  155. #else
  156. return false;
  157. #endif
  158. }
  159. bool EmitAsConstantArray(ParseNode *pnodeArr, ByteCodeGenerator *byteCodeGenerator)
  160. {
  161. Assert(pnodeArr && pnodeArr->nop == knopArray);
  162. // TODO: We shouldn't have to handle an empty funcinfo stack here, but there seem to be issues
  163. // with the stack involved nested deferral. Remove this null check when those are resolved.
  164. if (CreateNativeArrays(byteCodeGenerator, byteCodeGenerator->TopFuncInfo()))
  165. {
  166. return pnodeArr->AsParseNodeArrLit()->arrayOfNumbers;
  167. }
  168. return pnodeArr->AsParseNodeArrLit()->arrayOfTaggedInts && pnodeArr->AsParseNodeArrLit()->count > 1;
  169. }
  170. void PropagateFlags(ParseNode *pnodeChild, ParseNode *pnodeParent);
  171. template<class PrefixFn, class PostfixFn>
  172. void Visit(ParseNode *pnode, ByteCodeGenerator* byteCodeGenerator, PrefixFn prefix, PostfixFn postfix, ParseNode *pnodeParent)
  173. {
  174. if (pnode == nullptr)
  175. {
  176. return;
  177. }
  178. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  179. prefix(pnode, byteCodeGenerator);
  180. switch (pnode->nop)
  181. {
  182. default:
  183. {
  184. uint flags = ParseNode::Grfnop(pnode->nop);
  185. if (flags&fnopUni)
  186. {
  187. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  188. }
  189. else if (flags&fnopBin)
  190. {
  191. Visit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, prefix, postfix);
  192. Visit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, prefix, postfix);
  193. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  194. {
  195. Visit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, prefix, postfix);
  196. }
  197. }
  198. break;
  199. }
  200. case knopParamPattern:
  201. Visit(pnode->AsParseNodeParamPattern()->pnode1, byteCodeGenerator, prefix, postfix);
  202. break;
  203. case knopArrayPattern:
  204. if (!byteCodeGenerator->InDestructuredPattern())
  205. {
  206. byteCodeGenerator->SetInDestructuredPattern(true);
  207. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  208. byteCodeGenerator->SetInDestructuredPattern(false);
  209. }
  210. else
  211. {
  212. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  213. }
  214. break;
  215. case knopCall:
  216. Visit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, prefix, postfix);
  217. Visit(pnode->AsParseNodeCall()->pnodeArgs, byteCodeGenerator, prefix, postfix);
  218. if (pnode->AsParseNodeCall()->isSuperCall)
  219. {
  220. Visit(pnode->AsParseNodeSuperCall()->pnodeThis, byteCodeGenerator, prefix, postfix);
  221. Visit(pnode->AsParseNodeSuperCall()->pnodeNewTarget, byteCodeGenerator, prefix, postfix);
  222. }
  223. break;
  224. case knopNew:
  225. {
  226. Visit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, prefix, postfix);
  227. if (!IsCallOfConstants(pnode))
  228. {
  229. Visit(pnode->AsParseNodeCall()->pnodeArgs, byteCodeGenerator, prefix, postfix);
  230. }
  231. break;
  232. }
  233. case knopQmark:
  234. Visit(pnode->AsParseNodeTri()->pnode1, byteCodeGenerator, prefix, postfix);
  235. Visit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, prefix, postfix);
  236. Visit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, prefix, postfix);
  237. break;
  238. case knopList:
  239. VisitList(pnode, byteCodeGenerator, prefix, postfix);
  240. break;
  241. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  242. case knopVarDecl:
  243. case knopConstDecl:
  244. case knopLetDecl:
  245. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  246. Visit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, prefix, postfix);
  247. break;
  248. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  249. case knopFncDecl:
  250. {
  251. // Inner function declarations are visited before anything else in the scope.
  252. // (See VisitFunctionsInScope.)
  253. break;
  254. }
  255. case knopClassDecl:
  256. {
  257. Visit(pnode->AsParseNodeClass()->pnodeDeclName, byteCodeGenerator, prefix, postfix);
  258. // Now visit the class name and methods.
  259. BeginVisitBlock(pnode->AsParseNodeClass()->pnodeBlock, byteCodeGenerator);
  260. // The extends clause is bound to the scope which contains the class name
  261. // (and the class name identifier is in a TDZ when the extends clause is evaluated).
  262. // See ES 2017 14.5.13 Runtime Semantics: ClassDefinitionEvaluation.
  263. Visit(pnode->AsParseNodeClass()->pnodeExtends, byteCodeGenerator, prefix, postfix);
  264. Visit(pnode->AsParseNodeClass()->pnodeName, byteCodeGenerator, prefix, postfix);
  265. Visit(pnode->AsParseNodeClass()->pnodeStaticMembers, byteCodeGenerator, prefix, postfix);
  266. Visit(pnode->AsParseNodeClass()->pnodeConstructor, byteCodeGenerator, prefix, postfix);
  267. Visit(pnode->AsParseNodeClass()->pnodeMembers, byteCodeGenerator, prefix, postfix);
  268. EndVisitBlock(pnode->AsParseNodeClass()->pnodeBlock, byteCodeGenerator);
  269. break;
  270. }
  271. case knopStrTemplate:
  272. {
  273. // Visit the string node lists only if we do not have a tagged template.
  274. // We never need to visit the raw strings as they are not used in non-tagged templates and
  275. // tagged templates will register them as part of the callsite constant object.
  276. if (!pnode->AsParseNodeStrTemplate()->isTaggedTemplate)
  277. {
  278. Visit(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, byteCodeGenerator, prefix, postfix);
  279. }
  280. Visit(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, byteCodeGenerator, prefix, postfix);
  281. break;
  282. }
  283. case knopExportDefault:
  284. Visit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, prefix, postfix);
  285. break;
  286. // PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  287. case knopProg:
  288. {
  289. // We expect that the global statements have been generated (meaning that the pnodeFncs
  290. // field is a real pointer, not an enumeration).
  291. Assert(pnode->AsParseNodeFnc()->pnodeBody);
  292. uint i = 0;
  293. VisitNestedScopes(pnode->AsParseNodeFnc()->pnodeScopes, pnode, byteCodeGenerator, prefix, postfix, &i);
  294. // Visiting global code: track the last value statement.
  295. BeginVisitBlock(pnode->AsParseNodeFnc()->pnodeScopes, byteCodeGenerator);
  296. pnode->AsParseNodeProg()->pnodeLastValStmt = VisitBlock(pnode->AsParseNodeFnc()->pnodeBody, byteCodeGenerator, prefix, postfix);
  297. EndVisitBlock(pnode->AsParseNodeFnc()->pnodeScopes, byteCodeGenerator);
  298. break;
  299. }
  300. case knopFor:
  301. BeginVisitBlock(pnode->AsParseNodeFor()->pnodeBlock, byteCodeGenerator);
  302. Visit(pnode->AsParseNodeFor()->pnodeInit, byteCodeGenerator, prefix, postfix);
  303. byteCodeGenerator->EnterLoop();
  304. Visit(pnode->AsParseNodeFor()->pnodeCond, byteCodeGenerator, prefix, postfix);
  305. Visit(pnode->AsParseNodeFor()->pnodeIncr, byteCodeGenerator, prefix, postfix);
  306. Visit(pnode->AsParseNodeFor()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  307. byteCodeGenerator->ExitLoop();
  308. EndVisitBlock(pnode->AsParseNodeFor()->pnodeBlock, byteCodeGenerator);
  309. break;
  310. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  311. case knopIf:
  312. Visit(pnode->AsParseNodeIf()->pnodeCond, byteCodeGenerator, prefix, postfix);
  313. Visit(pnode->AsParseNodeIf()->pnodeTrue, byteCodeGenerator, prefix, postfix, pnode);
  314. if (pnode->AsParseNodeIf()->pnodeFalse != nullptr)
  315. {
  316. Visit(pnode->AsParseNodeIf()->pnodeFalse, byteCodeGenerator, prefix, postfix, pnode);
  317. }
  318. break;
  319. // PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  320. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  321. case knopDoWhile:
  322. case knopWhile:
  323. byteCodeGenerator->EnterLoop();
  324. Visit(pnode->AsParseNodeWhile()->pnodeCond, byteCodeGenerator, prefix, postfix);
  325. Visit(pnode->AsParseNodeWhile()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  326. byteCodeGenerator->ExitLoop();
  327. break;
  328. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  329. case knopForIn:
  330. case knopForOf:
  331. case knopForAwaitOf:
  332. BeginVisitBlock(pnode->AsParseNodeForInOrForOf()->pnodeBlock, byteCodeGenerator);
  333. Visit(pnode->AsParseNodeForInOrForOf()->pnodeLval, byteCodeGenerator, prefix, postfix);
  334. Visit(pnode->AsParseNodeForInOrForOf()->pnodeObj, byteCodeGenerator, prefix, postfix);
  335. byteCodeGenerator->EnterLoop();
  336. Visit(pnode->AsParseNodeForInOrForOf()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  337. byteCodeGenerator->ExitLoop();
  338. EndVisitBlock(pnode->AsParseNodeForInOrForOf()->pnodeBlock, byteCodeGenerator);
  339. break;
  340. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  341. case knopReturn:
  342. if (pnode->AsParseNodeReturn()->pnodeExpr != nullptr)
  343. Visit(pnode->AsParseNodeReturn()->pnodeExpr, byteCodeGenerator, prefix, postfix);
  344. break;
  345. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  346. case knopBlock:
  347. {
  348. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  349. if (pnodeBlock->pnodeStmt != nullptr)
  350. {
  351. BeginVisitBlock(pnodeBlock, byteCodeGenerator);
  352. pnodeBlock->pnodeLastValStmt = VisitBlock(pnodeBlock->pnodeStmt, byteCodeGenerator, prefix, postfix, pnode);
  353. EndVisitBlock(pnodeBlock, byteCodeGenerator);
  354. }
  355. else
  356. {
  357. pnodeBlock->pnodeLastValStmt = nullptr;
  358. }
  359. break;
  360. }
  361. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  362. case knopWith:
  363. Visit(pnode->AsParseNodeWith()->pnodeObj, byteCodeGenerator, prefix, postfix);
  364. VisitWithStmt(pnode, pnode->AsParseNodeWith()->pnodeObj->location, byteCodeGenerator, prefix, postfix, pnode);
  365. break;
  366. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  367. case knopBreak:
  368. // TODO: some representation of target
  369. break;
  370. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  371. case knopContinue:
  372. // TODO: some representation of target
  373. break;
  374. // PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  375. case knopSwitch:
  376. Visit(pnode->AsParseNodeSwitch()->pnodeVal, byteCodeGenerator, prefix, postfix);
  377. BeginVisitBlock(pnode->AsParseNodeSwitch()->pnodeBlock, byteCodeGenerator);
  378. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; nullptr != pnodeT; pnodeT = pnodeT->pnodeNext)
  379. {
  380. Visit(pnodeT, byteCodeGenerator, prefix, postfix, pnode);
  381. }
  382. Visit(pnode->AsParseNodeSwitch()->pnodeBlock, byteCodeGenerator, prefix, postfix);
  383. EndVisitBlock(pnode->AsParseNodeSwitch()->pnodeBlock, byteCodeGenerator);
  384. break;
  385. // PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  386. case knopCase:
  387. Visit(pnode->AsParseNodeCase()->pnodeExpr, byteCodeGenerator, prefix, postfix);
  388. Visit(pnode->AsParseNodeCase()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  389. break;
  390. case knopTypeof:
  391. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  392. break;
  393. // PTNODE(knopTryCatchFinally,"try-catch-finally",None,TryCatchFinally,fnopCleanup)
  394. case knopTryFinally:
  395. Visit(pnode->AsParseNodeTryFinally()->pnodeTry, byteCodeGenerator, prefix, postfix, pnode);
  396. Visit(pnode->AsParseNodeTryFinally()->pnodeFinally, byteCodeGenerator, prefix, postfix, pnode);
  397. break;
  398. // PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  399. case knopTryCatch:
  400. Visit(pnode->AsParseNodeTryCatch()->pnodeTry, byteCodeGenerator, prefix, postfix, pnode);
  401. Visit(pnode->AsParseNodeTryCatch()->pnodeCatch, byteCodeGenerator, prefix, postfix, pnode);
  402. break;
  403. // PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  404. case knopTry:
  405. Visit(pnode->AsParseNodeTry()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  406. break;
  407. case knopCatch:
  408. BeginVisitCatch(pnode, byteCodeGenerator);
  409. Visit(pnode->AsParseNodeCatch()->GetParam(), byteCodeGenerator, prefix, postfix);
  410. Visit(pnode->AsParseNodeCatch()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  411. EndVisitCatch(pnode, byteCodeGenerator);
  412. break;
  413. case knopFinally:
  414. Visit(pnode->AsParseNodeFinally()->pnodeBody, byteCodeGenerator, prefix, postfix, pnode);
  415. break;
  416. // PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  417. case knopThrow:
  418. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  419. break;
  420. case knopArray:
  421. {
  422. bool arrayLitOpt = EmitAsConstantArray(pnode, byteCodeGenerator);
  423. if (!arrayLitOpt)
  424. {
  425. Visit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, prefix, postfix);
  426. }
  427. break;
  428. }
  429. case knopComma:
  430. {
  431. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  432. if (pnode1->nop == knopComma)
  433. {
  434. // Spot-fix to avoid recursion on very large comma expressions.
  435. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  436. SList<ParseNode*> rhsStack(alloc);
  437. do
  438. {
  439. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  440. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  441. }
  442. while (pnode1->nop == knopComma);
  443. Visit(pnode1, byteCodeGenerator, prefix, postfix);
  444. while (!rhsStack.Empty())
  445. {
  446. ParseNode *pnodeRhs = rhsStack.Pop();
  447. Visit(pnodeRhs, byteCodeGenerator, prefix, postfix);
  448. }
  449. }
  450. else
  451. {
  452. Visit(pnode1, byteCodeGenerator, prefix, postfix);
  453. }
  454. Visit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, prefix, postfix);
  455. }
  456. break;
  457. }
  458. if (pnodeParent)
  459. {
  460. PropagateFlags(pnode, pnodeParent);
  461. }
  462. postfix(pnode, byteCodeGenerator);
  463. }
  464. bool IsJump(ParseNode *pnode)
  465. {
  466. switch (pnode->nop)
  467. {
  468. case knopBreak:
  469. case knopContinue:
  470. case knopThrow:
  471. case knopReturn:
  472. return true;
  473. case knopBlock:
  474. case knopDoWhile:
  475. case knopWhile:
  476. case knopWith:
  477. case knopIf:
  478. case knopForIn:
  479. case knopForOf:
  480. case knopForAwaitOf:
  481. case knopFor:
  482. case knopSwitch:
  483. case knopCase:
  484. case knopTryFinally:
  485. case knopTryCatch:
  486. case knopTry:
  487. case knopCatch:
  488. case knopFinally:
  489. return (pnode->AsParseNodeStmt()->grfnop & fnopJump) != 0;
  490. default:
  491. return false;
  492. }
  493. }
  494. void PropagateFlags(ParseNode *pnodeChild, ParseNode *pnodeParent)
  495. {
  496. if (IsJump(pnodeChild))
  497. {
  498. pnodeParent->AsParseNodeStmt()->grfnop |= fnopJump;
  499. }
  500. }
  501. void Bind(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator);
  502. void BindReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator);
  503. void AssignRegisters(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator);
  504. // TODO[ianhall]: This should be in a shared AST Utility header or source file
  505. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext)
  506. {
  507. if (stmt->nop == knopFncDecl)
  508. {
  509. // 'knopFncDecl' is used for both function declarations and function expressions. In a program, a function expression
  510. // produces the function object that is created for the function expression as its value for the program. A function
  511. // declaration does not produce a value for the program.
  512. return !stmt->AsParseNodeFnc()->IsDeclaration();
  513. }
  514. if ((stmt->nop >= 0) && (stmt->nop<knopLim))
  515. {
  516. return (ParseNode::Grfnop(stmt->nop) & fnopNotExprStmt) == 0;
  517. }
  518. return false;
  519. }
  520. bool MustProduceValue(ParseNode *pnode, const Js::ScriptContext *const scriptContext)
  521. {
  522. // Determine whether the current statement is guaranteed to produce a value.
  523. if (IsExpressionStatement(pnode, scriptContext))
  524. {
  525. // These are trivially true.
  526. return true;
  527. }
  528. for (;;)
  529. {
  530. switch (pnode->nop)
  531. {
  532. case knopFor:
  533. // Check the common "for (;;)" case.
  534. if (pnode->AsParseNodeFor()->pnodeCond != nullptr ||
  535. pnode->AsParseNodeFor()->pnodeBody == nullptr)
  536. {
  537. return false;
  538. }
  539. // Loop body is always executed. Look at the loop body next.
  540. pnode = pnode->AsParseNodeFor()->pnodeBody;
  541. break;
  542. case knopIf:
  543. // True only if both "if" and "else" exist, and both produce values.
  544. if (pnode->AsParseNodeIf()->pnodeTrue == nullptr ||
  545. pnode->AsParseNodeIf()->pnodeFalse == nullptr)
  546. {
  547. return false;
  548. }
  549. if (!MustProduceValue(pnode->AsParseNodeIf()->pnodeFalse, scriptContext))
  550. {
  551. return false;
  552. }
  553. pnode = pnode->AsParseNodeIf()->pnodeTrue;
  554. break;
  555. case knopWhile:
  556. // Check the common "while (1)" case.
  557. if (pnode->AsParseNodeWhile()->pnodeBody == nullptr ||
  558. (pnode->AsParseNodeWhile()->pnodeCond &&
  559. (pnode->AsParseNodeWhile()->pnodeCond->nop != knopInt ||
  560. pnode->AsParseNodeWhile()->pnodeCond->AsParseNodeInt()->lw == 0)))
  561. {
  562. return false;
  563. }
  564. // Loop body is always executed. Look at the loop body next.
  565. pnode = pnode->AsParseNodeWhile()->pnodeBody;
  566. break;
  567. case knopDoWhile:
  568. if (pnode->AsParseNodeWhile()->pnodeBody == nullptr)
  569. {
  570. return false;
  571. }
  572. // Loop body is always executed. Look at the loop body next.
  573. pnode = pnode->AsParseNodeWhile()->pnodeBody;
  574. break;
  575. case knopBlock:
  576. return pnode->AsParseNodeBlock()->pnodeLastValStmt != nullptr;
  577. case knopWith:
  578. if (pnode->AsParseNodeWith()->pnodeBody == nullptr)
  579. {
  580. return false;
  581. }
  582. pnode = pnode->AsParseNodeWith()->pnodeBody;
  583. break;
  584. case knopSwitch:
  585. {
  586. // This is potentially the most inefficient case. We could consider adding a flag to the PnSwitch
  587. // struct and computing it when we visit the switch, but:
  588. // a. switch statements at global scope shouldn't be that common;
  589. // b. switch statements with many arms shouldn't be that common;
  590. // c. switches without default cases can be trivially skipped.
  591. if (pnode->AsParseNodeSwitch()->pnodeDefault == nullptr)
  592. {
  593. // Can't guarantee that any code is executed.
  594. return false;
  595. }
  596. ParseNodeCase *pnodeCase;
  597. for (pnodeCase = pnode->AsParseNodeSwitch()->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  598. {
  599. if (pnodeCase->pnodeBody == nullptr)
  600. {
  601. if (pnodeCase->pnodeNext == nullptr)
  602. {
  603. // Last case has no code to execute.
  604. return false;
  605. }
  606. // Fall through to the next case.
  607. }
  608. else
  609. {
  610. if (!MustProduceValue(pnodeCase->pnodeBody, scriptContext))
  611. {
  612. return false;
  613. }
  614. }
  615. }
  616. return true;
  617. }
  618. case knopTryCatch:
  619. // True only if both try and catch produce a value.
  620. if (pnode->AsParseNodeTryCatch()->pnodeTry->pnodeBody == nullptr ||
  621. pnode->AsParseNodeTryCatch()->pnodeCatch->pnodeBody == nullptr)
  622. {
  623. return false;
  624. }
  625. if (!MustProduceValue(pnode->AsParseNodeTryCatch()->pnodeCatch->pnodeBody, scriptContext))
  626. {
  627. return false;
  628. }
  629. pnode = pnode->AsParseNodeTryCatch()->pnodeTry->pnodeBody;
  630. break;
  631. case knopTryFinally:
  632. if (pnode->AsParseNodeTryFinally()->pnodeFinally->pnodeBody == nullptr)
  633. {
  634. // No finally body: look at the try body.
  635. if (pnode->AsParseNodeTryFinally()->pnodeTry->pnodeBody == nullptr)
  636. {
  637. return false;
  638. }
  639. pnode = pnode->AsParseNodeTryFinally()->pnodeTry->pnodeBody;
  640. break;
  641. }
  642. // Skip the try body, since the finally body will always follow it.
  643. pnode = pnode->AsParseNodeTryFinally()->pnodeFinally->pnodeBody;
  644. break;
  645. default:
  646. return false;
  647. }
  648. }
  649. }
  650. ByteCodeGenerator::ByteCodeGenerator(Js::ScriptContext* scriptContext, Js::ScopeInfo* parentScopeInfo) :
  651. alloc(nullptr),
  652. scriptContext(scriptContext),
  653. flags(0),
  654. funcInfoStack(nullptr),
  655. pRootFunc(nullptr),
  656. pCurrentFunction(nullptr),
  657. globalScope(nullptr),
  658. currentScope(nullptr),
  659. parentScopeInfo(parentScopeInfo),
  660. dynamicScopeCount(0),
  661. isBinding(false),
  662. inDestructuredPattern(false)
  663. {
  664. m_writer.Create();
  665. }
  666. void ByteCodeGenerator::FinalizeFuncInfos()
  667. {
  668. if (this->funcInfosToFinalize == nullptr)
  669. {
  670. return;
  671. }
  672. FOREACH_SLIST_ENTRY(FuncInfo*, funcInfo, this->funcInfosToFinalize)
  673. {
  674. if (funcInfo->canDefer)
  675. {
  676. funcInfo->byteCodeFunction->SetAttributes((Js::FunctionInfo::Attributes)(funcInfo->byteCodeFunction->GetAttributes() | Js::FunctionInfo::Attributes::CanDefer));
  677. }
  678. }
  679. NEXT_SLIST_ENTRY;
  680. this->funcInfosToFinalize = nullptr;
  681. }
  682. void ByteCodeGenerator::AddFuncInfoToFinalizationSet(FuncInfo * funcInfo)
  683. {
  684. if (this->funcInfosToFinalize == nullptr)
  685. {
  686. this->funcInfosToFinalize = Anew(alloc, SList<FuncInfo*>, alloc);
  687. }
  688. this->funcInfosToFinalize->Prepend(funcInfo);
  689. }
  690. /* static */
  691. bool ByteCodeGenerator::IsFalse(ParseNode* node)
  692. {
  693. return (node->nop == knopInt && node->AsParseNodeInt()->lw == 0) || node->nop == knopFalse;
  694. }
  695. /* static */
  696. bool ByteCodeGenerator::IsThis(ParseNode* pnode)
  697. {
  698. return pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isThis;
  699. }
  700. /* static */
  701. bool ByteCodeGenerator::IsSuper(ParseNode* pnode)
  702. {
  703. return pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper;
  704. }
  705. bool ByteCodeGenerator::IsES6DestructuringEnabled() const
  706. {
  707. return scriptContext->GetConfig()->IsES6DestructuringEnabled();
  708. }
  709. bool ByteCodeGenerator::IsES6ForLoopSemanticsEnabled() const
  710. {
  711. return scriptContext->GetConfig()->IsES6ForLoopSemanticsEnabled();
  712. }
  713. // ByteCodeGenerator debug mode means we are generating debug mode user-code. Library code is always in non-debug mode.
  714. bool ByteCodeGenerator::IsInDebugMode() const
  715. {
  716. return m_utf8SourceInfo->IsInDebugMode();
  717. }
  718. // ByteCodeGenerator non-debug mode means we are not debugging, or we are generating library code which is always in non-debug mode.
  719. bool ByteCodeGenerator::IsInNonDebugMode() const
  720. {
  721. return scriptContext->IsScriptContextInNonDebugMode() || m_utf8SourceInfo->GetIsLibraryCode();
  722. }
  723. bool ByteCodeGenerator::ShouldTrackDebuggerMetadata() const
  724. {
  725. return (IsInDebugMode())
  726. #if DBG_DUMP
  727. || (Js::Configuration::Global.flags.Debug)
  728. #endif
  729. ;
  730. }
  731. void ByteCodeGenerator::SetRootFuncInfo(FuncInfo* func)
  732. {
  733. Assert(pRootFunc == nullptr || pRootFunc == func->byteCodeFunction || !IsInNonDebugMode());
  734. if ((this->flags & fscrImplicitThis) && !this->HasParentScopeInfo())
  735. {
  736. // Mark a top-level event handler, since it will need to construct the "this" pointer's
  737. // namespace hierarchy to access globals.
  738. Assert(!func->IsGlobalFunction());
  739. func->SetIsTopLevelEventHandler(true);
  740. }
  741. if (pRootFunc)
  742. {
  743. return;
  744. }
  745. this->pRootFunc = func->byteCodeFunction->GetParseableFunctionInfo();
  746. this->m_utf8SourceInfo->AddTopLevelFunctionInfo(func->byteCodeFunction->GetFunctionInfo(), scriptContext->GetRecycler());
  747. }
  748. Js::RegSlot ByteCodeGenerator::NextVarRegister()
  749. {
  750. return funcInfoStack->Top()->NextVarRegister();
  751. }
  752. Js::RegSlot ByteCodeGenerator::NextConstRegister()
  753. {
  754. return funcInfoStack->Top()->NextConstRegister();
  755. }
  756. FuncInfo * ByteCodeGenerator::TopFuncInfo() const
  757. {
  758. return funcInfoStack->Empty() ? nullptr : funcInfoStack->Top();
  759. }
  760. void ByteCodeGenerator::EnterLoop()
  761. {
  762. if (this->TopFuncInfo())
  763. {
  764. this->TopFuncInfo()->hasLoop = true;
  765. }
  766. loopDepth++;
  767. }
  768. void ByteCodeGenerator::SetHasTry(bool has)
  769. {
  770. TopFuncInfo()->GetParsedFunctionBody()->SetHasTry(has);
  771. }
  772. void ByteCodeGenerator::SetHasFinally(bool has)
  773. {
  774. TopFuncInfo()->GetParsedFunctionBody()->SetHasFinally(has);
  775. }
  776. // TODO: per-function register assignment for env and global symbols
  777. void ByteCodeGenerator::AssignRegister(Symbol *sym)
  778. {
  779. AssertMsg(sym->GetDecl() == nullptr || sym->GetDecl()->nop != knopConstDecl || sym->GetDecl()->nop != knopLetDecl,
  780. "const and let should get only temporary register, assigned during emit stage");
  781. if (sym->GetLocation() == Js::Constants::NoRegister)
  782. {
  783. sym->SetLocation(NextVarRegister());
  784. }
  785. }
  786. void ByteCodeGenerator::AddTargetStmt(ParseNodeStmt *pnodeStmt)
  787. {
  788. FuncInfo *top = funcInfoStack->Top();
  789. top->AddTargetStmt(pnodeStmt);
  790. }
  791. Js::RegSlot ByteCodeGenerator::AssignThisConstRegister()
  792. {
  793. FuncInfo *top = funcInfoStack->Top();
  794. return top->AssignThisConstRegister();
  795. }
  796. Js::RegSlot ByteCodeGenerator::AssignNullConstRegister()
  797. {
  798. FuncInfo *top = funcInfoStack->Top();
  799. return top->AssignNullConstRegister();
  800. }
  801. Js::RegSlot ByteCodeGenerator::AssignUndefinedConstRegister()
  802. {
  803. FuncInfo *top = funcInfoStack->Top();
  804. return top->AssignUndefinedConstRegister();
  805. }
  806. Js::RegSlot ByteCodeGenerator::AssignTrueConstRegister()
  807. {
  808. FuncInfo *top = funcInfoStack->Top();
  809. return top->AssignTrueConstRegister();
  810. }
  811. Js::RegSlot ByteCodeGenerator::AssignFalseConstRegister()
  812. {
  813. FuncInfo *top = funcInfoStack->Top();
  814. return top->AssignFalseConstRegister();
  815. }
  816. void ByteCodeGenerator::SetNeedEnvRegister()
  817. {
  818. FuncInfo *top = funcInfoStack->Top();
  819. top->SetNeedEnvRegister();
  820. }
  821. void ByteCodeGenerator::AssignFrameObjRegister()
  822. {
  823. FuncInfo* top = funcInfoStack->Top();
  824. if (top->frameObjRegister == Js::Constants::NoRegister)
  825. {
  826. top->frameObjRegister = top->NextVarRegister();
  827. }
  828. }
  829. void ByteCodeGenerator::AssignFrameDisplayRegister()
  830. {
  831. FuncInfo* top = funcInfoStack->Top();
  832. if (top->frameDisplayRegister == Js::Constants::NoRegister)
  833. {
  834. top->frameDisplayRegister = top->NextVarRegister();
  835. }
  836. }
  837. void ByteCodeGenerator::AssignFrameSlotsRegister()
  838. {
  839. FuncInfo* top = funcInfoStack->Top();
  840. if (top->frameSlotsRegister == Js::Constants::NoRegister)
  841. {
  842. top->frameSlotsRegister = NextVarRegister();
  843. }
  844. }
  845. void ByteCodeGenerator::AssignParamSlotsRegister()
  846. {
  847. FuncInfo* top = funcInfoStack->Top();
  848. Assert(top->paramSlotsRegister == Js::Constants::NoRegister);
  849. top->paramSlotsRegister = NextVarRegister();
  850. }
  851. void ByteCodeGenerator::SetNumberOfInArgs(Js::ArgSlot argCount)
  852. {
  853. FuncInfo *top = funcInfoStack->Top();
  854. top->inArgsCount = argCount;
  855. }
  856. Js::RegSlot ByteCodeGenerator::EnregisterConstant(unsigned int constant)
  857. {
  858. Js::RegSlot loc = Js::Constants::NoRegister;
  859. FuncInfo *top = funcInfoStack->Top();
  860. if (!top->constantToRegister.TryGetValue(constant, &loc))
  861. {
  862. loc = NextConstRegister();
  863. top->constantToRegister.Add(constant, loc);
  864. }
  865. return loc;
  866. }
  867. Js::RegSlot ByteCodeGenerator::EnregisterBigIntConstant(ParseNode* pnode)
  868. {
  869. Js::RegSlot loc = Js::Constants::NoRegister;
  870. FuncInfo *top = funcInfoStack->Top();
  871. if (!top->bigintToRegister.TryGetValue(pnode, &loc))
  872. {
  873. loc = NextConstRegister();
  874. top->bigintToRegister.Add(pnode, loc);
  875. }
  876. return loc;
  877. }
  878. Js::RegSlot ByteCodeGenerator::EnregisterStringConstant(IdentPtr pid)
  879. {
  880. Js::RegSlot loc = Js::Constants::NoRegister;
  881. FuncInfo *top = funcInfoStack->Top();
  882. if (!top->stringToRegister.TryGetValue(pid, &loc))
  883. {
  884. loc = NextConstRegister();
  885. top->stringToRegister.Add(pid, loc);
  886. }
  887. return loc;
  888. }
  889. Js::RegSlot ByteCodeGenerator::EnregisterDoubleConstant(double d)
  890. {
  891. Js::RegSlot loc = Js::Constants::NoRegister;
  892. FuncInfo *top = funcInfoStack->Top();
  893. if (!top->TryGetDoubleLoc(d, &loc))
  894. {
  895. loc = NextConstRegister();
  896. top->AddDoubleConstant(d, loc);
  897. }
  898. return loc;
  899. }
  900. Js::RegSlot ByteCodeGenerator::EnregisterStringTemplateCallsiteConstant(ParseNode* pnode)
  901. {
  902. Assert(pnode->nop == knopStrTemplate);
  903. Assert(pnode->AsParseNodeStrTemplate()->isTaggedTemplate);
  904. Js::RegSlot loc = Js::Constants::NoRegister;
  905. FuncInfo* top = funcInfoStack->Top();
  906. if (!top->stringTemplateCallsiteRegisterMap.TryGetValue(pnode, &loc))
  907. {
  908. loc = NextConstRegister();
  909. top->stringTemplateCallsiteRegisterMap.Add(pnode, loc);
  910. }
  911. return loc;
  912. }
  913. //
  914. // Restore all outer func scope info when reparsing a deferred func.
  915. //
  916. void ByteCodeGenerator::RestoreScopeInfo(Js::ScopeInfo *scopeInfo, FuncInfo * func)
  917. {
  918. if (scopeInfo)
  919. {
  920. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackByteCodeVisitor);
  921. Js::ParseableFunctionInfo * pfi = scopeInfo->GetFunctionInfo()->GetParseableFunctionInfo();
  922. bool newFunc = (func == nullptr || func->byteCodeFunction != pfi);
  923. if (newFunc)
  924. {
  925. func = Anew(alloc, FuncInfo, pfi->GetDisplayName(), alloc, this, nullptr, nullptr, nullptr, pfi);
  926. }
  927. // Recursively restore enclosing scope info so outermost scopes/funcs are pushed first.
  928. this->RestoreScopeInfo(scopeInfo->GetParentScopeInfo(), func);
  929. this->RestoreOneScope(scopeInfo, func);
  930. if (newFunc)
  931. {
  932. PushFuncInfo(_u("RestoreScopeInfo"), func);
  933. if (!pfi->DoStackNestedFunc())
  934. {
  935. func->hasEscapedUseNestedFunc = true;
  936. }
  937. }
  938. }
  939. else
  940. {
  941. Assert(this->TopFuncInfo() == nullptr);
  942. // funcBody is glo
  943. Assert(currentScope == nullptr);
  944. currentScope = Anew(alloc, Scope, alloc, ScopeType_Global);
  945. globalScope = currentScope;
  946. if (func == nullptr || !func->byteCodeFunction->GetIsGlobalFunc())
  947. {
  948. func = Anew(alloc, FuncInfo, Js::Constants::GlobalFunction,
  949. alloc, this, nullptr, nullptr/*currentScope*/, nullptr, nullptr/*functionBody*/);
  950. PushFuncInfo(_u("RestoreScopeInfo"), func);
  951. }
  952. func->SetBodyScope(currentScope);
  953. }
  954. }
  955. void ByteCodeGenerator::RestoreOneScope(Js::ScopeInfo * scopeInfo, FuncInfo * func)
  956. {
  957. TRACE_BYTECODE(_u("\nRestore ScopeInfo: %s #symbols: %d %s\n"),
  958. func->name, scopeInfo->GetSymbolCount(), scopeInfo->IsObject() ? _u("isObject") : _u(""));
  959. Scope * scope = scopeInfo->GetScope();
  960. scope->SetFunc(func);
  961. switch (scope->GetScopeType())
  962. {
  963. case ScopeType_Parameter:
  964. Assert(func->GetParamScope() == nullptr);
  965. func->SetParamScope(scope);
  966. break;
  967. case ScopeType_FuncExpr:
  968. Assert(func->GetFuncExprScope() == nullptr);
  969. func->SetFuncExprScope(scope);
  970. break;
  971. case ScopeType_FunctionBody:
  972. case ScopeType_GlobalEvalBlock:
  973. Assert(func->GetBodyScope() == nullptr || (func->GetBodyScope()->GetScopeType() == ScopeType_Global && scope->GetScopeType() == ScopeType_GlobalEvalBlock));
  974. func->SetBodyScope(scope);
  975. func->SetHasCachedScope(scopeInfo->IsCached());
  976. break;
  977. }
  978. Assert(!scopeInfo->IsCached() || scope == func->GetBodyScope());
  979. // scopeInfo->scope was created/saved during parsing.
  980. // We no longer need it by now.
  981. // Clear it to avoid GC false positive (arena memory later used by GC).
  982. scopeInfo->SetScope(nullptr);
  983. this->PushScope(scope);
  984. }
  985. FuncInfo * ByteCodeGenerator::StartBindGlobalStatements(ParseNodeProg *pnode)
  986. {
  987. if (parentScopeInfo)
  988. {
  989. trackEnvDepth = true;
  990. RestoreScopeInfo(parentScopeInfo, nullptr);
  991. trackEnvDepth = false;
  992. // "currentScope" is the parentFunc scope. This ensures the deferred func declaration
  993. // symbol will bind to the func declaration symbol already available in parentFunc scope.
  994. }
  995. else
  996. {
  997. currentScope = pnode->scope;
  998. Assert(currentScope);
  999. globalScope = currentScope;
  1000. }
  1001. Js::FunctionBody * byteCodeFunction;
  1002. if (!IsInNonDebugMode() && this->pCurrentFunction != nullptr && this->pCurrentFunction->GetIsGlobalFunc() && !this->pCurrentFunction->IsFakeGlobalFunc(flags))
  1003. {
  1004. // we will re-use the global FunctionBody which was created before deferred parse.
  1005. byteCodeFunction = this->pCurrentFunction;
  1006. byteCodeFunction->RemoveDeferParseAttribute();
  1007. byteCodeFunction->ResetByteCodeGenVisitState();
  1008. }
  1009. else if ((this->flags & fscrDeferredFnc))
  1010. {
  1011. byteCodeFunction = this->EnsureFakeGlobalFuncForUndefer(pnode);
  1012. }
  1013. else
  1014. {
  1015. byteCodeFunction = this->MakeGlobalFunctionBody(pnode);
  1016. // Mark this global function to required for register script event
  1017. byteCodeFunction->SetIsTopLevel(true);
  1018. if (pnode->GetStrictMode() != 0)
  1019. {
  1020. byteCodeFunction->SetIsStrictMode();
  1021. }
  1022. }
  1023. if (byteCodeFunction->IsReparsed())
  1024. {
  1025. byteCodeFunction->RestoreState(pnode);
  1026. }
  1027. else
  1028. {
  1029. byteCodeFunction->SaveState(pnode);
  1030. }
  1031. FuncInfo *funcInfo = Anew(alloc, FuncInfo, Js::Constants::GlobalFunction,
  1032. alloc, this, nullptr, globalScope, pnode, byteCodeFunction);
  1033. int32 currentAstSize = pnode->astSize;
  1034. if (currentAstSize > this->maxAstSize)
  1035. {
  1036. this->maxAstSize = currentAstSize;
  1037. }
  1038. PushFuncInfo(_u("StartBindGlobalStatements"), funcInfo);
  1039. return funcInfo;
  1040. }
  1041. void ByteCodeGenerator::AssignPropertyId(IdentPtr pid)
  1042. {
  1043. if (pid->GetPropertyId() == Js::Constants::NoProperty)
  1044. {
  1045. Js::PropertyId id = TopFuncInfo()->byteCodeFunction->GetOrAddPropertyIdTracked(SymbolName(pid->Psz(), pid->Cch()));
  1046. pid->SetPropertyId(id);
  1047. }
  1048. }
  1049. void ByteCodeGenerator::AssignPropertyId(Symbol *sym, Js::ParseableFunctionInfo* functionInfo)
  1050. {
  1051. sym->SetPosition(functionInfo->GetOrAddPropertyIdTracked(sym->GetName()));
  1052. }
  1053. template <class PrefixFn, class PostfixFn>
  1054. ParseNode* VisitBlock(ParseNode *pnode, ByteCodeGenerator* byteCodeGenerator, PrefixFn prefix, PostfixFn postfix, ParseNode *pnodeParent = nullptr)
  1055. {
  1056. ParseNode *pnodeLastVal = nullptr;
  1057. if (pnode != nullptr)
  1058. {
  1059. bool fTrackVal = byteCodeGenerator->IsBinding() &&
  1060. (byteCodeGenerator->GetFlags() & fscrReturnExpression) &&
  1061. byteCodeGenerator->TopFuncInfo()->IsGlobalFunction();
  1062. while (pnode->nop == knopList)
  1063. {
  1064. Visit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, prefix, postfix, pnodeParent);
  1065. if (fTrackVal)
  1066. {
  1067. // If we're tracking values, find the last statement (if any) in the block that is
  1068. // guaranteed to produce a value.
  1069. if (MustProduceValue(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator->GetScriptContext()))
  1070. {
  1071. pnodeLastVal = pnode->AsParseNodeBin()->pnode1;
  1072. }
  1073. if (IsJump(pnode->AsParseNodeBin()->pnode1))
  1074. {
  1075. // This is a jump out of the current block. The remaining instructions (if any)
  1076. // will not be executed, so stop tracking them.
  1077. fTrackVal = false;
  1078. }
  1079. }
  1080. pnode = pnode->AsParseNodeBin()->pnode2;
  1081. }
  1082. Visit(pnode, byteCodeGenerator, prefix, postfix, pnodeParent);
  1083. if (fTrackVal)
  1084. {
  1085. if (MustProduceValue(pnode, byteCodeGenerator->GetScriptContext()))
  1086. {
  1087. pnodeLastVal = pnode;
  1088. }
  1089. }
  1090. }
  1091. return pnodeLastVal;
  1092. }
  1093. // Attributes that should be consistent between defer parse and full parse.
  1094. static const Js::FunctionInfo::Attributes StableFunctionInfoAttributesMask = (Js::FunctionInfo::Attributes)
  1095. (
  1096. Js::FunctionInfo::Attributes::ErrorOnNew |
  1097. Js::FunctionInfo::Attributes::Async |
  1098. Js::FunctionInfo::Attributes::Lambda |
  1099. Js::FunctionInfo::Attributes::SuperReference |
  1100. Js::FunctionInfo::Attributes::ClassConstructor |
  1101. Js::FunctionInfo::Attributes::BaseConstructorKind |
  1102. Js::FunctionInfo::Attributes::ClassMethod |
  1103. Js::FunctionInfo::Attributes::Method |
  1104. Js::FunctionInfo::Attributes::Generator |
  1105. Js::FunctionInfo::Attributes::Module |
  1106. Js::FunctionInfo::Attributes::ComputedName |
  1107. Js::FunctionInfo::Attributes::HomeObj
  1108. );
  1109. static Js::FunctionInfo::Attributes GetFunctionInfoAttributes(ParseNodeFnc * pnodeFnc)
  1110. {
  1111. Js::FunctionInfo::Attributes attributes = Js::FunctionInfo::Attributes::None;
  1112. if (pnodeFnc->IsAsync())
  1113. {
  1114. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ErrorOnNew | Js::FunctionInfo::Attributes::Async);
  1115. }
  1116. if (pnodeFnc->IsLambda())
  1117. {
  1118. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ErrorOnNew | Js::FunctionInfo::Attributes::Lambda);
  1119. }
  1120. if (pnodeFnc->HasSuperReference())
  1121. {
  1122. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::SuperReference);
  1123. }
  1124. if (pnodeFnc->IsClassMember())
  1125. {
  1126. if (pnodeFnc->IsClassConstructor())
  1127. {
  1128. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ClassConstructor);
  1129. if (pnodeFnc->IsBaseClassConstructor())
  1130. {
  1131. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::BaseConstructorKind);
  1132. }
  1133. }
  1134. else
  1135. {
  1136. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ErrorOnNew | Js::FunctionInfo::Attributes::ClassMethod);
  1137. }
  1138. }
  1139. if (pnodeFnc->IsMethod())
  1140. {
  1141. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::Method);
  1142. // #sec-runtime-semantics-classdefinitionevaluation calls #sec-makeconstructor. #sec-makeconstructor
  1143. // creates a prototype. Thus a method that is a class constructor has a prototype and should not
  1144. // throw an error when new is called on the method.
  1145. if (!pnodeFnc->IsClassConstructor())
  1146. {
  1147. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ErrorOnNew);
  1148. }
  1149. }
  1150. if (pnodeFnc->IsGenerator())
  1151. {
  1152. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::Generator);
  1153. }
  1154. if (pnodeFnc->IsAccessor())
  1155. {
  1156. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ErrorOnNew);
  1157. }
  1158. if (pnodeFnc->IsModule())
  1159. {
  1160. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::Module);
  1161. }
  1162. if (pnodeFnc->CanBeDeferred())
  1163. {
  1164. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::CanDefer);
  1165. }
  1166. if (pnodeFnc->HasComputedName() && pnodeFnc->pnodeName == nullptr)
  1167. {
  1168. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::ComputedName);
  1169. }
  1170. if (pnodeFnc->HasHomeObj())
  1171. {
  1172. attributes = (Js::FunctionInfo::Attributes)(attributes | Js::FunctionInfo::Attributes::HomeObj);
  1173. }
  1174. return attributes;
  1175. }
  1176. FuncInfo * ByteCodeGenerator::StartBindFunction(const char16 *name, uint nameLength, uint shortNameOffset, bool* pfuncExprWithName, ParseNodeFnc *pnodeFnc, Js::ParseableFunctionInfo * reuseNestedFunc)
  1177. {
  1178. bool funcExprWithName;
  1179. Js::ParseableFunctionInfo* parseableFunctionInfo = nullptr;
  1180. Js::AutoRestoreFunctionInfo autoRestoreFunctionInfo(reuseNestedFunc, reuseNestedFunc ? reuseNestedFunc->GetOriginalEntryPoint_Unchecked() : nullptr);
  1181. if (this->pCurrentFunction &&
  1182. this->pCurrentFunction->IsFunctionParsed())
  1183. {
  1184. Assert(this->pCurrentFunction->StartInDocument() == pnodeFnc->ichMin);
  1185. Assert(this->pCurrentFunction->LengthInChars() == pnodeFnc->LengthInCodepoints());
  1186. // This is the root function for the current AST subtree, and it already has a FunctionBody
  1187. // (created by a deferred parse) which we're now filling in.
  1188. Js::FunctionBody * parsedFunctionBody = this->pCurrentFunction;
  1189. parsedFunctionBody->RemoveDeferParseAttribute();
  1190. Assert(!parsedFunctionBody->IsDeferredParseFunction() || parsedFunctionBody->IsReparsed());
  1191. pnodeFnc->SetDeclaration(parsedFunctionBody->GetIsDeclaration());
  1192. if (!pnodeFnc->CanBeDeferred())
  1193. {
  1194. parsedFunctionBody->SetAttributes(
  1195. (Js::FunctionInfo::Attributes)(parsedFunctionBody->GetAttributes() & ~Js::FunctionInfo::Attributes::CanDefer));
  1196. }
  1197. funcExprWithName =
  1198. !(parsedFunctionBody->GetIsDeclaration() || pnodeFnc->IsMethod()) &&
  1199. pnodeFnc->pnodeName != nullptr &&
  1200. pnodeFnc->pnodeName->nop == knopVarDecl;
  1201. *pfuncExprWithName = funcExprWithName;
  1202. Assert(parsedFunctionBody->GetLocalFunctionId() == pnodeFnc->functionId || !IsInNonDebugMode());
  1203. // Some state may be tracked on the function body during the visit pass. Since the previous visit pass may have failed,
  1204. // we need to reset the state on the function body.
  1205. parsedFunctionBody->ResetByteCodeGenVisitState();
  1206. if (parsedFunctionBody->GetScopeInfo())
  1207. {
  1208. // Propagate flags from the (real) parent function.
  1209. Js::ParseableFunctionInfo *parent = parsedFunctionBody->GetScopeInfo()->GetParseableFunctionInfo();
  1210. if (parent)
  1211. {
  1212. if (parent->GetHasOrParentHasArguments())
  1213. {
  1214. parsedFunctionBody->SetHasOrParentHasArguments(true);
  1215. }
  1216. }
  1217. }
  1218. parseableFunctionInfo = parsedFunctionBody;
  1219. }
  1220. else
  1221. {
  1222. funcExprWithName = *pfuncExprWithName;
  1223. Js::LocalFunctionId functionId = pnodeFnc->functionId;
  1224. // Create a function body if:
  1225. // 1. The parse node is not defer parsed
  1226. // 2. Or creating function proxies is disallowed
  1227. bool createFunctionBody = (pnodeFnc->pnodeBody != nullptr);
  1228. if (!CONFIG_FLAG(CreateFunctionProxy)) createFunctionBody = true;
  1229. const Js::FunctionInfo::Attributes attributes = GetFunctionInfoAttributes(pnodeFnc);
  1230. if (createFunctionBody)
  1231. {
  1232. if (reuseNestedFunc)
  1233. {
  1234. if (!reuseNestedFunc->IsFunctionBody())
  1235. {
  1236. reuseNestedFunc->GetUtf8SourceInfo()->StopTrackingDeferredFunction(reuseNestedFunc->GetLocalFunctionId());
  1237. Js::FunctionBody * parsedFunctionBody =
  1238. Js::FunctionBody::NewFromParseableFunctionInfo(reuseNestedFunc->GetParseableFunctionInfo());
  1239. autoRestoreFunctionInfo.funcBody = parsedFunctionBody;
  1240. parseableFunctionInfo = parsedFunctionBody;
  1241. }
  1242. else
  1243. {
  1244. parseableFunctionInfo = reuseNestedFunc->GetFunctionBody();
  1245. }
  1246. Assert((parseableFunctionInfo->GetAttributes() & StableFunctionInfoAttributesMask) == (attributes & StableFunctionInfoAttributesMask));
  1247. }
  1248. else
  1249. {
  1250. parseableFunctionInfo = Js::FunctionBody::NewFromRecycler(scriptContext, name, nameLength, shortNameOffset, pnodeFnc->nestedCount, m_utf8SourceInfo,
  1251. m_utf8SourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId, functionId
  1252. , attributes
  1253. , pnodeFnc->IsClassConstructor() ?
  1254. Js::FunctionBody::FunctionBodyFlags::Flags_None :
  1255. Js::FunctionBody::FunctionBodyFlags::Flags_HasNoExplicitReturnValue
  1256. #ifdef PERF_COUNTERS
  1257. , false /* is function from deferred deserialized proxy */
  1258. #endif
  1259. );
  1260. }
  1261. }
  1262. else
  1263. {
  1264. if (reuseNestedFunc)
  1265. {
  1266. Assert(!reuseNestedFunc->IsFunctionBody() || reuseNestedFunc->GetFunctionBody()->GetByteCode() != nullptr);
  1267. Assert(pnodeFnc->pnodeBody == nullptr);
  1268. parseableFunctionInfo = reuseNestedFunc;
  1269. Assert((parseableFunctionInfo->GetAttributes() & StableFunctionInfoAttributesMask) == (attributes & StableFunctionInfoAttributesMask));
  1270. }
  1271. else
  1272. {
  1273. parseableFunctionInfo = Js::ParseableFunctionInfo::New(scriptContext, pnodeFnc->nestedCount, functionId, m_utf8SourceInfo, name, nameLength, shortNameOffset, attributes,
  1274. pnodeFnc->IsClassConstructor() ?
  1275. Js::FunctionBody::FunctionBodyFlags::Flags_None :
  1276. Js::FunctionBody::FunctionBodyFlags::Flags_HasNoExplicitReturnValue);
  1277. }
  1278. }
  1279. // In either case register the function reference
  1280. scriptContext->GetLibrary()->RegisterDynamicFunctionReference(parseableFunctionInfo);
  1281. #if DBG
  1282. parseableFunctionInfo->deferredParseNextFunctionId = pnodeFnc->deferredParseNextFunctionId;
  1283. #endif
  1284. parseableFunctionInfo->SetIsDeclaration(pnodeFnc->IsDeclaration() != 0);
  1285. parseableFunctionInfo->SetIsMethod(pnodeFnc->IsMethod() != 0);
  1286. parseableFunctionInfo->SetIsAccessor(pnodeFnc->IsAccessor() != 0);
  1287. if (pnodeFnc->IsAccessor())
  1288. {
  1289. scriptContext->optimizationOverrides.SetSideEffects(Js::SideEffects_Accessor);
  1290. }
  1291. }
  1292. Scope *funcExprScope = nullptr;
  1293. if (funcExprWithName)
  1294. {
  1295. funcExprScope = pnodeFnc->scope;
  1296. Assert(funcExprScope);
  1297. PushScope(funcExprScope);
  1298. Symbol *sym = AddSymbolToScope(funcExprScope, name, nameLength, pnodeFnc->pnodeName, STFunction);
  1299. sym->SetIsFuncExpr(true);
  1300. sym->SetPosition(parseableFunctionInfo->GetOrAddPropertyIdTracked(sym->GetName()));
  1301. pnodeFnc->SetFuncSymbol(sym);
  1302. if (funcExprScope->GetIsObject())
  1303. {
  1304. funcExprScope->SetMustInstantiate(true);
  1305. }
  1306. }
  1307. Scope *paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  1308. Scope *bodyScope = pnodeFnc->pnodeBodyScope ? pnodeFnc->pnodeBodyScope->scope : nullptr;
  1309. Assert(paramScope != nullptr || !pnodeFnc->pnodeScopes);
  1310. if (paramScope == nullptr)
  1311. {
  1312. paramScope = Anew(alloc, Scope, alloc, ScopeType_Parameter, true);
  1313. if (pnodeFnc->pnodeScopes)
  1314. {
  1315. pnodeFnc->pnodeScopes->scope = paramScope;
  1316. }
  1317. }
  1318. if (bodyScope == nullptr)
  1319. {
  1320. bodyScope = Anew(alloc, Scope, alloc, ScopeType_FunctionBody, true);
  1321. if (pnodeFnc->pnodeBodyScope)
  1322. {
  1323. pnodeFnc->pnodeBodyScope->scope = bodyScope;
  1324. }
  1325. }
  1326. AssertMsg(pnodeFnc->nop == knopFncDecl, "Non-function declaration trying to create function body");
  1327. parseableFunctionInfo->SetIsGlobalFunc(false);
  1328. if (pnodeFnc->GetStrictMode() != 0)
  1329. {
  1330. parseableFunctionInfo->SetIsStrictMode();
  1331. }
  1332. FuncInfo *funcInfo = Anew(alloc, FuncInfo, name, alloc, this, paramScope, bodyScope, pnodeFnc, parseableFunctionInfo);
  1333. #if DBG
  1334. funcInfo->isReused = (reuseNestedFunc != nullptr);
  1335. #endif
  1336. if (pnodeFnc->GetArgumentsObjectEscapes())
  1337. {
  1338. // If the parser detected that the arguments object escapes, then the function scope escapes
  1339. // and cannot be cached.
  1340. this->FuncEscapes(bodyScope);
  1341. funcInfo->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("ArgumentsObjectEscapes")));
  1342. }
  1343. if (parseableFunctionInfo->IsFunctionBody())
  1344. {
  1345. Js::FunctionBody * parsedFunctionBody = parseableFunctionInfo->GetFunctionBody();
  1346. if (parsedFunctionBody->IsReparsed())
  1347. {
  1348. parsedFunctionBody->RestoreState(pnodeFnc);
  1349. }
  1350. else
  1351. {
  1352. parsedFunctionBody->SaveState(pnodeFnc);
  1353. }
  1354. }
  1355. funcInfo->SetChildCallsEval(!!pnodeFnc->ChildCallsEval());
  1356. if (pnodeFnc->CallsEval())
  1357. {
  1358. funcInfo->SetCallsEval(true);
  1359. bodyScope->SetIsDynamic(true);
  1360. bodyScope->SetIsObject();
  1361. bodyScope->SetCapturesAll(true);
  1362. bodyScope->SetMustInstantiate(true);
  1363. // Do not mark param scope as dynamic as it does not leak declarations
  1364. paramScope->SetIsObject();
  1365. paramScope->SetCapturesAll(true);
  1366. paramScope->SetMustInstantiate(true);
  1367. }
  1368. PushFuncInfo(_u("StartBindFunction"), funcInfo);
  1369. if (funcExprScope)
  1370. {
  1371. funcExprScope->SetFunc(funcInfo);
  1372. funcInfo->funcExprScope = funcExprScope;
  1373. }
  1374. int32 currentAstSize = pnodeFnc->astSize;
  1375. if (currentAstSize > this->maxAstSize)
  1376. {
  1377. this->maxAstSize = currentAstSize;
  1378. }
  1379. autoRestoreFunctionInfo.Clear();
  1380. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  1381. {
  1382. funcInfo->ResetBodyAndParamScopeMerged();
  1383. }
  1384. return funcInfo;
  1385. }
  1386. void ByteCodeGenerator::EndBindFunction(bool funcExprWithName)
  1387. {
  1388. bool isGlobalScope = currentScope->GetScopeType() == ScopeType_Global;
  1389. Assert(currentScope->GetScopeType() == ScopeType_FunctionBody || isGlobalScope);
  1390. PopScope(); // function body
  1391. if (isGlobalScope)
  1392. {
  1393. Assert(currentScope == nullptr);
  1394. }
  1395. else
  1396. {
  1397. Assert(currentScope->GetScopeType() == ScopeType_Parameter);
  1398. PopScope(); // parameter scope
  1399. }
  1400. if (funcExprWithName)
  1401. {
  1402. Assert(currentScope->GetScopeType() == ScopeType_FuncExpr);
  1403. PopScope();
  1404. }
  1405. funcInfoStack->Pop();
  1406. }
  1407. void ByteCodeGenerator::StartBindCatch(ParseNode *pnode)
  1408. {
  1409. Scope *scope = pnode->AsParseNodeCatch()->scope;
  1410. Assert(scope);
  1411. Assert(currentScope);
  1412. scope->SetFunc(currentScope->GetFunc());
  1413. PushScope(scope);
  1414. }
  1415. void ByteCodeGenerator::EndBindCatch()
  1416. {
  1417. PopScope();
  1418. }
  1419. void ByteCodeGenerator::PushScope(Scope *innerScope)
  1420. {
  1421. Assert(innerScope != nullptr);
  1422. innerScope->SetEnclosingScope(currentScope);
  1423. currentScope = innerScope;
  1424. if (currentScope->GetIsDynamic())
  1425. {
  1426. this->dynamicScopeCount++;
  1427. }
  1428. if (this->trackEnvDepth && currentScope->GetMustInstantiate())
  1429. {
  1430. this->envDepth++;
  1431. if (this->envDepth == 0)
  1432. {
  1433. Js::Throw::OutOfMemory();
  1434. }
  1435. }
  1436. }
  1437. void ByteCodeGenerator::PopScope()
  1438. {
  1439. Assert(currentScope != nullptr);
  1440. if (this->trackEnvDepth && currentScope->GetMustInstantiate())
  1441. {
  1442. this->envDepth--;
  1443. Assert(this->envDepth != (uint16)-1);
  1444. }
  1445. if (currentScope->GetIsDynamic())
  1446. {
  1447. this->dynamicScopeCount--;
  1448. }
  1449. currentScope = currentScope->GetEnclosingScope();
  1450. }
  1451. void ByteCodeGenerator::PushBlock(ParseNodeBlock *pnode)
  1452. {
  1453. pnode->SetEnclosingBlock(currentBlock);
  1454. currentBlock = pnode;
  1455. }
  1456. void ByteCodeGenerator::PopBlock()
  1457. {
  1458. currentBlock = currentBlock->GetEnclosingBlock();
  1459. }
  1460. void ByteCodeGenerator::PushFuncInfo(char16 const * location, FuncInfo* funcInfo)
  1461. {
  1462. // We might have multiple global scope for deferparse.
  1463. // Assert(!funcInfo->IsGlobalFunction() || this->TopFuncInfo() == nullptr || this->TopFuncInfo()->IsGlobalFunction());
  1464. if (PHASE_TRACE1(Js::ByteCodePhase))
  1465. {
  1466. Output::Print(_u("%s: PushFuncInfo: %s"), location, funcInfo->name);
  1467. if (this->TopFuncInfo())
  1468. {
  1469. Output::Print(_u(" Top: %s"), this->TopFuncInfo()->name);
  1470. }
  1471. Output::Print(_u("\n"));
  1472. Output::Flush();
  1473. }
  1474. funcInfoStack->Push(funcInfo);
  1475. }
  1476. void ByteCodeGenerator::PopFuncInfo(char16 const * location)
  1477. {
  1478. FuncInfo * funcInfo = funcInfoStack->Pop();
  1479. // Assert(!funcInfo->IsGlobalFunction() || this->TopFuncInfo() == nullptr || this->TopFuncInfo()->IsGlobalFunction());
  1480. if (PHASE_TRACE1(Js::ByteCodePhase))
  1481. {
  1482. Output::Print(_u("%s: PopFuncInfo: %s"), location, funcInfo->name);
  1483. if (this->TopFuncInfo())
  1484. {
  1485. Output::Print(_u(" Top: %s"), this->TopFuncInfo()->name);
  1486. }
  1487. Output::Print(_u("\n"));
  1488. Output::Flush();
  1489. }
  1490. }
  1491. Symbol * ByteCodeGenerator::FindSymbol(Symbol **symRef, IdentPtr pid, bool forReference)
  1492. {
  1493. const char16 *key = nullptr;
  1494. Symbol *sym = nullptr;
  1495. Assert(symRef);
  1496. if (*symRef)
  1497. {
  1498. sym = *symRef;
  1499. }
  1500. else
  1501. {
  1502. this->AssignPropertyId(pid);
  1503. return nullptr;
  1504. }
  1505. key = reinterpret_cast<const char16*>(sym->GetPid()->Psz());
  1506. Scope *symScope = sym->GetScope();
  1507. Assert(symScope);
  1508. #if DBG_DUMP
  1509. if (this->Trace())
  1510. {
  1511. if (sym != nullptr)
  1512. {
  1513. Output::Print(_u("resolved %s to symbol of type %s: \n"), key, sym->GetSymbolTypeName());
  1514. }
  1515. else
  1516. {
  1517. Output::Print(_u("did not resolve %s\n"), key);
  1518. }
  1519. }
  1520. #endif
  1521. if (!sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1522. {
  1523. FuncInfo *top = funcInfoStack->Top();
  1524. bool nonLocalRef = symScope->GetFunc() != top;
  1525. Scope *scope = nullptr;
  1526. if (forReference)
  1527. {
  1528. Js::PropertyId i;
  1529. scope = FindScopeForSym(symScope, nullptr, &i, top);
  1530. // If we have a reference to a local within a with, we want to generate a closure represented by an object.
  1531. if (scope != symScope && scope->GetIsDynamic())
  1532. {
  1533. nonLocalRef = true;
  1534. sym->SetHasNonLocalReference();
  1535. symScope->SetIsObject();
  1536. }
  1537. }
  1538. // This may not be a non-local reference, but the symbol may still be accessed non-locally. ('with', e.g.)
  1539. // In that case, make sure we still process the symbol and its scope for closure capture.
  1540. if (nonLocalRef || sym->GetHasNonLocalReference())
  1541. {
  1542. // Symbol referenced through a closure. Mark it as such and give it a property ID.
  1543. this->ProcessCapturedSym(sym);
  1544. sym->SetPosition(top->byteCodeFunction->GetOrAddPropertyIdTracked(sym->GetName()));
  1545. // If this is var is local to a function (meaning that it belongs to the function's scope
  1546. // *or* to scope that need not be instantiated, like a function expression scope, which we'll
  1547. // merge with the function scope, then indicate that fact.
  1548. this->ProcessScopeWithCapturedSym(symScope);
  1549. if (symScope->GetFunc()->GetHasArguments() && sym->GetIsFormal())
  1550. {
  1551. // A formal is referenced non-locally. We need to allocate it on the heap, so
  1552. // do the same for the whole arguments object.
  1553. // Formal is referenced. So count of formals to function > 0.
  1554. // So no need to check for inParams here.
  1555. symScope->GetFunc()->SetHasHeapArguments(true);
  1556. }
  1557. if (symScope->GetFunc() != top)
  1558. {
  1559. top->SetHasClosureReference(true);
  1560. }
  1561. }
  1562. else if (!nonLocalRef && sym->GetHasNonLocalReference() && !sym->GetIsCommittedToSlot() && !sym->HasVisitedCapturingFunc())
  1563. {
  1564. sym->SetHasNonCommittedReference(true);
  1565. }
  1566. if (sym->GetIsFuncExpr())
  1567. {
  1568. symScope->GetFunc()->SetFuncExprNameReference(true);
  1569. }
  1570. }
  1571. return sym;
  1572. }
  1573. Symbol * ByteCodeGenerator::AddSymbolToScope(Scope *scope, const char16 *key, int keyLength, ParseNode *varDecl, SymbolType symbolType)
  1574. {
  1575. Symbol *sym = nullptr;
  1576. switch (varDecl->nop)
  1577. {
  1578. case knopConstDecl:
  1579. case knopLetDecl:
  1580. case knopVarDecl:
  1581. sym = varDecl->AsParseNodeVar()->sym;
  1582. break;
  1583. case knopName:
  1584. AnalysisAssert(varDecl->AsParseNodeName()->GetSymRef());
  1585. sym = *varDecl->AsParseNodeName()->GetSymRef();
  1586. break;
  1587. default:
  1588. AnalysisAssert(0);
  1589. sym = nullptr;
  1590. break;
  1591. }
  1592. if (sym->GetScope() != scope && sym->GetScope()->GetScopeType() != ScopeType_Parameter)
  1593. {
  1594. // This can happen when we have a function declared at global eval scope, and it has
  1595. // references in deferred function bodies inside the eval. The BCG creates a new global scope
  1596. // on such compiles, so we essentially have to migrate the symbol to the new scope.
  1597. // We check fscrEvalCode, not fscrEval, because the same thing can happen in indirect eval,
  1598. // when fscrEval is not set.
  1599. Assert(scope->GetScopeType() == ScopeType_Global || scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  1600. scope->AddNewSymbol(sym);
  1601. }
  1602. Assert(sym && sym->GetScope() && (sym->GetScope() == scope || sym->GetScope()->GetScopeType() == ScopeType_Parameter));
  1603. if (sym->NeedsScopeObject())
  1604. {
  1605. scope->SetIsObject();
  1606. }
  1607. return sym;
  1608. }
  1609. Symbol * ByteCodeGenerator::AddSymbolToFunctionScope(const char16 *key, int keyLength, ParseNode *varDecl, SymbolType symbolType)
  1610. {
  1611. Scope* scope = currentScope->GetFunc()->GetBodyScope();
  1612. return this->AddSymbolToScope(scope, key, keyLength, varDecl, symbolType);
  1613. }
  1614. FuncInfo *ByteCodeGenerator::FindEnclosingNonLambda()
  1615. {
  1616. for (Scope *scope = GetCurrentScope(); scope; scope = scope->GetEnclosingScope())
  1617. {
  1618. if (!scope->GetFunc()->IsLambda())
  1619. {
  1620. return scope->GetFunc();
  1621. }
  1622. }
  1623. Assert(0);
  1624. return nullptr;
  1625. }
  1626. FuncInfo* GetParentFuncInfo(FuncInfo* child)
  1627. {
  1628. for (Scope* scope = child->GetBodyScope(); scope; scope = scope->GetEnclosingScope())
  1629. {
  1630. if (scope->GetFunc() != child)
  1631. {
  1632. return scope->GetFunc();
  1633. }
  1634. }
  1635. Assert(0);
  1636. return nullptr;
  1637. }
  1638. bool ByteCodeGenerator::CanStackNestedFunc(FuncInfo * funcInfo, bool trace)
  1639. {
  1640. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1641. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1642. #endif
  1643. Assert(!funcInfo->IsGlobalFunction());
  1644. bool const doStackNestedFunc = !funcInfo->HasMaybeEscapedNestedFunc() && !IsInDebugMode()
  1645. && !funcInfo->byteCodeFunction->IsCoroutine()
  1646. && !funcInfo->byteCodeFunction->IsModule()
  1647. && !Js::ScriptContext::ExceedsStackNestedFuncCount(funcInfo->root->nestedCount);
  1648. if (!doStackNestedFunc)
  1649. {
  1650. return false;
  1651. }
  1652. bool callsEval = funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval();
  1653. if (callsEval)
  1654. {
  1655. if (trace)
  1656. {
  1657. PHASE_PRINT_TESTTRACE(Js::StackFuncPhase, funcInfo->byteCodeFunction,
  1658. _u("HasMaybeEscapedNestedFunc (Eval): %s (function %s)\n"),
  1659. funcInfo->byteCodeFunction->GetDisplayName(),
  1660. funcInfo->byteCodeFunction->GetDebugNumberSet(debugStringBuffer));
  1661. }
  1662. return false;
  1663. }
  1664. if (funcInfo->GetBodyScope()->GetIsObject() || funcInfo->GetParamScope()->GetIsObject() || (funcInfo->GetFuncExprScope() && funcInfo->GetFuncExprScope()->GetIsObject()))
  1665. {
  1666. if (trace)
  1667. {
  1668. PHASE_PRINT_TESTTRACE(Js::StackFuncPhase, funcInfo->byteCodeFunction,
  1669. _u("HasMaybeEscapedNestedFunc (ObjectScope): %s (function %s)\n"),
  1670. funcInfo->byteCodeFunction->GetDisplayName(),
  1671. funcInfo->byteCodeFunction->GetDebugNumberSet(debugStringBuffer));
  1672. }
  1673. return false;
  1674. }
  1675. if (!funcInfo->IsBodyAndParamScopeMerged())
  1676. {
  1677. if (trace)
  1678. {
  1679. PHASE_PRINT_TESTTRACE(Js::StackFuncPhase, funcInfo->byteCodeFunction,
  1680. _u("CanStackNestedFunc: %s (Split Scope)\n"),
  1681. funcInfo->byteCodeFunction->GetDisplayName());
  1682. }
  1683. return false;
  1684. }
  1685. if (trace && funcInfo->byteCodeFunction->GetNestedCount())
  1686. {
  1687. // Only print functions that actually have nested functions, although we will still mark
  1688. // functions that don't have nested child functions as DoStackNestedFunc.
  1689. PHASE_PRINT_TESTTRACE(Js::StackFuncPhase, funcInfo->byteCodeFunction,
  1690. _u("DoStackNestedFunc: %s (function %s)\n"),
  1691. funcInfo->byteCodeFunction->GetDisplayName(),
  1692. funcInfo->byteCodeFunction->GetDebugNumberSet(debugStringBuffer));
  1693. }
  1694. return !PHASE_OFF(Js::StackFuncPhase, funcInfo->byteCodeFunction);
  1695. }
  1696. bool ByteCodeGenerator::NeedObjectAsFunctionScope(FuncInfo * funcInfo, ParseNodeFnc * pnodeFnc) const
  1697. {
  1698. return funcInfo->GetCallsEval()
  1699. || funcInfo->GetChildCallsEval()
  1700. || NeedScopeObjectForArguments(funcInfo, pnodeFnc)
  1701. || (this->flags & (fscrEval | fscrImplicitThis));
  1702. }
  1703. Scope * ByteCodeGenerator::FindScopeForSym(Scope *symScope, Scope *scope, Js::PropertyId *envIndex, FuncInfo *funcInfo) const
  1704. {
  1705. for (scope = scope ? scope->GetEnclosingScope() : currentScope; scope; scope = scope->GetEnclosingScope())
  1706. {
  1707. if (scope->GetFunc() != funcInfo
  1708. && scope->GetMustInstantiate()
  1709. && scope != this->globalScope)
  1710. {
  1711. (*envIndex)++;
  1712. }
  1713. if (scope == symScope || scope->GetIsDynamic())
  1714. {
  1715. break;
  1716. }
  1717. }
  1718. Assert(scope);
  1719. return scope;
  1720. }
  1721. /* static */
  1722. Js::OpCode ByteCodeGenerator::GetStFldOpCode(FuncInfo* funcInfo, bool isRoot, bool isLetDecl, bool isConstDecl, bool isClassMemberInit, bool forceStrictModeForClassComputedPropertyName)
  1723. {
  1724. return GetStFldOpCode(funcInfo->GetIsStrictMode() || forceStrictModeForClassComputedPropertyName, isRoot, isLetDecl, isConstDecl, isClassMemberInit);
  1725. }
  1726. /* static */
  1727. Js::OpCode ByteCodeGenerator::GetScopedStFldOpCode(FuncInfo* funcInfo, bool isConsoleScopeLetConst)
  1728. {
  1729. return GetScopedStFldOpCode(funcInfo->GetIsStrictMode(), isConsoleScopeLetConst);
  1730. }
  1731. /* static */
  1732. Js::OpCode ByteCodeGenerator::GetStElemIOpCode(FuncInfo* funcInfo)
  1733. {
  1734. return GetStElemIOpCode(funcInfo->GetIsStrictMode());
  1735. }
  1736. bool ByteCodeGenerator::DoJitLoopBodies(FuncInfo *funcInfo) const
  1737. {
  1738. // Never JIT loop bodies in a function with a try.
  1739. // Otherwise, always JIT loop bodies under /forcejitloopbody.
  1740. // Otherwise, JIT loop bodies unless we're in eval/"new Function" or feature is disabled.
  1741. Assert(funcInfo->byteCodeFunction->IsFunctionParsed());
  1742. Js::FunctionBody* functionBody = funcInfo->byteCodeFunction->GetFunctionBody();
  1743. return functionBody->ForceJITLoopBody() || funcInfo->byteCodeFunction->IsJitLoopBodyPhaseEnabled();
  1744. }
  1745. void ByteCodeGenerator::Generate(__in ParseNodeProg *pnodeProg, uint32 grfscr, __in ByteCodeGenerator* byteCodeGenerator,
  1746. __inout Js::ParseableFunctionInfo ** ppRootFunc, __in uint sourceIndex,
  1747. __in bool forceNoNative, __in Parser* parser, Js::ScriptFunction **functionRef)
  1748. {
  1749. #if DBG
  1750. struct WalkerPolicyTest : public WalkerPolicyBase<bool, ParseNodeWalker<WalkerPolicyTest>*>
  1751. {
  1752. inline bool ContinueWalk(ResultType) { return ThreadContext::IsCurrentStackAvailable(Js::Constants::MinStackByteCodeVisitor); }
  1753. virtual ResultType WalkChild(ParseNode *pnode, ParseNodeWalker<WalkerPolicyTest>* walker) { return ContinueWalk(true) && walker->Walk(pnode, walker); }
  1754. };
  1755. ParseNodeWalker<WalkerPolicyTest> walker;
  1756. // Just walk the ast to see if our walker encounters any problems
  1757. walker.Walk(pnodeProg, &walker);
  1758. #endif
  1759. Js::ScriptContext * scriptContext = byteCodeGenerator->scriptContext;
  1760. #ifdef PROFILE_EXEC
  1761. scriptContext->ProfileBegin(Js::ByteCodePhase);
  1762. #endif
  1763. JS_ETW_INTERNAL(EventWriteJSCRIPT_BYTECODEGEN_START(scriptContext, 0));
  1764. ThreadContext * threadContext = scriptContext->GetThreadContext();
  1765. Js::Utf8SourceInfo * utf8SourceInfo = scriptContext->GetSource(sourceIndex);
  1766. byteCodeGenerator->m_utf8SourceInfo = utf8SourceInfo;
  1767. // For dynamic code, just provide a small number since that source info should have very few functions
  1768. // For static code, the nextLocalFunctionId is a good guess of the initial size of the array to minimize reallocs
  1769. SourceContextInfo * sourceContextInfo = utf8SourceInfo->GetSrcInfo()->sourceContextInfo;
  1770. utf8SourceInfo->EnsureInitialized((grfscr & fscrDynamicCode) ? 4 : (sourceContextInfo->nextLocalFunctionId - pnodeProg->functionId));
  1771. sourceContextInfo->EnsureInitialized();
  1772. ArenaAllocator localAlloc(_u("ByteCode"), threadContext->GetPageAllocator(), Js::Throw::OutOfMemory);
  1773. // Make sure FuncInfo's get finalized when byte code gen is done.
  1774. struct AutoFinalizeFuncInfos {
  1775. AutoFinalizeFuncInfos(ByteCodeGenerator * byteCodeGenerator) : byteCodeGenerator(byteCodeGenerator) {}
  1776. ~AutoFinalizeFuncInfos() {
  1777. if (byteCodeGenerator)
  1778. {
  1779. byteCodeGenerator->FinalizeFuncInfos();
  1780. }
  1781. }
  1782. ByteCodeGenerator * byteCodeGenerator;
  1783. } autoFinalizeFuncInfos(byteCodeGenerator);
  1784. byteCodeGenerator->parser = parser;
  1785. byteCodeGenerator->SetCurrentSourceIndex(sourceIndex);
  1786. byteCodeGenerator->Begin(&localAlloc, grfscr, *ppRootFunc);
  1787. byteCodeGenerator->functionRef = functionRef;
  1788. Visit(pnodeProg, byteCodeGenerator, Bind, AssignRegisters);
  1789. byteCodeGenerator->forceNoNative = forceNoNative;
  1790. byteCodeGenerator->EmitProgram(pnodeProg);
  1791. if (byteCodeGenerator->flags & fscrEval)
  1792. {
  1793. // The eval caller's frame always escapes if eval refers to the caller's arguments.
  1794. byteCodeGenerator->GetRootFunc()->GetFunctionBody()->SetFuncEscapes(
  1795. byteCodeGenerator->funcEscapes || pnodeProg->m_UsesArgumentsAtGlobal);
  1796. }
  1797. #ifdef IR_VIEWER
  1798. if (grfscr & fscrIrDumpEnable)
  1799. {
  1800. byteCodeGenerator->GetRootFunc()->GetFunctionBody()->SetIRDumpEnabled(true);
  1801. }
  1802. #endif /* IR_VIEWER */
  1803. byteCodeGenerator->CheckDeferParseHasMaybeEscapedNestedFunc();
  1804. #ifdef PROFILE_EXEC
  1805. scriptContext->ProfileEnd(Js::ByteCodePhase);
  1806. #endif
  1807. JS_ETW_INTERNAL(EventWriteJSCRIPT_BYTECODEGEN_STOP(scriptContext, 0));
  1808. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_PREJIT)
  1809. if (!byteCodeGenerator->forceNoNative && !scriptContext->GetConfig()->IsNoNative()
  1810. && Js::Configuration::Global.flags.Prejit
  1811. && (grfscr & fscrNoPreJit) == 0)
  1812. {
  1813. GenerateAllFunctions(scriptContext->GetNativeCodeGenerator(), byteCodeGenerator->GetRootFunc()->GetFunctionBody());
  1814. }
  1815. #endif
  1816. if (ppRootFunc)
  1817. {
  1818. *ppRootFunc = byteCodeGenerator->GetRootFunc();
  1819. }
  1820. #ifdef PERF_COUNTERS
  1821. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: deferparse - # of func: %d # deferparsed: %d\n"),
  1822. PerfCounter::CodeCounterSet::GetTotalFunctionCounter().GetValue(), PerfCounter::CodeCounterSet::GetDeferredFunctionCounter().GetValue());
  1823. #endif
  1824. }
  1825. void ByteCodeGenerator::CheckDeferParseHasMaybeEscapedNestedFunc()
  1826. {
  1827. if (!this->parentScopeInfo)
  1828. {
  1829. return;
  1830. }
  1831. Assert(this->funcInfoStack && !this->funcInfoStack->Empty());
  1832. // Box the stack nested function if we detected new may be escaped use function.
  1833. SList<FuncInfo *>::Iterator i(this->funcInfoStack);
  1834. bool succeed = i.Next();
  1835. Assert(succeed);
  1836. Assert(i.Data()->IsGlobalFunction()); // We always leave a glo on type when defer parsing.
  1837. Assert(!i.Data()->IsRestored());
  1838. succeed = i.Next();
  1839. FuncInfo * top = i.Data();
  1840. Assert(!top->IsGlobalFunction());
  1841. Assert(top->IsRestored());
  1842. Js::FunctionBody * rootFuncBody = this->GetRootFunc()->GetFunctionBody();
  1843. if (!rootFuncBody->DoStackNestedFunc())
  1844. {
  1845. top->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("DeferredChild")));
  1846. }
  1847. else
  1848. {
  1849. // We have to wait until it is parsed before we populate the stack nested func parent.
  1850. Scope * enclosingScope = top->GetParamScope() ? top->GetParamScope() :
  1851. top->GetBodyScope() ? top->GetBodyScope() :
  1852. top->GetFuncExprScope();
  1853. FuncInfo * parentFunc = enclosingScope->GetEnclosingFunc();
  1854. if (!parentFunc->IsGlobalFunction())
  1855. {
  1856. Assert(parentFunc->byteCodeFunction != rootFuncBody);
  1857. Js::ParseableFunctionInfo * parentFunctionInfo = parentFunc->byteCodeFunction;
  1858. if (parentFunctionInfo->DoStackNestedFunc())
  1859. {
  1860. rootFuncBody->SetStackNestedFuncParent(parentFunctionInfo->GetFunctionInfo());
  1861. }
  1862. }
  1863. }
  1864. do
  1865. {
  1866. FuncInfo * funcInfo = i.Data();
  1867. Assert(funcInfo->IsRestored());
  1868. Js::ParseableFunctionInfo * parseableFunctionInfo = funcInfo->byteCodeFunction;
  1869. if (parseableFunctionInfo == nullptr)
  1870. {
  1871. Assert(funcInfo->GetBodyScope() && funcInfo->GetBodyScope()->GetScopeType() == ScopeType_Global);
  1872. return;
  1873. }
  1874. bool didStackNestedFunc = parseableFunctionInfo->DoStackNestedFunc();
  1875. if (!didStackNestedFunc)
  1876. {
  1877. return;
  1878. }
  1879. if (!parseableFunctionInfo->IsFunctionBody())
  1880. {
  1881. continue;
  1882. }
  1883. Js::FunctionBody * functionBody = funcInfo->GetParsedFunctionBody();
  1884. if (funcInfo->HasMaybeEscapedNestedFunc())
  1885. {
  1886. // This should box the rest of the parent functions.
  1887. if (PHASE_TESTTRACE(Js::StackFuncPhase, this->pCurrentFunction))
  1888. {
  1889. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1890. Output::Print(_u("DeferParse: box and disable stack function: %s (function %s)\n"),
  1891. functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer));
  1892. Output::Flush();
  1893. }
  1894. // During the box workflow we reset all the parents of all nested functions and up. If a fault occurs when the stack function
  1895. // is created this will cause further issues when trying to use the function object again. So failing faster seems to make more sense.
  1896. try
  1897. {
  1898. Js::StackScriptFunction::Box(functionBody, functionRef);
  1899. }
  1900. catch (Js::OutOfMemoryException)
  1901. {
  1902. FailedToBox_OOM_unrecoverable_error((ULONG_PTR)functionBody);
  1903. }
  1904. return;
  1905. }
  1906. }
  1907. while (i.Next());
  1908. }
  1909. void ByteCodeGenerator::Begin(
  1910. __in ArenaAllocator *alloc,
  1911. __in uint32 grfscr,
  1912. __in Js::ParseableFunctionInfo* pRootFunc)
  1913. {
  1914. this->alloc = alloc;
  1915. this->flags = grfscr;
  1916. this->pRootFunc = pRootFunc;
  1917. this->pCurrentFunction = pRootFunc ? pRootFunc->GetFunctionBody() : nullptr;
  1918. if (this->pCurrentFunction && this->pCurrentFunction->GetIsGlobalFunc() && IsInNonDebugMode())
  1919. {
  1920. // This is the deferred parse case (not due to debug mode), in which case the global function will not be marked to compiled again.
  1921. this->pCurrentFunction = nullptr;
  1922. }
  1923. this->globalScope = nullptr;
  1924. this->currentScope = nullptr;
  1925. this->currentBlock = nullptr;
  1926. this->isBinding = true;
  1927. this->inPrologue = false;
  1928. this->funcEscapes = false;
  1929. this->maxAstSize = 0;
  1930. this->loopDepth = 0;
  1931. this->envDepth = 0;
  1932. this->trackEnvDepth = false;
  1933. this->funcInfosToFinalize = nullptr;
  1934. this->funcInfoStack = Anew(alloc, SList<FuncInfo*>, alloc);
  1935. }
  1936. HRESULT GenerateByteCode(__in ParseNodeProg *pnode, __in uint32 grfscr, __in Js::ScriptContext* scriptContext, __inout Js::ParseableFunctionInfo ** ppRootFunc,
  1937. __in uint sourceIndex, __in bool forceNoNative, __in Parser* parser, __in CompileScriptException *pse, Js::ScopeInfo* parentScopeInfo,
  1938. Js::ScriptFunction ** functionRef)
  1939. {
  1940. HRESULT hr = S_OK;
  1941. ByteCodeGenerator byteCodeGenerator(scriptContext, parentScopeInfo);
  1942. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT_NESTED
  1943. {
  1944. // Main code.
  1945. ByteCodeGenerator::Generate(pnode, grfscr, &byteCodeGenerator, ppRootFunc, sourceIndex, forceNoNative, parser, functionRef);
  1946. }
  1947. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  1948. if (FAILED(hr))
  1949. {
  1950. hr = pse->ProcessError(nullptr, hr, nullptr);
  1951. }
  1952. return hr;
  1953. }
  1954. void BindInstAndMember(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  1955. {
  1956. Assert(pnode->nop == knopDot);
  1957. BindReference(pnode, byteCodeGenerator);
  1958. ParseNodeName *right = pnode->AsParseNodeBin()->pnode2->AsParseNodeName();
  1959. byteCodeGenerator->AssignPropertyId(right->pid);
  1960. right->sym = nullptr;
  1961. right->ClearSymRef();
  1962. right->grfpn |= fpnMemberReference;
  1963. }
  1964. void BindReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  1965. {
  1966. // Do special reference-op binding so that we can, for instance, handle call from inside "with"
  1967. // where the "this" instance must be found dynamically.
  1968. bool isCallNode = false;
  1969. bool funcEscapes = false;
  1970. switch (pnode->nop)
  1971. {
  1972. case knopCall:
  1973. isCallNode = true;
  1974. pnode = pnode->AsParseNodeCall()->pnodeTarget;
  1975. break;
  1976. case knopDelete:
  1977. case knopTypeof:
  1978. pnode = pnode->AsParseNodeUni()->pnode1;
  1979. break;
  1980. case knopDot:
  1981. case knopIndex:
  1982. funcEscapes = true;
  1983. // fall through
  1984. case knopAsg:
  1985. pnode = pnode->AsParseNodeBin()->pnode1;
  1986. break;
  1987. default:
  1988. AssertMsg(0, "Unexpected opcode in BindReference");
  1989. return;
  1990. }
  1991. if (pnode->nop == knopName)
  1992. {
  1993. ParseNodeName * pnodeName = pnode->AsParseNodeName();
  1994. pnodeName->sym = byteCodeGenerator->FindSymbol(pnodeName->GetSymRef(), pnodeName->pid, isCallNode);
  1995. if (funcEscapes &&
  1996. pnodeName->sym &&
  1997. pnodeName->sym->GetSymbolType() == STFunction &&
  1998. (!pnodeName->sym->GetIsGlobal() || (byteCodeGenerator->GetFlags() & fscrEval)))
  1999. {
  2000. // Dot, index, and scope ops can cause a local function on the LHS to escape.
  2001. // Make sure scopes are not cached in this case.
  2002. byteCodeGenerator->FuncEscapes(pnodeName->sym->GetScope());
  2003. }
  2004. }
  2005. }
  2006. void MarkFormal(ByteCodeGenerator *byteCodeGenerator, Symbol *formal, bool assignLocation, bool needDeclaration)
  2007. {
  2008. if (assignLocation)
  2009. {
  2010. formal->SetLocation(byteCodeGenerator->NextVarRegister());
  2011. }
  2012. if (needDeclaration)
  2013. {
  2014. formal->SetNeedDeclaration(true);
  2015. }
  2016. }
  2017. void AddArgsToScope(ParseNodeFnc * pnodeFnc, ByteCodeGenerator *byteCodeGenerator, bool assignLocation)
  2018. {
  2019. Assert(byteCodeGenerator->TopFuncInfo()->varRegsCount == 0);
  2020. Js::ArgSlot pos = 1;
  2021. bool isNonSimpleParameterList = pnodeFnc->HasNonSimpleParameterList();
  2022. auto addArgToScope = [&](ParseNode *arg)
  2023. {
  2024. if (arg->IsVarLetOrConst())
  2025. {
  2026. ParseNodeVar * pnodeVarArg = arg->AsParseNodeVar();
  2027. Symbol *formal = byteCodeGenerator->AddSymbolToScope(byteCodeGenerator->TopFuncInfo()->GetParamScope(),
  2028. reinterpret_cast<const char16*>(pnodeVarArg->pid->Psz()),
  2029. pnodeVarArg->pid->Cch(),
  2030. pnodeVarArg,
  2031. STFormal);
  2032. #if DBG_DUMP
  2033. if (byteCodeGenerator->Trace())
  2034. {
  2035. Output::Print(_u("current context has declared arg %s of type %s at position %d\n"), arg->AsParseNodeVar()->pid->Psz(), formal->GetSymbolTypeName(), pos);
  2036. }
  2037. #endif
  2038. if (isNonSimpleParameterList)
  2039. {
  2040. formal->SetIsNonSimpleParameter(true);
  2041. }
  2042. pnodeVarArg->sym = formal;
  2043. MarkFormal(byteCodeGenerator, formal, assignLocation || isNonSimpleParameterList, isNonSimpleParameterList);
  2044. }
  2045. else if (arg->nop == knopParamPattern)
  2046. {
  2047. arg->AsParseNodeParamPattern()->location = byteCodeGenerator->NextVarRegister();
  2048. }
  2049. else
  2050. {
  2051. Assert(false);
  2052. }
  2053. ArgSlotMath::Inc(pos);
  2054. };
  2055. // We process rest separately because the number of in args needs to exclude rest.
  2056. MapFormalsWithoutRest(pnodeFnc, addArgToScope);
  2057. byteCodeGenerator->SetNumberOfInArgs(pos);
  2058. if (pnodeFnc->pnodeRest != nullptr)
  2059. {
  2060. // The rest parameter will always be in a register, regardless of whether it is in a scope slot.
  2061. // We save the assignLocation value for the assert condition below.
  2062. bool assignLocationSave = assignLocation;
  2063. assignLocation = true;
  2064. addArgToScope(pnodeFnc->pnodeRest);
  2065. assignLocation = assignLocationSave;
  2066. }
  2067. MapFormalsFromPattern(pnodeFnc, addArgToScope);
  2068. Assert(!assignLocation || byteCodeGenerator->TopFuncInfo()->varRegsCount + 1 == pos);
  2069. }
  2070. void AddVarsToScope(ParseNode *vars, ByteCodeGenerator *byteCodeGenerator)
  2071. {
  2072. while (vars != nullptr)
  2073. {
  2074. Symbol *sym = byteCodeGenerator->AddSymbolToFunctionScope(reinterpret_cast<const char16*>(vars->AsParseNodeVar()->pid->Psz()), vars->AsParseNodeVar()->pid->Cch(), vars, STVariable);
  2075. #if DBG_DUMP
  2076. if (sym->GetSymbolType() == STVariable && byteCodeGenerator->Trace())
  2077. {
  2078. Output::Print(_u("current context has declared var %s of type %s\n"),
  2079. vars->AsParseNodeVar()->pid->Psz(), sym->GetSymbolTypeName());
  2080. }
  2081. #endif
  2082. if (sym->IsArguments() || sym->IsSpecialSymbol() || vars->AsParseNodeVar()->pnodeInit == nullptr)
  2083. {
  2084. // LHS's of var decls are usually bound to symbols later, during the Visit/Bind pass,
  2085. // so that things like catch scopes can be taken into account.
  2086. // The exception is "arguments", which always binds to the local scope.
  2087. // We can also bind to the function scope symbol now if there's no init value
  2088. // to assign.
  2089. vars->AsParseNodeVar()->sym = sym;
  2090. if (sym->IsArguments())
  2091. {
  2092. FuncInfo* funcInfo = byteCodeGenerator->TopFuncInfo();
  2093. funcInfo->SetArgumentsSymbol(sym);
  2094. }
  2095. else if (sym->IsSpecialSymbol())
  2096. {
  2097. FuncInfo* funcInfo = byteCodeGenerator->TopFuncInfo();
  2098. if (sym->IsThis())
  2099. {
  2100. funcInfo->SetThisSymbol(sym);
  2101. }
  2102. else if (sym->IsNewTarget())
  2103. {
  2104. funcInfo->SetNewTargetSymbol(sym);
  2105. }
  2106. else if (sym->IsImportMeta())
  2107. {
  2108. funcInfo->SetImportMetaSymbol(sym);
  2109. }
  2110. else if (sym->IsSuper())
  2111. {
  2112. funcInfo->SetSuperSymbol(sym);
  2113. }
  2114. else if (sym->IsSuperConstructor())
  2115. {
  2116. funcInfo->SetSuperConstructorSymbol(sym);
  2117. }
  2118. }
  2119. }
  2120. else
  2121. {
  2122. vars->AsParseNodeVar()->sym = nullptr;
  2123. }
  2124. vars = vars->AsParseNodeVar()->pnodeNext;
  2125. }
  2126. }
  2127. template <class Fn>
  2128. void VisitFncDecls(ParseNode *fns, Fn action)
  2129. {
  2130. while (fns != nullptr)
  2131. {
  2132. switch (fns->nop)
  2133. {
  2134. case knopFncDecl:
  2135. action(fns);
  2136. fns = fns->AsParseNodeFnc()->pnodeNext;
  2137. break;
  2138. case knopBlock:
  2139. fns = fns->AsParseNodeBlock()->pnodeNext;
  2140. break;
  2141. case knopCatch:
  2142. fns = fns->AsParseNodeCatch()->pnodeNext;
  2143. break;
  2144. case knopWith:
  2145. fns = fns->AsParseNodeWith()->pnodeNext;
  2146. break;
  2147. default:
  2148. AssertMsg(false, "Unexpected opcode in tree of scopes");
  2149. return;
  2150. }
  2151. }
  2152. }
  2153. FuncInfo* PreVisitFunction(ParseNodeFnc* pnodeFnc, ByteCodeGenerator* byteCodeGenerator, Js::ParseableFunctionInfo *reuseNestedFunc)
  2154. {
  2155. // Do binding of function name(s), initialize function scope, propagate function-wide properties from
  2156. // the parent (if any).
  2157. FuncInfo* parentFunc = byteCodeGenerator->TopFuncInfo();
  2158. // fIsRoot indicates that this is the root function to be returned to a ParseProcedureText/AddScriptLet/etc. call.
  2159. // In such cases, the global function is just a wrapper around the root function's declaration.
  2160. // We used to assert that this was the only top-level function body, but it's possible to trick
  2161. // "new Function" into compiling more than one function (see WOOB 1121759).
  2162. bool fIsRoot = (!(byteCodeGenerator->GetFlags() & fscrGlobalCode) &&
  2163. parentFunc->IsGlobalFunction() &&
  2164. parentFunc->root->GetTopLevelScope() == pnodeFnc);
  2165. const char16 *funcName = Js::Constants::AnonymousFunction;
  2166. uint funcNameLength = Js::Constants::AnonymousFunctionLength;
  2167. uint functionNameOffset = 0;
  2168. bool funcExprWithName = false;
  2169. if (pnodeFnc->hint != nullptr)
  2170. {
  2171. funcName = reinterpret_cast<const char16*>(pnodeFnc->hint);
  2172. funcNameLength = pnodeFnc->hintLength;
  2173. functionNameOffset = pnodeFnc->hintOffset;
  2174. Assert(funcNameLength != 0 || funcNameLength == (int)wcslen(funcName));
  2175. }
  2176. if (pnodeFnc->IsDeclaration() || pnodeFnc->IsMethod())
  2177. {
  2178. // Class members have the fully qualified name stored in 'hint', no need to replace it.
  2179. if (pnodeFnc->pid && !pnodeFnc->IsClassMember())
  2180. {
  2181. funcName = reinterpret_cast<const char16*>(pnodeFnc->pid->Psz());
  2182. funcNameLength = pnodeFnc->pid->Cch();
  2183. functionNameOffset = 0;
  2184. }
  2185. }
  2186. else if (pnodeFnc->pnodeName != nullptr)
  2187. {
  2188. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  2189. funcName = reinterpret_cast<const char16*>(pnodeFnc->pnodeName->pid->Psz());
  2190. funcNameLength = pnodeFnc->pnodeName->pid->Cch();
  2191. functionNameOffset = 0;
  2192. //
  2193. // create the new scope for Function expression only in ES5 mode
  2194. //
  2195. funcExprWithName = true;
  2196. }
  2197. if (byteCodeGenerator->Trace())
  2198. {
  2199. Output::Print(_u("function start %s\n"), funcName);
  2200. }
  2201. Assert(pnodeFnc->funcInfo == nullptr);
  2202. FuncInfo* funcInfo = pnodeFnc->funcInfo = byteCodeGenerator->StartBindFunction(funcName, funcNameLength, functionNameOffset, &funcExprWithName, pnodeFnc, reuseNestedFunc);
  2203. funcInfo->byteCodeFunction->SetIsNamedFunctionExpression(funcExprWithName);
  2204. funcInfo->byteCodeFunction->SetIsNameIdentifierRef(pnodeFnc->isNameIdentifierRef);
  2205. if (fIsRoot)
  2206. {
  2207. byteCodeGenerator->SetRootFuncInfo(funcInfo);
  2208. }
  2209. if (pnodeFnc->pnodeBody == nullptr)
  2210. {
  2211. // This is a deferred byte code gen, so we're done.
  2212. // Process the formal arguments, even if there's no AST for the body, to support Function.length.
  2213. Js::ArgSlot pos = 1;
  2214. // We skip the rest parameter here because it is not counted towards the in arg count.
  2215. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnode) { ArgSlotMath::Inc(pos); });
  2216. byteCodeGenerator->SetNumberOfInArgs(pos);
  2217. return funcInfo;
  2218. }
  2219. if (pnodeFnc->HasReferenceableBuiltInArguments())
  2220. {
  2221. // The parser identified that there is a way to reference the built-in 'arguments' variable from this function. So, we
  2222. // need to determine whether we need to create the variable or not. We need to create the variable iff:
  2223. if (pnodeFnc->CallsEval())
  2224. {
  2225. // 1. eval is called.
  2226. // 2. when the debugging is enabled, since user can seek arguments during breakpoint.
  2227. funcInfo->SetHasArguments(true);
  2228. funcInfo->SetHasHeapArguments(true);
  2229. if (funcInfo->inArgsCount == 0)
  2230. {
  2231. // If no formals to function, no need to create the propertyid array
  2232. byteCodeGenerator->AssignNullConstRegister();
  2233. }
  2234. }
  2235. else if (pnodeFnc->UsesArguments())
  2236. {
  2237. // 3. the function directly references an 'arguments' identifier
  2238. funcInfo->SetHasArguments(true);
  2239. funcInfo->GetParsedFunctionBody()->SetUsesArgumentsObject(true);
  2240. if (pnodeFnc->HasHeapArguments())
  2241. {
  2242. bool doStackArgsOpt = (!pnodeFnc->HasAnyWriteToFormals() || funcInfo->GetIsStrictMode());
  2243. #ifdef PERF_HINT
  2244. if (PHASE_TRACE1(Js::PerfHintPhase) && !doStackArgsOpt)
  2245. {
  2246. WritePerfHint(PerfHints::HeapArgumentsDueToWriteToFormals, funcInfo->GetParsedFunctionBody(), 0);
  2247. }
  2248. #endif
  2249. //With statements - need scope object to be present.
  2250. if ((doStackArgsOpt && pnodeFnc->funcInfo->GetParamScope()->Count() > 1) && ((byteCodeGenerator->GetFlags() & fscrEval) ||
  2251. pnodeFnc->HasWithStmt() || byteCodeGenerator->IsInDebugMode() || PHASE_OFF1(Js::StackArgFormalsOptPhase) || PHASE_OFF1(Js::StackArgOptPhase)))
  2252. {
  2253. doStackArgsOpt = false;
  2254. #ifdef PERF_HINT
  2255. if (PHASE_TRACE1(Js::PerfHintPhase))
  2256. {
  2257. if (pnodeFnc->HasWithStmt())
  2258. {
  2259. WritePerfHint(PerfHints::HasWithBlock, funcInfo->GetParsedFunctionBody(), 0);
  2260. }
  2261. if(byteCodeGenerator->GetFlags() & fscrEval)
  2262. {
  2263. WritePerfHint(PerfHints::SrcIsEval, funcInfo->GetParsedFunctionBody(), 0);
  2264. }
  2265. }
  2266. #endif
  2267. }
  2268. funcInfo->SetHasHeapArguments(true, !pnodeFnc->IsCoroutine() && doStackArgsOpt /*= Optimize arguments in backend*/);
  2269. if (funcInfo->inArgsCount == 0)
  2270. {
  2271. // If no formals to function, no need to create the propertyid array
  2272. byteCodeGenerator->AssignNullConstRegister();
  2273. }
  2274. }
  2275. }
  2276. }
  2277. Js::FunctionBody* parentFunctionBody = parentFunc->GetParsedFunctionBody();
  2278. if (funcInfo->GetHasArguments() ||
  2279. parentFunctionBody->GetHasOrParentHasArguments())
  2280. {
  2281. // The JIT uses this info, for instance, to narrow kills of array operations
  2282. funcInfo->GetParsedFunctionBody()->SetHasOrParentHasArguments(true);
  2283. }
  2284. PreVisitBlock(pnodeFnc->pnodeScopes, byteCodeGenerator);
  2285. // If we have arguments, we are going to need locations if the function is in strict mode or we have a non-simple parameter list. This is because we will not create a scope object.
  2286. bool assignLocationForFormals = !byteCodeGenerator->NeedScopeObjectForArguments(funcInfo, funcInfo->root);
  2287. AddArgsToScope(pnodeFnc, byteCodeGenerator, assignLocationForFormals);
  2288. return funcInfo;
  2289. }
  2290. void AssignFuncSymRegister(ParseNodeFnc * pnodeFnc, ByteCodeGenerator * byteCodeGenerator, FuncInfo * callee)
  2291. {
  2292. // register to hold the allocated function (in enclosing sequence of global statements)
  2293. // TODO: Make the parser identify uses of function decls as RHS's of expressions.
  2294. // Currently they're all marked as used, so they all get permanent (non-temp) registers.
  2295. if (pnodeFnc->pnodeName == nullptr)
  2296. {
  2297. return;
  2298. }
  2299. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  2300. Symbol *sym = pnodeFnc->pnodeName->sym;
  2301. if (sym)
  2302. {
  2303. if (!sym->GetIsGlobal() && !(callee->funcExprScope && callee->funcExprScope->GetIsObject()))
  2304. {
  2305. // If the func decl is used, we have to give the expression a register to protect against:
  2306. // x.x = function f() {...};
  2307. // x.y = function f() {...};
  2308. // If we let the value reside in the local slot for f, then both assignments will get the
  2309. // second definition.
  2310. if (!pnodeFnc->IsDeclaration())
  2311. {
  2312. // A named function expression's name belongs to the enclosing scope.
  2313. // In ES5 mode, it is visible only inside the inner function.
  2314. // Allocate a register for the 'name' symbol from an appropriate register namespace.
  2315. if (callee->GetFuncExprNameReference())
  2316. {
  2317. // This is a function expression with a name, but probably doesn't have a use within
  2318. // the function. If that is the case then allocate a register for LdFuncExpr inside the function
  2319. // we just finished post-visiting.
  2320. if (sym->GetLocation() == Js::Constants::NoRegister)
  2321. {
  2322. sym->SetLocation(callee->NextVarRegister());
  2323. }
  2324. }
  2325. }
  2326. else
  2327. {
  2328. // Function declaration
  2329. byteCodeGenerator->AssignRegister(sym);
  2330. pnodeFnc->location = sym->GetLocation();
  2331. Assert(byteCodeGenerator->GetCurrentScope()->GetFunc() == sym->GetScope()->GetFunc());
  2332. if (byteCodeGenerator->GetCurrentScope()->GetFunc() != sym->GetScope()->GetFunc())
  2333. {
  2334. Assert(GetParentFuncInfo(byteCodeGenerator->GetCurrentScope()->GetFunc()) == sym->GetScope()->GetFunc());
  2335. sym->GetScope()->SetMustInstantiate(true);
  2336. byteCodeGenerator->ProcessCapturedSym(sym);
  2337. sym->GetScope()->GetFunc()->SetHasLocalInClosure(true);
  2338. }
  2339. Symbol * functionScopeVarSym = sym->GetFuncScopeVarSym();
  2340. if (functionScopeVarSym &&
  2341. !functionScopeVarSym->GetIsGlobal() &&
  2342. !functionScopeVarSym->IsInSlot(byteCodeGenerator, sym->GetScope()->GetFunc()))
  2343. {
  2344. byteCodeGenerator->AssignRegister(functionScopeVarSym);
  2345. }
  2346. }
  2347. }
  2348. else if (!pnodeFnc->IsDeclaration())
  2349. {
  2350. if (sym->GetLocation() == Js::Constants::NoRegister)
  2351. {
  2352. // Here, we are assigning a register for the LdFuncExpr instruction inside the function we just finished
  2353. // post-visiting. The symbol is given a register from the register pool for the function we just finished
  2354. // post-visiting, rather than from the parent function's register pool.
  2355. sym->SetLocation(callee->NextVarRegister());
  2356. }
  2357. }
  2358. }
  2359. }
  2360. bool FuncAllowsDirectSuper(FuncInfo *funcInfo, ByteCodeGenerator *byteCodeGenerator)
  2361. {
  2362. if (!funcInfo->IsBaseClassConstructor() && funcInfo->IsClassConstructor())
  2363. {
  2364. return true;
  2365. }
  2366. if (funcInfo->IsGlobalFunction() && ((byteCodeGenerator->GetFlags() & fscrEval) != 0))
  2367. {
  2368. Js::JavascriptFunction *caller = nullptr;
  2369. if (Js::JavascriptStackWalker::GetCaller(&caller, byteCodeGenerator->GetScriptContext()) && caller->GetFunctionInfo()->GetAllowDirectSuper())
  2370. {
  2371. return true;
  2372. }
  2373. }
  2374. return false;
  2375. }
  2376. FuncInfo* PostVisitFunction(ParseNodeFnc* pnodeFnc, ByteCodeGenerator* byteCodeGenerator)
  2377. {
  2378. // Assign function-wide registers such as local frame object, closure environment, etc., based on
  2379. // observed attributes. Propagate attributes to the parent function (if any).
  2380. FuncInfo *top = byteCodeGenerator->TopFuncInfo();
  2381. Symbol *sym = pnodeFnc->GetFuncSymbol();
  2382. bool funcExprWithName = !top->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  2383. if (top->IsLambda())
  2384. {
  2385. FuncInfo *enclosingNonLambda = byteCodeGenerator->FindEnclosingNonLambda();
  2386. if (enclosingNonLambda->IsGlobalFunction())
  2387. {
  2388. top->byteCodeFunction->SetEnclosedByGlobalFunc();
  2389. }
  2390. if (FuncAllowsDirectSuper(enclosingNonLambda, byteCodeGenerator))
  2391. {
  2392. top->byteCodeFunction->GetFunctionInfo()->SetAllowDirectSuper();
  2393. }
  2394. }
  2395. else if (FuncAllowsDirectSuper(top, byteCodeGenerator))
  2396. {
  2397. top->byteCodeFunction->GetFunctionInfo()->SetAllowDirectSuper();
  2398. }
  2399. // If this is a named function expression and has deferred child, mark has non-local reference.
  2400. if (funcExprWithName)
  2401. {
  2402. // If we are reparsing this function due to being in debug mode - we should restore the state of this from the earlier parse
  2403. if (top->byteCodeFunction->IsFunctionParsed() && top->GetParsedFunctionBody()->HasFuncExprNameReference())
  2404. {
  2405. top->SetFuncExprNameReference(true);
  2406. }
  2407. if (sym->GetHasNonLocalReference())
  2408. {
  2409. // Before doing this, though, make sure there's no local symbol that hides the function name
  2410. // from the nested functions. If a lookup starting at the current local scope finds some symbol
  2411. // other than the func expr, then it's hidden. (See Win8 393618.)
  2412. byteCodeGenerator->ProcessCapturedSym(sym);
  2413. top->SetFuncExprNameReference(true);
  2414. if (pnodeFnc->pnodeBody)
  2415. {
  2416. top->GetParsedFunctionBody()->SetFuncExprNameReference(true);
  2417. }
  2418. byteCodeGenerator->ProcessScopeWithCapturedSym(sym->GetScope());
  2419. }
  2420. }
  2421. if (pnodeFnc->nop != knopProg
  2422. && !top->bodyScope->GetIsObject()
  2423. && byteCodeGenerator->NeedObjectAsFunctionScope(top, pnodeFnc))
  2424. {
  2425. // Even if it wasn't determined during visiting this function that we need a scope object, we still have a few conditions that may require one.
  2426. top->bodyScope->SetIsObject();
  2427. if (!top->IsBodyAndParamScopeMerged())
  2428. {
  2429. // If we have the function inside an eval then access to outer variables should go through scope object.
  2430. // So we set the body scope as object and we need to set the param scope also as object in case of split scope.
  2431. top->paramScope->SetIsObject();
  2432. }
  2433. }
  2434. if (pnodeFnc->nop == knopProg
  2435. && top->byteCodeFunction->GetIsStrictMode()
  2436. && (byteCodeGenerator->GetFlags() & fscrEval))
  2437. {
  2438. // At global scope inside a strict mode eval, vars will not leak out and require a scope object (along with its parent.)
  2439. top->bodyScope->SetIsObject();
  2440. }
  2441. if (pnodeFnc->pnodeBody)
  2442. {
  2443. if (!top->IsGlobalFunction())
  2444. {
  2445. auto fnProcess =
  2446. [byteCodeGenerator, top](Symbol *const sym)
  2447. {
  2448. if (sym->GetHasNonLocalReference() && !sym->GetIsModuleExportStorage())
  2449. {
  2450. byteCodeGenerator->ProcessCapturedSym(sym);
  2451. }
  2452. };
  2453. Scope *bodyScope = top->bodyScope;
  2454. Scope *paramScope = top->paramScope;
  2455. if (paramScope != nullptr)
  2456. {
  2457. if (paramScope->GetHasOwnLocalInClosure())
  2458. {
  2459. paramScope->ForEachSymbol(fnProcess);
  2460. top->SetHasLocalInClosure(true);
  2461. }
  2462. }
  2463. if (bodyScope->GetHasOwnLocalInClosure())
  2464. {
  2465. bodyScope->ForEachSymbol(fnProcess);
  2466. top->SetHasLocalInClosure(true);
  2467. }
  2468. PostVisitBlock(pnodeFnc->pnodeBodyScope, byteCodeGenerator);
  2469. PostVisitBlock(pnodeFnc->pnodeScopes, byteCodeGenerator);
  2470. }
  2471. // This function refers to the closure environment if:
  2472. // 1. it has a child function (we'll pass the environment to the constructor when the child is created -
  2473. // even if it's not needed, it's as cheap as loading "null" from the library);
  2474. // 2. it calls eval (and will use the environment to construct the scope chain to pass to eval);
  2475. // 3. it refers to a local defined in a parent function;
  2476. // 4. some parent calls eval;
  2477. // 5. we're in an event handler;
  2478. // 6. the function was declared inside a "with";
  2479. // 7. we're in an eval expression.
  2480. if (pnodeFnc->nestedCount != 0 ||
  2481. top->GetCallsEval() ||
  2482. top->GetHasClosureReference() ||
  2483. byteCodeGenerator->InDynamicScope() ||
  2484. (byteCodeGenerator->GetFlags() & (fscrImplicitThis | fscrEval)))
  2485. {
  2486. byteCodeGenerator->SetNeedEnvRegister();
  2487. }
  2488. // This function needs to construct a local frame on the heap if it is not the global function (even in eval) and:
  2489. // 1. it calls eval, which may refer to or declare any locals in this frame;
  2490. // 2. a child calls eval (which may refer to locals through a closure);
  2491. // 3. it uses non-strict mode "arguments", so the arguments have to be put in a closure;
  2492. // 4. it defines a local that is used by a child function (read from a closure).
  2493. // 5. it is a main function that's wrapped in a function expression scope but has locals used through
  2494. // a closure (used in forReference function call cases in a with for example).
  2495. if (!top->IsGlobalFunction())
  2496. {
  2497. if (top->GetCallsEval() ||
  2498. top->GetChildCallsEval() ||
  2499. (top->GetHasArguments() && byteCodeGenerator->NeedScopeObjectForArguments(top, pnodeFnc)) ||
  2500. top->GetHasLocalInClosure() ||
  2501. (top->funcExprScope && top->funcExprScope->GetMustInstantiate()) ||
  2502. // When we have split scope normally either eval will be present or the GetHasLocalInClosure will be true as one of the formal is
  2503. // captured. But when we force split scope or split scope happens due to some other reasons we have to make sure we allocate frame
  2504. // slot register here.
  2505. (!top->IsBodyAndParamScopeMerged()))
  2506. {
  2507. if (!top->GetCallsEval() && top->GetHasLocalInClosure())
  2508. {
  2509. byteCodeGenerator->AssignFrameSlotsRegister();
  2510. }
  2511. if (!top->IsBodyAndParamScopeMerged())
  2512. {
  2513. byteCodeGenerator->AssignParamSlotsRegister();
  2514. }
  2515. if (byteCodeGenerator->NeedObjectAsFunctionScope(top, top->root)
  2516. || top->bodyScope->GetIsObject()
  2517. || top->paramScope->GetIsObject())
  2518. {
  2519. byteCodeGenerator->AssignFrameObjRegister();
  2520. }
  2521. // The function also needs to construct a frame display if:
  2522. // 1. it calls eval;
  2523. // 2. it has a child function.
  2524. // 3. When has arguments and in debug mode. So that frame display be there along with frame object register.
  2525. if (top->GetCallsEval() ||
  2526. pnodeFnc->nestedCount != 0
  2527. || (top->GetHasArguments()
  2528. && (pnodeFnc->pnodeParams != nullptr)
  2529. && byteCodeGenerator->IsInDebugMode()))
  2530. {
  2531. byteCodeGenerator->SetNeedEnvRegister(); // This to ensure that Env should be there when the FrameDisplay register is there.
  2532. byteCodeGenerator->AssignFrameDisplayRegister();
  2533. }
  2534. }
  2535. if (top->GetHasArguments())
  2536. {
  2537. Symbol *argSym = top->GetArgumentsSymbol();
  2538. Assert(argSym);
  2539. if (argSym)
  2540. {
  2541. Assert(top->bodyScope->GetScopeSlotCount() == 0);
  2542. Assert(top->argsPlaceHolderSlotCount == 0);
  2543. byteCodeGenerator->AssignRegister(argSym);
  2544. uint i = 0;
  2545. auto setArgScopeSlot = [&](ParseNode *pnodeArg)
  2546. {
  2547. if (pnodeArg->IsVarLetOrConst())
  2548. {
  2549. Symbol* sym = pnodeArg->AsParseNodeVar()->sym;
  2550. if (sym->GetScopeSlot() != Js::Constants::NoProperty)
  2551. {
  2552. top->argsPlaceHolderSlotCount++; // Same name args appeared before
  2553. }
  2554. sym->SetScopeSlot(i);
  2555. }
  2556. else if (pnodeArg->nop == knopParamPattern)
  2557. {
  2558. top->argsPlaceHolderSlotCount++;
  2559. }
  2560. i++;
  2561. };
  2562. // We need to include the rest as well -as it will get slot assigned.
  2563. if (byteCodeGenerator->NeedScopeObjectForArguments(top, pnodeFnc))
  2564. {
  2565. MapFormals(pnodeFnc, setArgScopeSlot);
  2566. if (argSym->NeedsSlotAlloc(byteCodeGenerator, top))
  2567. {
  2568. Assert(argSym->GetScopeSlot() == Js::Constants::NoProperty);
  2569. argSym->SetScopeSlot(i++);
  2570. }
  2571. MapFormalsFromPattern(pnodeFnc, setArgScopeSlot);
  2572. }
  2573. top->paramScope->SetScopeSlotCount(i);
  2574. Assert(top->GetHasHeapArguments());
  2575. if (byteCodeGenerator->NeedScopeObjectForArguments(top, pnodeFnc)
  2576. && !pnodeFnc->HasNonSimpleParameterList())
  2577. {
  2578. top->byteCodeFunction->SetHasImplicitArgIns(false);
  2579. }
  2580. }
  2581. }
  2582. }
  2583. else
  2584. {
  2585. Assert(top->IsGlobalFunction() || pnodeFnc->IsModule());
  2586. // eval is called in strict mode
  2587. bool newScopeForEval = (top->byteCodeFunction->GetIsStrictMode() && (byteCodeGenerator->GetFlags() & fscrEval));
  2588. if (newScopeForEval)
  2589. {
  2590. byteCodeGenerator->SetNeedEnvRegister();
  2591. byteCodeGenerator->AssignFrameObjRegister();
  2592. byteCodeGenerator->AssignFrameDisplayRegister();
  2593. }
  2594. }
  2595. if (top->GetNewTargetSymbol())
  2596. {
  2597. byteCodeGenerator->AssignRegister(top->GetNewTargetSymbol());
  2598. }
  2599. if (top->GetThisSymbol())
  2600. {
  2601. byteCodeGenerator->AssignRegister(top->GetThisSymbol());
  2602. // Indirect eval has a 'this' binding and needs to load from null
  2603. if (top->IsGlobalFunction())
  2604. {
  2605. byteCodeGenerator->AssignNullConstRegister();
  2606. }
  2607. }
  2608. if (top->GetSuperSymbol())
  2609. {
  2610. byteCodeGenerator->AssignRegister(top->GetSuperSymbol());
  2611. }
  2612. if (top->GetSuperConstructorSymbol())
  2613. {
  2614. byteCodeGenerator->AssignRegister(top->GetSuperConstructorSymbol());
  2615. }
  2616. if (top->GetImportMetaSymbol())
  2617. {
  2618. byteCodeGenerator->AssignRegister(top->GetImportMetaSymbol());
  2619. }
  2620. Assert(!funcExprWithName || sym);
  2621. if (funcExprWithName)
  2622. {
  2623. Assert(top->funcExprScope);
  2624. // If the func expr may be accessed via eval, force the func expr scope into an object.
  2625. if (top->GetCallsEval() || top->GetChildCallsEval())
  2626. {
  2627. top->funcExprScope->SetIsObject();
  2628. }
  2629. if (top->funcExprScope->GetIsObject())
  2630. {
  2631. top->funcExprScope->SetLocation(byteCodeGenerator->NextVarRegister());
  2632. }
  2633. }
  2634. }
  2635. byteCodeGenerator->EndBindFunction(funcExprWithName);
  2636. // If the "child" is the global function, we're done.
  2637. if (top->IsGlobalFunction())
  2638. {
  2639. return top;
  2640. }
  2641. if (top->IsBodyAndParamScopeMerged())
  2642. {
  2643. Scope::MergeParamAndBodyScopes(pnodeFnc);
  2644. Scope::RemoveParamScope(pnodeFnc);
  2645. }
  2646. else
  2647. {
  2648. // A param and body scope exist for the same function, they
  2649. // should both either be using scope slots or scope objects.
  2650. Assert_FailFast(top->bodyScope->GetIsObject() == top->paramScope->GetIsObject());
  2651. }
  2652. FuncInfo* const parentFunc = byteCodeGenerator->TopFuncInfo();
  2653. Js::FunctionBody * parentFunctionBody = parentFunc->byteCodeFunction->GetFunctionBody();
  2654. Assert(parentFunctionBody != nullptr);
  2655. bool setHasNonLocalReference = parentFunctionBody->HasAllNonLocalReferenced();
  2656. // This is required for class constructors as will be able to determine the actual home object register only after emitting InitClass
  2657. if (pnodeFnc->HasHomeObj() && pnodeFnc->GetHomeObjLocation() == Js::Constants::NoRegister)
  2658. {
  2659. pnodeFnc->SetHomeObjLocation(parentFunc->AssignUndefinedConstRegister());
  2660. }
  2661. // If we have any deferred child, we need to instantiate the fake global block scope if it is not empty
  2662. if (parentFunc->IsGlobalFunction())
  2663. {
  2664. if (byteCodeGenerator->IsEvalWithNoParentScopeInfo())
  2665. {
  2666. Scope * globalEvalBlockScope = parentFunc->GetGlobalEvalBlockScope();
  2667. if (globalEvalBlockScope->GetHasOwnLocalInClosure())
  2668. {
  2669. globalEvalBlockScope->SetMustInstantiate(true);
  2670. }
  2671. }
  2672. }
  2673. else
  2674. {
  2675. if (setHasNonLocalReference)
  2676. {
  2677. // All locals are already marked as non-locals-referenced. Mark the parent as well.
  2678. if (parentFunctionBody->HasSetIsObject())
  2679. {
  2680. // Updated the current function, as per the previous stored info.
  2681. parentFunc->GetBodyScope()->SetIsObject();
  2682. parentFunc->GetParamScope()->SetIsObject();
  2683. }
  2684. }
  2685. // Propagate HasMaybeEscapedNestedFunc
  2686. if (!byteCodeGenerator->CanStackNestedFunc(top, false) ||
  2687. byteCodeGenerator->NeedObjectAsFunctionScope(top, pnodeFnc))
  2688. {
  2689. parentFunc->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("Child")));
  2690. }
  2691. }
  2692. if (top->GetCallsEval() || top->GetChildCallsEval())
  2693. {
  2694. parentFunc->SetChildCallsEval(true);
  2695. ParseNodeBlock *currentBlock = byteCodeGenerator->GetCurrentBlock();
  2696. if (currentBlock)
  2697. {
  2698. Assert(currentBlock->nop == knopBlock);
  2699. currentBlock->SetChildCallsEval(true);
  2700. }
  2701. parentFunc->SetHasHeapArguments(true);
  2702. setHasNonLocalReference = true;
  2703. parentFunctionBody->SetAllNonLocalReferenced(true);
  2704. Scope * const funcExprScope = top->funcExprScope;
  2705. if (funcExprScope)
  2706. {
  2707. // If we have the body scope as an object, the outer function expression scope also needs to be an object to propagate the name.
  2708. funcExprScope->SetIsObject();
  2709. }
  2710. if (parentFunc->inArgsCount == 1)
  2711. {
  2712. // If no formals to function, no need to create the propertyid array
  2713. byteCodeGenerator->AssignNullConstRegister();
  2714. }
  2715. }
  2716. if (setHasNonLocalReference && !parentFunctionBody->HasDoneAllNonLocalReferenced())
  2717. {
  2718. parentFunc->GetBodyScope()->ForceAllSymbolNonLocalReference(byteCodeGenerator);
  2719. if (!parentFunc->IsGlobalFunction())
  2720. {
  2721. parentFunc->GetParamScope()->ForceAllSymbolNonLocalReference(byteCodeGenerator);
  2722. }
  2723. parentFunctionBody->SetHasDoneAllNonLocalReferenced(true);
  2724. }
  2725. if (pnodeFnc->IsGenerator())
  2726. {
  2727. top->AssignUndefinedConstRegister();
  2728. }
  2729. if ((top->root->IsConstructor() && (top->GetCallsEval() || top->GetChildCallsEval())) || top->IsClassConstructor())
  2730. {
  2731. if (!top->IsBaseClassConstructor())
  2732. {
  2733. // Derived class constructors need to check undefined against explicit return statements.
  2734. top->AssignUndefinedConstRegister();
  2735. }
  2736. }
  2737. AssignFuncSymRegister(pnodeFnc, byteCodeGenerator, top);
  2738. if (pnodeFnc->pnodeBody && pnodeFnc->HasReferenceableBuiltInArguments() && pnodeFnc->UsesArguments() &&
  2739. pnodeFnc->HasHeapArguments())
  2740. {
  2741. bool doStackArgsOpt = top->byteCodeFunction->GetDoBackendArgumentsOptimization();
  2742. bool hasAnyParamInClosure = top->GetHasLocalInClosure() && top->GetParamScope()->GetHasOwnLocalInClosure();
  2743. if ((doStackArgsOpt && top->inArgsCount > 1))
  2744. {
  2745. if (doStackArgsOpt && hasAnyParamInClosure)
  2746. {
  2747. top->SetHasHeapArguments(true, false /*= Optimize arguments in backend*/);
  2748. #ifdef PERF_HINT
  2749. if (PHASE_TRACE1(Js::PerfHintPhase))
  2750. {
  2751. WritePerfHint(PerfHints::HeapArgumentsDueToNonLocalRef, top->GetParsedFunctionBody(), 0);
  2752. }
  2753. #endif
  2754. }
  2755. else if (!top->GetHasLocalInClosure() && !(byteCodeGenerator->GetFlags() & fscrEval) && !top->byteCodeFunction->IsEval())
  2756. {
  2757. //Scope object creation instr will be a MOV NULL instruction in the Lowerer - if we still decide to do StackArgs after Globopt phase.
  2758. //Note that if we're in eval, scoped ldfld/stfld will traverse the whole frame display, including this slot, so it can't be null.
  2759. top->byteCodeFunction->SetDoScopeObjectCreation(false);
  2760. }
  2761. }
  2762. }
  2763. return top;
  2764. }
  2765. void ByteCodeGenerator::ProcessCapturedSym(Symbol *sym)
  2766. {
  2767. // The symbol's home function will tell us which child function we're currently processing.
  2768. // This is the one that captures the symbol, from the declaring function's perspective.
  2769. // So based on that information, note either that, (a.) the symbol is committed to the heap from its
  2770. // inception, (b.) the symbol must be committed when the capturing function is instantiated.
  2771. FuncInfo *funcHome = sym->GetScope()->GetFunc();
  2772. FuncInfo *funcChild = funcHome->GetCurrentChildFunction();
  2773. Assert(sym->NeedsSlotAlloc(this, funcHome) || sym->GetIsGlobal() || sym->GetIsModuleImport() || sym->GetIsModuleExportStorage());
  2774. if (sym->GetScope()->GetScopeType() == ScopeType_FuncExpr)
  2775. {
  2776. if ((funcHome->GetParamScope() && Scope::HasSymbolName(funcHome->GetParamScope(), sym->GetName())) ||
  2777. (funcHome->IsBodyAndParamScopeMerged() && funcHome->GetBodyScope() && Scope::HasSymbolName(funcHome->GetBodyScope(), sym->GetName())))
  2778. {
  2779. // Make sure the function expression scope gets instantiated, since we can't merge the name symbol into another scope.
  2780. // Make it an object, since that's the only case the code gen can currently handle.
  2781. sym->GetScope()->SetIsObject();
  2782. }
  2783. }
  2784. // If this is not a local property, or not all its references can be tracked, or
  2785. // it's not scoped to the function, or we're in debug mode, disable the delayed capture optimization.
  2786. if (funcHome->IsGlobalFunction() ||
  2787. funcHome->GetCallsEval() ||
  2788. funcHome->GetChildCallsEval() ||
  2789. funcChild == nullptr ||
  2790. sym->GetScope() != funcHome->GetBodyScope() ||
  2791. this->IsInDebugMode() ||
  2792. PHASE_OFF(Js::DelayCapturePhase, funcHome->byteCodeFunction))
  2793. {
  2794. sym->SetIsCommittedToSlot();
  2795. }
  2796. if (sym->GetIsCommittedToSlot())
  2797. {
  2798. return;
  2799. }
  2800. AnalysisAssert(funcChild);
  2801. ParseNode *pnodeChild = funcChild->root;
  2802. Assert(pnodeChild && pnodeChild->nop == knopFncDecl);
  2803. if (pnodeChild->AsParseNodeFnc()->IsDeclaration())
  2804. {
  2805. // The capturing function is a declaration but may still be limited to an inner scope.
  2806. Scope *scopeChild = funcHome->GetCurrentChildScope();
  2807. if (scopeChild == sym->GetScope() || scopeChild->GetScopeType() == ScopeType_FunctionBody)
  2808. {
  2809. // The symbol is captured on entry to the scope in which it's declared.
  2810. // (Check the scope type separately so that we get the special parameter list and
  2811. // named function expression cases as well.)
  2812. sym->SetIsCommittedToSlot();
  2813. return;
  2814. }
  2815. }
  2816. // There is a chance we can limit the region in which the symbol lives on the heap.
  2817. // Note which function captures the symbol.
  2818. funcChild->AddCapturedSym(sym);
  2819. }
  2820. void ByteCodeGenerator::ProcessScopeWithCapturedSym(Scope *scope)
  2821. {
  2822. Assert(scope->GetHasOwnLocalInClosure());
  2823. // (Note: if any catch var is closure-captured, we won't merge the catch scope with the function scope.
  2824. // So don't mark the function scope "has local in closure".)
  2825. FuncInfo *func = scope->GetFunc();
  2826. bool notCatch = scope->GetScopeType() != ScopeType_Catch && scope->GetScopeType() != ScopeType_CatchParamPattern;
  2827. if (scope == func->GetBodyScope() || scope == func->GetParamScope() || (scope->GetCanMerge() && notCatch))
  2828. {
  2829. func->SetHasLocalInClosure(true);
  2830. }
  2831. else
  2832. {
  2833. if (scope->HasCrossScopeFuncAssignment())
  2834. {
  2835. func->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("InstantiateScopeWithCrossScopeAssignment")));
  2836. }
  2837. scope->SetMustInstantiate(true);
  2838. }
  2839. }
  2840. void MarkInit(ParseNode* pnode)
  2841. {
  2842. if (pnode->nop == knopList)
  2843. {
  2844. do
  2845. {
  2846. MarkInit(pnode->AsParseNodeBin()->pnode1);
  2847. pnode = pnode->AsParseNodeBin()->pnode2;
  2848. }
  2849. while (pnode->nop == knopList);
  2850. MarkInit(pnode);
  2851. }
  2852. else
  2853. {
  2854. Symbol *sym = nullptr;
  2855. ParseNode *pnodeInit = nullptr;
  2856. if (pnode->nop == knopVarDecl)
  2857. {
  2858. sym = pnode->AsParseNodeVar()->sym;
  2859. pnodeInit = pnode->AsParseNodeVar()->pnodeInit;
  2860. }
  2861. else if (pnode->nop == knopAsg && pnode->AsParseNodeBin()->pnode1->nop == knopName)
  2862. {
  2863. sym = pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->sym;
  2864. pnodeInit = pnode->AsParseNodeBin()->pnode2;
  2865. }
  2866. if (sym && !sym->GetIsUsed() && pnodeInit)
  2867. {
  2868. sym->SetHasInit(true);
  2869. if (sym->HasVisitedCapturingFunc())
  2870. {
  2871. sym->SetHasNonCommittedReference(false);
  2872. }
  2873. }
  2874. }
  2875. }
  2876. void AddFunctionsToScope(ParseNodePtr scope, ByteCodeGenerator * byteCodeGenerator)
  2877. {
  2878. VisitFncDecls(scope, [byteCodeGenerator](ParseNode *fn)
  2879. {
  2880. ParseNode *pnodeName = fn->AsParseNodeFnc()->pnodeName;
  2881. if (pnodeName && pnodeName->nop == knopVarDecl && fn->AsParseNodeFnc()->IsDeclaration())
  2882. {
  2883. const char16 *fnName = pnodeName->AsParseNodeVar()->pid->Psz();
  2884. if (byteCodeGenerator->Trace())
  2885. {
  2886. Output::Print(_u("current context has declared function %s\n"), fnName);
  2887. }
  2888. // In ES6, functions are scoped to the block, which will be the current scope.
  2889. // Pre-ES6, function declarations are scoped to the function body, so get that scope.
  2890. Symbol *sym;
  2891. if (!byteCodeGenerator->GetCurrentScope()->IsGlobalEvalBlockScope())
  2892. {
  2893. sym = byteCodeGenerator->AddSymbolToScope(byteCodeGenerator->GetCurrentScope(), fnName, pnodeName->AsParseNodeVar()->pid->Cch(), pnodeName, STFunction);
  2894. }
  2895. else
  2896. {
  2897. sym = byteCodeGenerator->AddSymbolToFunctionScope(fnName, pnodeName->AsParseNodeVar()->pid->Cch(), pnodeName, STFunction);
  2898. }
  2899. pnodeName->AsParseNodeVar()->sym = sym;
  2900. if (sym->GetScope() != sym->GetScope()->GetFunc()->GetBodyScope() &&
  2901. sym->GetScope() != sym->GetScope()->GetFunc()->GetParamScope())
  2902. {
  2903. sym->SetIsBlockVar(true);
  2904. }
  2905. }
  2906. });
  2907. }
  2908. template <class PrefixFn, class PostfixFn>
  2909. void VisitNestedScopes(ParseNode* pnodeScopeList, ParseNode* pnodeParent, ByteCodeGenerator* byteCodeGenerator,
  2910. PrefixFn prefix, PostfixFn postfix, uint *pIndex, bool breakOnBodyScope = false)
  2911. {
  2912. // Visit all scopes nested in this scope before visiting this function's statements. This way we have all the
  2913. // attributes of all the inner functions before we assign registers within this function.
  2914. // All the attributes we need to propagate downward should already be recorded by the parser.
  2915. // - call to "eval()"
  2916. // - nested in "with"
  2917. FuncInfo * parentFuncInfo = pnodeParent->AsParseNodeFnc()->funcInfo;
  2918. Js::ParseableFunctionInfo* parentFunc = parentFuncInfo->byteCodeFunction;
  2919. ParseNode* pnodeScope;
  2920. uint i = 0;
  2921. // Cache to restore it back once we come out of current function.
  2922. Js::FunctionBody * pLastReuseFunc = byteCodeGenerator->pCurrentFunction;
  2923. for (pnodeScope = pnodeScopeList; pnodeScope;)
  2924. {
  2925. if (breakOnBodyScope && pnodeScope == pnodeParent->AsParseNodeFnc()->pnodeBodyScope)
  2926. {
  2927. break;
  2928. }
  2929. switch (pnodeScope->nop)
  2930. {
  2931. case knopFncDecl:
  2932. {
  2933. ParseNodeFnc * pnodeFnc = pnodeScope->AsParseNodeFnc();
  2934. if (pLastReuseFunc)
  2935. {
  2936. if (!byteCodeGenerator->IsInNonDebugMode())
  2937. {
  2938. // Here we are trying to match the inner sub-tree as well with already created inner function.
  2939. if ((pLastReuseFunc->GetIsGlobalFunc() && parentFunc->GetIsGlobalFunc())
  2940. || (!pLastReuseFunc->GetIsGlobalFunc() && !parentFunc->GetIsGlobalFunc()))
  2941. {
  2942. Assert(pLastReuseFunc->StartInDocument() == pnodeParent->ichMin);
  2943. Assert(pLastReuseFunc->LengthInChars() == pnodeParent->LengthInCodepoints());
  2944. Assert(pLastReuseFunc->GetNestedCount() == parentFunc->GetNestedCount());
  2945. // If the current function is not parsed yet, its function body is not generated yet.
  2946. // Reset pCurrentFunction to null so that it will not be able re-use anything.
  2947. Js::FunctionProxy* proxy = pLastReuseFunc->GetNestedFunctionProxy((*pIndex));
  2948. if (proxy && proxy->IsFunctionBody())
  2949. {
  2950. byteCodeGenerator->pCurrentFunction = proxy->GetFunctionBody();
  2951. }
  2952. else
  2953. {
  2954. byteCodeGenerator->pCurrentFunction = nullptr;
  2955. }
  2956. }
  2957. }
  2958. else if (!parentFunc->GetIsGlobalFunc())
  2959. {
  2960. // In the deferred parsing mode, we will be reusing the only one function (which is asked when on ::Begin) all inner function will be created.
  2961. byteCodeGenerator->pCurrentFunction = nullptr;
  2962. }
  2963. }
  2964. Js::ParseableFunctionInfo::NestedArray * parentNestedArray = parentFunc->GetNestedArray();
  2965. Js::ParseableFunctionInfo* reuseNestedFunc = nullptr;
  2966. if (parentNestedArray)
  2967. {
  2968. Assert(*pIndex < parentNestedArray->nestedCount);
  2969. Js::FunctionInfo * info = parentNestedArray->functionInfoArray[*pIndex];
  2970. if (info && info->HasParseableInfo())
  2971. {
  2972. reuseNestedFunc = info->GetParseableFunctionInfo();
  2973. // If parentFunc was redeferred, try to set pCurrentFunction to this FunctionBody,
  2974. // and cleanup to reparse (as previous cleanup stops at redeferred parentFunc).
  2975. if (!byteCodeGenerator->IsInNonDebugMode()
  2976. && !byteCodeGenerator->pCurrentFunction
  2977. && reuseNestedFunc->IsFunctionBody())
  2978. {
  2979. byteCodeGenerator->pCurrentFunction = reuseNestedFunc->GetFunctionBody();
  2980. }
  2981. }
  2982. }
  2983. PreVisitFunction(pnodeFnc, byteCodeGenerator, reuseNestedFunc);
  2984. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2985. parentFuncInfo->OnStartVisitFunction(pnodeFnc);
  2986. if (pnodeFnc->pnodeBody)
  2987. {
  2988. if (!byteCodeGenerator->IsInNonDebugMode() && pLastReuseFunc != nullptr && byteCodeGenerator->pCurrentFunction == nullptr)
  2989. {
  2990. // Patch current non-parsed function's FunctionBodyImpl with the new generated function body.
  2991. // So that the function object (pointing to the old function body) can able to get to the new one.
  2992. Js::FunctionProxy* proxy = pLastReuseFunc->GetNestedFunctionProxy((*pIndex));
  2993. if (proxy && !proxy->IsFunctionBody())
  2994. {
  2995. proxy->UpdateFunctionBodyImpl(funcInfo->byteCodeFunction->GetFunctionBody());
  2996. }
  2997. }
  2998. Scope *paramScope = funcInfo->GetParamScope();
  2999. Scope *bodyScope = funcInfo->GetBodyScope();
  3000. BeginVisitBlock(pnodeFnc->pnodeScopes, byteCodeGenerator);
  3001. i = 0;
  3002. ParseNodePtr containerScope = pnodeFnc->pnodeScopes;
  3003. // Push the param scope
  3004. byteCodeGenerator->PushScope(paramScope);
  3005. if (pnodeFnc->HasNonSimpleParameterList() && !funcInfo->IsBodyAndParamScopeMerged())
  3006. {
  3007. // Set param scope as the current child scope.
  3008. funcInfo->SetCurrentChildScope(paramScope);
  3009. Assert(containerScope->nop == knopBlock && containerScope->AsParseNodeBlock()->blockType == Parameter);
  3010. VisitNestedScopes(containerScope->AsParseNodeBlock()->pnodeScopes, pnodeFnc, byteCodeGenerator, prefix, postfix, &i, true);
  3011. MapFormals(pnodeFnc, [&](ParseNode *argNode) { Visit(argNode, byteCodeGenerator, prefix, postfix); });
  3012. }
  3013. // Push the body scope
  3014. byteCodeGenerator->PushScope(bodyScope);
  3015. funcInfo->SetCurrentChildScope(bodyScope);
  3016. PreVisitBlock(pnodeFnc->pnodeBodyScope, byteCodeGenerator);
  3017. AddVarsToScope(pnodeFnc->pnodeVars, byteCodeGenerator);
  3018. if (!pnodeFnc->HasNonSimpleParameterList() || funcInfo->IsBodyAndParamScopeMerged())
  3019. {
  3020. VisitNestedScopes(containerScope, pnodeFnc, byteCodeGenerator, prefix, postfix, &i);
  3021. MapFormals(pnodeFnc, [&](ParseNode *argNode) { Visit(argNode, byteCodeGenerator, prefix, postfix); });
  3022. }
  3023. if (pnodeFnc->HasNonSimpleParameterList())
  3024. {
  3025. byteCodeGenerator->AssignUndefinedConstRegister();
  3026. if (!funcInfo->IsBodyAndParamScopeMerged())
  3027. {
  3028. Assert(pnodeFnc->pnodeBodyScope->scope);
  3029. VisitNestedScopes(pnodeFnc->pnodeBodyScope->pnodeScopes, pnodeFnc, byteCodeGenerator, prefix, postfix, &i);
  3030. }
  3031. }
  3032. BeginVisitBlock(pnodeFnc->pnodeBodyScope, byteCodeGenerator);
  3033. ParseNode* pnode = pnodeFnc->pnodeBody;
  3034. while (pnode->nop == knopList)
  3035. {
  3036. // Check to see whether initializations of locals to "undef" can be skipped.
  3037. // The logic to do this is cheap - omit the init if we see an init with a value
  3038. // on the RHS at the top statement level (i.e., not inside a block, try, loop, etc.)
  3039. // before we see a use. The motivation is to help identify single-def locals in the BE.
  3040. // Note that this can't be done for globals.
  3041. byteCodeGenerator->SetCurrentTopStatement(pnode->AsParseNodeBin()->pnode1);
  3042. Visit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, prefix, postfix);
  3043. if (!funcInfo->GetCallsEval() && !funcInfo->GetChildCallsEval() &&
  3044. // So that it will not be marked as init thus it will be added to the diagnostics symbols container.
  3045. !(byteCodeGenerator->ShouldTrackDebuggerMetadata()))
  3046. {
  3047. MarkInit(pnode->AsParseNodeBin()->pnode1);
  3048. }
  3049. pnode = pnode->AsParseNodeBin()->pnode2;
  3050. }
  3051. byteCodeGenerator->SetCurrentTopStatement(pnode);
  3052. Visit(pnode, byteCodeGenerator, prefix, postfix);
  3053. EndVisitBlock(pnodeFnc->pnodeBodyScope, byteCodeGenerator);
  3054. EndVisitBlock(pnodeFnc->pnodeScopes, byteCodeGenerator);
  3055. }
  3056. if (!pnodeFnc->pnodeBody)
  3057. {
  3058. // For defer prase scenario push the scopes here
  3059. byteCodeGenerator->PushScope(funcInfo->GetParamScope());
  3060. byteCodeGenerator->PushScope(funcInfo->GetBodyScope());
  3061. }
  3062. if (!parentFuncInfo->IsFakeGlobalFunction(byteCodeGenerator->GetFlags()))
  3063. {
  3064. pnodeFnc->nestedIndex = *pIndex;
  3065. parentFunc->SetNestedFunc(funcInfo->byteCodeFunction->GetFunctionInfo(), (*pIndex)++, byteCodeGenerator->GetFlags());
  3066. }
  3067. Assert(parentFunc);
  3068. parentFuncInfo->OnEndVisitFunction(pnodeFnc);
  3069. PostVisitFunction(pnodeFnc, byteCodeGenerator);
  3070. pnodeScope = pnodeFnc->pnodeNext;
  3071. byteCodeGenerator->pCurrentFunction = pLastReuseFunc;
  3072. break;
  3073. }
  3074. case knopBlock:
  3075. {
  3076. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  3077. PreVisitBlock(pnodeBlockScope, byteCodeGenerator);
  3078. bool isMergedScope;
  3079. parentFuncInfo->OnStartVisitScope(pnodeBlockScope->scope, &isMergedScope);
  3080. VisitNestedScopes(pnodeBlockScope->pnodeScopes, pnodeParent, byteCodeGenerator, prefix, postfix, pIndex);
  3081. parentFuncInfo->OnEndVisitScope(pnodeBlockScope->scope, isMergedScope);
  3082. PostVisitBlock(pnodeBlockScope, byteCodeGenerator);
  3083. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  3084. break;
  3085. }
  3086. case knopCatch:
  3087. {
  3088. ParseNodeCatch * pnodeCatchScope = pnodeScope->AsParseNodeCatch();
  3089. PreVisitCatch(pnodeCatchScope, byteCodeGenerator);
  3090. if (pnodeCatchScope->HasParam() && !pnodeCatchScope->HasPatternParam())
  3091. {
  3092. Visit(pnodeCatchScope->GetParam(), byteCodeGenerator, prefix, postfix);
  3093. }
  3094. bool isMergedScope;
  3095. parentFuncInfo->OnStartVisitScope(pnodeCatchScope->scope, &isMergedScope);
  3096. VisitNestedScopes(pnodeCatchScope->pnodeScopes, pnodeParent, byteCodeGenerator, prefix, postfix, pIndex);
  3097. parentFuncInfo->OnEndVisitScope(pnodeCatchScope->scope, isMergedScope);
  3098. PostVisitCatch(pnodeCatchScope, byteCodeGenerator);
  3099. pnodeScope = pnodeCatchScope->pnodeNext;
  3100. break;
  3101. }
  3102. case knopWith:
  3103. {
  3104. PreVisitWith(pnodeScope, byteCodeGenerator);
  3105. bool isMergedScope;
  3106. parentFuncInfo->OnStartVisitScope(pnodeScope->AsParseNodeWith()->scope, &isMergedScope);
  3107. VisitNestedScopes(pnodeScope->AsParseNodeWith()->pnodeScopes, pnodeParent, byteCodeGenerator, prefix, postfix, pIndex);
  3108. parentFuncInfo->OnEndVisitScope(pnodeScope->AsParseNodeWith()->scope, isMergedScope);
  3109. PostVisitWith(pnodeScope, byteCodeGenerator);
  3110. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  3111. break;
  3112. }
  3113. default:
  3114. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3115. return;
  3116. }
  3117. }
  3118. }
  3119. void PreVisitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator)
  3120. {
  3121. if (!pnodeBlock->scope &&
  3122. !pnodeBlock->HasBlockScopedContent() &&
  3123. !pnodeBlock->GetCallsEval())
  3124. {
  3125. // Do nothing here if the block doesn't declare anything or call eval (which may declare something).
  3126. return;
  3127. }
  3128. bool isGlobalEvalBlockScope = false;
  3129. FuncInfo *func = byteCodeGenerator->TopFuncInfo();
  3130. if (func->IsGlobalFunction() &&
  3131. func->root->pnodeScopes == pnodeBlock &&
  3132. byteCodeGenerator->IsEvalWithNoParentScopeInfo())
  3133. {
  3134. isGlobalEvalBlockScope = true;
  3135. }
  3136. Assert(!pnodeBlock->scope ||
  3137. isGlobalEvalBlockScope == (pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock));
  3138. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  3139. Scope *scope;
  3140. if ((pnodeBlock->blockType == PnodeBlockType::Global && !byteCodeGenerator->IsEvalWithNoParentScopeInfo()) || pnodeBlock->blockType == PnodeBlockType::Function)
  3141. {
  3142. scope = byteCodeGenerator->GetCurrentScope();
  3143. if (pnodeBlock->blockType == PnodeBlockType::Function)
  3144. {
  3145. AnalysisAssert(pnodeBlock->scope);
  3146. if (pnodeBlock->scope->GetScopeType() == ScopeType_Parameter
  3147. && scope->GetScopeType() == ScopeType_FunctionBody)
  3148. {
  3149. scope = scope->GetEnclosingScope();
  3150. }
  3151. }
  3152. pnodeBlock->scope = scope;
  3153. }
  3154. else if (!(pnodeBlock->grfpn & fpnSyntheticNode) || isGlobalEvalBlockScope)
  3155. {
  3156. scope = pnodeBlock->scope;
  3157. if (!scope)
  3158. {
  3159. scope = Anew(alloc, Scope, alloc,
  3160. isGlobalEvalBlockScope? ScopeType_GlobalEvalBlock : ScopeType_Block, true);
  3161. pnodeBlock->scope = scope;
  3162. }
  3163. scope->SetFunc(byteCodeGenerator->TopFuncInfo());
  3164. // For now, prevent block scope from being merged with enclosing function scope.
  3165. // Consider optimizing this.
  3166. scope->SetCanMerge(false);
  3167. if (isGlobalEvalBlockScope)
  3168. {
  3169. scope->SetIsObject();
  3170. }
  3171. byteCodeGenerator->PushScope(scope);
  3172. byteCodeGenerator->PushBlock(pnodeBlock);
  3173. }
  3174. else
  3175. {
  3176. return;
  3177. }
  3178. Assert(scope && scope == pnodeBlock->scope);
  3179. bool isGlobalScope = (scope->GetEnclosingScope() == nullptr);
  3180. Assert(!isGlobalScope || (pnodeBlock->grfpn & fpnSyntheticNode));
  3181. // If it is the global eval block scope, we don't what function decl to be assigned in the block scope.
  3182. // They should already declared in the global function's scope.
  3183. if (!isGlobalEvalBlockScope && !isGlobalScope)
  3184. {
  3185. AddFunctionsToScope(pnodeBlock->pnodeScopes, byteCodeGenerator);
  3186. }
  3187. // We can skip this check by not creating the GlobalEvalBlock above and in Parser::Parse for console eval but that seems to break couple of places
  3188. // as we heavily depend on BlockHasOwnScope function. Once we clean up the creation of GlobalEvalBlock for evals we can clean this as well.
  3189. if (byteCodeGenerator->IsConsoleScopeEval() && isGlobalEvalBlockScope && !isGlobalScope)
  3190. {
  3191. AssertMsg(scope->GetEnclosingScope()->GetScopeType() == ScopeType_Global, "Additional scope between Global and GlobalEvalBlock?");
  3192. scope = scope->GetEnclosingScope();
  3193. isGlobalScope = true;
  3194. }
  3195. auto addSymbolToScope = [scope, byteCodeGenerator, isGlobalScope](ParseNode *pnode)
  3196. {
  3197. Symbol *sym = byteCodeGenerator->AddSymbolToScope(scope, reinterpret_cast<const char16*>(pnode->AsParseNodeVar()->pid->Psz()), pnode->AsParseNodeVar()->pid->Cch(), pnode, STVariable);
  3198. #if DBG_DUMP
  3199. if (sym->GetSymbolType() == STVariable && byteCodeGenerator->Trace())
  3200. {
  3201. Output::Print(_u("current context has declared %s %s of type %s\n"),
  3202. sym->GetDecl()->nop == knopLetDecl ? _u("let") : _u("const"),
  3203. pnode->AsParseNodeVar()->pid->Psz(),
  3204. sym->GetSymbolTypeName());
  3205. }
  3206. #endif
  3207. sym->SetIsGlobal(isGlobalScope);
  3208. sym->SetIsBlockVar(true);
  3209. sym->SetIsConst(pnode->nop == knopConstDecl);
  3210. sym->SetNeedDeclaration(true);
  3211. pnode->AsParseNodeVar()->sym = sym;
  3212. };
  3213. byteCodeGenerator->IterateBlockScopedVariables(pnodeBlock, addSymbolToScope);
  3214. }
  3215. void PostVisitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator)
  3216. {
  3217. if (!BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  3218. {
  3219. return;
  3220. }
  3221. Scope *scope = pnodeBlock->scope;
  3222. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (byteCodeGenerator->GetFlags() & (fscrEval | fscrImplicitThis)))
  3223. {
  3224. bool scopeIsEmpty = scope->IsEmpty();
  3225. scope->SetIsObject();
  3226. scope->SetCapturesAll(true);
  3227. scope->SetMustInstantiate(!scopeIsEmpty);
  3228. }
  3229. if (scope->GetHasOwnLocalInClosure())
  3230. {
  3231. byteCodeGenerator->ProcessScopeWithCapturedSym(scope);
  3232. }
  3233. byteCodeGenerator->PopScope();
  3234. byteCodeGenerator->PopBlock();
  3235. ParseNodeBlock *currentBlock = byteCodeGenerator->GetCurrentBlock();
  3236. if (currentBlock && (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval()))
  3237. {
  3238. currentBlock->SetChildCallsEval(true);
  3239. }
  3240. }
  3241. void PreVisitCatch(ParseNodeCatch *pnodeCatch, ByteCodeGenerator *byteCodeGenerator)
  3242. {
  3243. // Push the catch scope and add the catch expression to it.
  3244. byteCodeGenerator->StartBindCatch(pnodeCatch);
  3245. if (pnodeCatch->HasPatternParam())
  3246. {
  3247. ParseNodeParamPattern * pnodeParamPattern = pnodeCatch->GetParam()->AsParseNodeParamPattern();
  3248. Parser::MapBindIdentifier(pnodeParamPattern->pnode1, [&](ParseNodePtr item)
  3249. {
  3250. Symbol *sym = item->AsParseNodeVar()->sym;
  3251. #if DBG_DUMP
  3252. if (byteCodeGenerator->Trace())
  3253. {
  3254. Output::Print(_u("current context has declared catch var %s of type %s\n"),
  3255. item->AsParseNodeVar()->pid->Psz(), sym->GetSymbolTypeName());
  3256. }
  3257. #endif
  3258. sym->SetIsCatch(true);
  3259. sym->SetIsBlockVar(true);
  3260. });
  3261. }
  3262. else if (pnodeCatch->HasParam())
  3263. {
  3264. ParseNodeName * pnodeName = pnodeCatch->GetParam()->AsParseNodeName();
  3265. Symbol *sym = *pnodeName->GetSymRef();
  3266. Assert(sym->GetScope() == pnodeCatch->scope);
  3267. #if DBG_DUMP
  3268. if (byteCodeGenerator->Trace())
  3269. {
  3270. Output::Print(_u("current context has declared catch var %s of type %s\n"),
  3271. pnodeName->pid->Psz(), sym->GetSymbolTypeName());
  3272. }
  3273. #endif
  3274. sym->SetIsCatch(true);
  3275. pnodeName->sym = sym;
  3276. }
  3277. // This call will actually add the nested function symbols to the enclosing function scope (which is what we want).
  3278. AddFunctionsToScope(pnodeCatch->pnodeScopes, byteCodeGenerator);
  3279. }
  3280. void PostVisitCatch(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3281. {
  3282. Scope *scope = pnode->AsParseNodeCatch()->scope;
  3283. if (scope->GetHasOwnLocalInClosure())
  3284. {
  3285. byteCodeGenerator->ProcessScopeWithCapturedSym(scope);
  3286. }
  3287. byteCodeGenerator->EndBindCatch();
  3288. }
  3289. void PreVisitWith(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3290. {
  3291. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  3292. Scope *scope = Anew(alloc, Scope, alloc, ScopeType_With);
  3293. scope->SetFunc(byteCodeGenerator->TopFuncInfo());
  3294. scope->SetIsDynamic(true);
  3295. pnode->AsParseNodeWith()->scope = scope;
  3296. byteCodeGenerator->PushScope(scope);
  3297. }
  3298. void PostVisitWith(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3299. {
  3300. byteCodeGenerator->PopScope();
  3301. }
  3302. bool IsMathLibraryId(Js::PropertyId propertyId)
  3303. {
  3304. return (propertyId >= Js::PropertyIds::abs) && (propertyId <= Js::PropertyIds::fround);
  3305. }
  3306. bool IsLibraryFunction(ParseNode* expr, Js::ScriptContext* scriptContext)
  3307. {
  3308. if (expr && expr->nop == knopDot)
  3309. {
  3310. ParseNode* lhs = expr->AsParseNodeBin()->pnode1;
  3311. ParseNode* rhs = expr->AsParseNodeBin()->pnode2;
  3312. if ((lhs != nullptr) && (rhs != nullptr) && (lhs->nop == knopName) && (rhs->nop == knopName))
  3313. {
  3314. Symbol* lsym = lhs->AsParseNodeName()->sym;
  3315. if ((lsym == nullptr || lsym->GetIsGlobal()) && lhs->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Math)
  3316. {
  3317. return IsMathLibraryId(rhs->AsParseNodeName()->PropertyIdFromNameNode());
  3318. }
  3319. }
  3320. }
  3321. return false;
  3322. }
  3323. struct SymCheck
  3324. {
  3325. static const int kMaxInvertedSyms = 8;
  3326. Symbol* syms[kMaxInvertedSyms];
  3327. Symbol* permittedSym;
  3328. int symCount;
  3329. bool result;
  3330. bool cond;
  3331. bool AddSymbol(Symbol* sym)
  3332. {
  3333. if (symCount < kMaxInvertedSyms)
  3334. {
  3335. syms[symCount++] = sym;
  3336. return true;
  3337. }
  3338. else
  3339. {
  3340. return false;
  3341. }
  3342. }
  3343. bool MatchSymbol(Symbol* sym)
  3344. {
  3345. if (sym != permittedSym)
  3346. {
  3347. for (int i = 0; i < symCount; i++)
  3348. {
  3349. if (sym == syms[i])
  3350. {
  3351. return true;
  3352. }
  3353. }
  3354. }
  3355. return false;
  3356. }
  3357. void Init()
  3358. {
  3359. symCount = 0;
  3360. result = true;
  3361. }
  3362. };
  3363. void CheckInvertableExpr(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, SymCheck* symCheck)
  3364. {
  3365. if (symCheck->result)
  3366. {
  3367. switch (pnode->nop)
  3368. {
  3369. case knopName:
  3370. if (symCheck->MatchSymbol(pnode->AsParseNodeName()->sym))
  3371. {
  3372. symCheck->result = false;
  3373. }
  3374. break;
  3375. case knopCall:
  3376. {
  3377. ParseNode* callTarget = pnode->AsParseNodeCall()->pnodeTarget;
  3378. if (callTarget != nullptr)
  3379. {
  3380. if (callTarget->nop == knopName)
  3381. {
  3382. Symbol* sym = callTarget->AsParseNodeName()->sym;
  3383. if (sym && sym->SingleDef())
  3384. {
  3385. ParseNode* decl = sym->GetDecl();
  3386. if (decl == nullptr ||
  3387. decl->nop != knopVarDecl ||
  3388. !IsLibraryFunction(decl->AsParseNodeVar()->pnodeInit, byteCodeGenerator->GetScriptContext()))
  3389. {
  3390. symCheck->result = false;
  3391. }
  3392. }
  3393. else
  3394. {
  3395. symCheck->result = false;
  3396. }
  3397. }
  3398. else if (callTarget->nop == knopDot)
  3399. {
  3400. if (!IsLibraryFunction(callTarget, byteCodeGenerator->GetScriptContext()))
  3401. {
  3402. symCheck->result = false;
  3403. }
  3404. }
  3405. }
  3406. else
  3407. {
  3408. symCheck->result = false;
  3409. }
  3410. break;
  3411. }
  3412. case knopDot:
  3413. if (!IsLibraryFunction(pnode, byteCodeGenerator->GetScriptContext()))
  3414. {
  3415. symCheck->result = false;
  3416. }
  3417. break;
  3418. case knopTrue:
  3419. case knopFalse:
  3420. case knopAdd:
  3421. case knopSub:
  3422. case knopDiv:
  3423. case knopMul:
  3424. case knopExpo:
  3425. case knopMod:
  3426. case knopNeg:
  3427. case knopInt:
  3428. case knopFlt:
  3429. case knopLt:
  3430. case knopGt:
  3431. case knopLe:
  3432. case knopGe:
  3433. case knopEq:
  3434. case knopNe:
  3435. break;
  3436. default:
  3437. symCheck->result = false;
  3438. break;
  3439. }
  3440. }
  3441. }
  3442. bool InvertableExpr(SymCheck* symCheck, ParseNode* expr, ByteCodeGenerator* byteCodeGenerator)
  3443. {
  3444. symCheck->result = true;
  3445. symCheck->cond = false;
  3446. symCheck->permittedSym = nullptr;
  3447. VisitIndirect<SymCheck>(expr, byteCodeGenerator, symCheck, &CheckInvertableExpr, nullptr);
  3448. return symCheck->result;
  3449. }
  3450. bool InvertableExprPlus(SymCheck* symCheck, ParseNode* expr, ByteCodeGenerator* byteCodeGenerator, Symbol* permittedSym)
  3451. {
  3452. symCheck->result = true;
  3453. symCheck->cond = true;
  3454. symCheck->permittedSym = permittedSym;
  3455. VisitIndirect<SymCheck>(expr, byteCodeGenerator, symCheck, &CheckInvertableExpr, nullptr);
  3456. return symCheck->result;
  3457. }
  3458. void CheckLocalVarDef(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3459. {
  3460. Assert(pnode->nop == knopAsg);
  3461. if (pnode->AsParseNodeBin()->pnode1 != nullptr)
  3462. {
  3463. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  3464. if (lhs->nop == knopName)
  3465. {
  3466. Symbol *sym = lhs->AsParseNodeName()->sym;
  3467. if (sym != nullptr)
  3468. {
  3469. sym->RecordDef();
  3470. if (sym->IsUsedInLdElem())
  3471. {
  3472. Ident::TrySetIsUsedInLdElem(pnode->AsParseNodeBin()->pnode2);
  3473. }
  3474. }
  3475. }
  3476. }
  3477. }
  3478. ParseNode* ConstructInvertedStatement(ParseNode* stmt, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo,
  3479. ParseNodeBin** outerStmtRef)
  3480. {
  3481. if (stmt == nullptr)
  3482. {
  3483. return nullptr;
  3484. }
  3485. ParseNode * cStmt;
  3486. if ((stmt->nop == knopAsg) || (stmt->nop == knopVarDecl))
  3487. {
  3488. ParseNode * rhs = nullptr;
  3489. ParseNode * lhs = nullptr;
  3490. if (stmt->nop == knopAsg)
  3491. {
  3492. rhs = stmt->AsParseNodeBin()->pnode2;
  3493. lhs = stmt->AsParseNodeBin()->pnode1;
  3494. }
  3495. else if (stmt->nop == knopVarDecl)
  3496. {
  3497. rhs = stmt->AsParseNodeVar()->pnodeInit;
  3498. }
  3499. ArenaAllocator * alloc = byteCodeGenerator->GetAllocator();
  3500. ParseNodeVar * loopInvar = Parser::StaticCreateTempNode(rhs, alloc);
  3501. loopInvar->location = funcInfo->NextVarRegister();
  3502. // Can't use a temp register here because the inversion happens at the parse tree level without generating
  3503. // any bytecode yet. All local non-temp registers need to be initialized for jitted loop bodies, and since this is
  3504. // not a user variable, track this register separately to have it be initialized at the top of the function.
  3505. funcInfo->nonUserNonTempRegistersToInitialize.Add(loopInvar->location);
  3506. // add temp node to list of initializers for new outer loop
  3507. if ((*outerStmtRef)->pnode1 == nullptr)
  3508. {
  3509. (*outerStmtRef)->pnode1 = loopInvar;
  3510. }
  3511. else
  3512. {
  3513. ParseNodeBin * listNode = Parser::StaticCreateBinNode(knopList, nullptr, nullptr, alloc);
  3514. (*outerStmtRef)->pnode2 = listNode;
  3515. listNode->pnode1 = loopInvar;
  3516. *outerStmtRef = listNode;
  3517. }
  3518. ParseNodeUni * tempName = Parser::StaticCreateTempRef(loopInvar, alloc);
  3519. if (lhs != nullptr)
  3520. {
  3521. cStmt = Parser::StaticCreateBinNode(knopAsg, lhs, tempName, alloc);
  3522. }
  3523. else
  3524. {
  3525. // Use AddVarDeclNode to add the var to the function.
  3526. // Do not use CreateVarDeclNode which is meant to be used while parsing. It assumes that
  3527. // parser's internal data structures (m_ppnodeVar in particular) is at the "current" location.
  3528. cStmt = byteCodeGenerator->GetParser()->AddVarDeclNode(stmt->AsParseNodeVar()->pid, funcInfo->root);
  3529. cStmt->AsParseNodeVar()->pnodeInit = tempName;
  3530. cStmt->AsParseNodeVar()->sym = stmt->AsParseNodeVar()->sym;
  3531. }
  3532. }
  3533. else
  3534. {
  3535. cStmt = byteCodeGenerator->GetParser()->CopyPnode(stmt);
  3536. }
  3537. return cStmt;
  3538. }
  3539. ParseNodeFor* ConstructInvertedLoop(ParseNode* innerLoop, ParseNode* outerLoop, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  3540. {
  3541. ArenaAllocator* alloc = byteCodeGenerator->GetAllocator();
  3542. ParseNodeFor * outerLoopC = Parser::StaticCreateNodeT<knopFor>(alloc);
  3543. outerLoopC->pnodeInit = innerLoop->AsParseNodeFor()->pnodeInit;
  3544. outerLoopC->pnodeCond = innerLoop->AsParseNodeFor()->pnodeCond;
  3545. outerLoopC->pnodeIncr = innerLoop->AsParseNodeFor()->pnodeIncr;
  3546. outerLoopC->pnodeBlock = innerLoop->AsParseNodeFor()->pnodeBlock;
  3547. outerLoopC->pnodeInverted = nullptr;
  3548. ParseNodeFor * innerLoopC = Parser::StaticCreateNodeT<knopFor>(alloc);
  3549. innerLoopC->pnodeInit = outerLoop->AsParseNodeFor()->pnodeInit;
  3550. innerLoopC->pnodeCond = outerLoop->AsParseNodeFor()->pnodeCond;
  3551. innerLoopC->pnodeIncr = outerLoop->AsParseNodeFor()->pnodeIncr;
  3552. innerLoopC->pnodeBlock = outerLoop->AsParseNodeFor()->pnodeBlock;
  3553. innerLoopC->pnodeInverted = nullptr;
  3554. ParseNodeBlock * innerBod = Parser::StaticCreateBlockNode(alloc);
  3555. innerLoopC->pnodeBody = innerBod;
  3556. innerBod->scope = innerLoop->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->scope;
  3557. ParseNodeBlock * outerBod = Parser::StaticCreateBlockNode(alloc);
  3558. outerLoopC->pnodeBody = outerBod;
  3559. outerBod->scope = outerLoop->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->scope;
  3560. ParseNodeBin * listNode = Parser::StaticCreateBinNode(knopList, nullptr, nullptr, alloc);
  3561. outerBod->pnodeStmt = listNode;
  3562. ParseNode* innerBodOriginal = innerLoop->AsParseNodeFor()->pnodeBody;
  3563. ParseNode* origStmt = innerBodOriginal->AsParseNodeBlock()->pnodeStmt;
  3564. if (origStmt->nop == knopList)
  3565. {
  3566. ParseNode* invertedStmt = nullptr;
  3567. while (origStmt->nop == knopList)
  3568. {
  3569. ParseNode* invertedItem = ConstructInvertedStatement(origStmt->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, &listNode);
  3570. ParseNode * newInvertedStmt = Parser::StaticCreateBinNode(knopList, invertedItem, nullptr, alloc, invertedItem->ichMin, invertedItem->ichLim);
  3571. if (invertedStmt != nullptr)
  3572. {
  3573. invertedStmt = invertedStmt->AsParseNodeBin()->pnode2 = newInvertedStmt;
  3574. }
  3575. else
  3576. {
  3577. invertedStmt = innerBod->pnodeStmt = newInvertedStmt;
  3578. }
  3579. origStmt = origStmt->AsParseNodeBin()->pnode2;
  3580. }
  3581. Assert(invertedStmt != nullptr);
  3582. invertedStmt->AsParseNodeBin()->pnode2 = ConstructInvertedStatement(origStmt, byteCodeGenerator, funcInfo, &listNode);
  3583. }
  3584. else
  3585. {
  3586. innerBod->pnodeStmt = ConstructInvertedStatement(origStmt, byteCodeGenerator, funcInfo, &listNode);
  3587. }
  3588. if (listNode->pnode1 == nullptr)
  3589. {
  3590. listNode->pnode1 = Parser::StaticCreateTempNode(nullptr, alloc);
  3591. }
  3592. listNode->pnode2 = innerLoopC;
  3593. return outerLoopC;
  3594. }
  3595. bool InvertableStmt(ParseNode* stmt, Symbol* outerVar, ParseNode* innerLoop, ParseNode* outerLoop, ByteCodeGenerator* byteCodeGenerator, SymCheck* symCheck)
  3596. {
  3597. if (stmt != nullptr)
  3598. {
  3599. ParseNode* lhs = nullptr;
  3600. ParseNode* rhs = nullptr;
  3601. if (stmt->nop == knopAsg)
  3602. {
  3603. lhs = stmt->AsParseNodeBin()->pnode1;
  3604. rhs = stmt->AsParseNodeBin()->pnode2;
  3605. }
  3606. else if (stmt->nop == knopVarDecl)
  3607. {
  3608. rhs = stmt->AsParseNodeVar()->pnodeInit;
  3609. }
  3610. if (lhs != nullptr)
  3611. {
  3612. if (lhs->nop == knopDot)
  3613. {
  3614. return false;
  3615. }
  3616. if (lhs->nop == knopName)
  3617. {
  3618. if ((lhs->AsParseNodeName()->sym != nullptr) && (lhs->AsParseNodeName()->sym->GetIsGlobal()))
  3619. {
  3620. return false;
  3621. }
  3622. }
  3623. else if (lhs->nop == knopIndex)
  3624. {
  3625. ParseNode* indexed = lhs->AsParseNodeBin()->pnode1;
  3626. ParseNode* index = lhs->AsParseNodeBin()->pnode2;
  3627. if ((index == nullptr) || (indexed == nullptr))
  3628. {
  3629. return false;
  3630. }
  3631. if ((indexed->nop != knopName) || (indexed->AsParseNodeName()->sym == nullptr))
  3632. {
  3633. return false;
  3634. }
  3635. if (!InvertableExprPlus(symCheck, index, byteCodeGenerator, outerVar))
  3636. {
  3637. return false;
  3638. }
  3639. }
  3640. }
  3641. if (rhs != nullptr)
  3642. {
  3643. if (!InvertableExpr(symCheck, rhs, byteCodeGenerator))
  3644. {
  3645. return false;
  3646. }
  3647. }
  3648. else
  3649. {
  3650. if (!InvertableExpr(symCheck, stmt, byteCodeGenerator))
  3651. {
  3652. return false;
  3653. }
  3654. }
  3655. return true;
  3656. }
  3657. return false;
  3658. }
  3659. bool GatherInversionSyms(ParseNode* stmt, Symbol* outerVar, ParseNode* innerLoop, ByteCodeGenerator* byteCodeGenerator, SymCheck* symCheck)
  3660. {
  3661. if (stmt != nullptr)
  3662. {
  3663. ParseNode* lhs = nullptr;
  3664. Symbol* auxSym = nullptr;
  3665. if (stmt->nop == knopAsg)
  3666. {
  3667. lhs = stmt->AsParseNodeBin()->pnode1;
  3668. }
  3669. else if (stmt->nop == knopVarDecl)
  3670. {
  3671. auxSym = stmt->AsParseNodeVar()->sym;
  3672. }
  3673. if (lhs != nullptr)
  3674. {
  3675. if (lhs->nop == knopDot)
  3676. {
  3677. return false;
  3678. }
  3679. if (lhs->nop == knopName)
  3680. {
  3681. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  3682. if ((pnodeNameLhs->sym == nullptr) || (pnodeNameLhs->sym->GetIsGlobal()))
  3683. {
  3684. return false;
  3685. }
  3686. else
  3687. {
  3688. auxSym = pnodeNameLhs->sym;
  3689. }
  3690. }
  3691. }
  3692. if (auxSym != nullptr)
  3693. {
  3694. return symCheck->AddSymbol(auxSym);
  3695. }
  3696. }
  3697. return true;
  3698. }
  3699. bool InvertableBlock(ParseNode* block, Symbol* outerVar, ParseNode* innerLoop, ParseNode* outerLoop, ByteCodeGenerator* byteCodeGenerator,
  3700. SymCheck* symCheck)
  3701. {
  3702. if (block == nullptr)
  3703. {
  3704. return false;
  3705. }
  3706. if (!symCheck->AddSymbol(outerVar))
  3707. {
  3708. return false;
  3709. }
  3710. if ((innerLoop->AsParseNodeFor()->pnodeBody->nop == knopBlock && innerLoop->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->HasBlockScopedContent())
  3711. || (outerLoop->AsParseNodeFor()->pnodeBody->nop == knopBlock && outerLoop->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->HasBlockScopedContent()))
  3712. {
  3713. // we can not invert loops if there are block scoped declarations inside
  3714. return false;
  3715. }
  3716. if ((block != nullptr) && (block->nop == knopBlock))
  3717. {
  3718. ParseNode* stmt = block->AsParseNodeBlock()->pnodeStmt;
  3719. while ((stmt != nullptr) && (stmt->nop == knopList))
  3720. {
  3721. if (!GatherInversionSyms(stmt->AsParseNodeBin()->pnode1, outerVar, innerLoop, byteCodeGenerator, symCheck))
  3722. {
  3723. return false;
  3724. }
  3725. stmt = stmt->AsParseNodeBin()->pnode2;
  3726. }
  3727. if (!GatherInversionSyms(stmt, outerVar, innerLoop, byteCodeGenerator, symCheck))
  3728. {
  3729. return false;
  3730. }
  3731. stmt = block->AsParseNodeBlock()->pnodeStmt;
  3732. while ((stmt != nullptr) && (stmt->nop == knopList))
  3733. {
  3734. if (!InvertableStmt(stmt->AsParseNodeBin()->pnode1, outerVar, innerLoop, outerLoop, byteCodeGenerator, symCheck))
  3735. {
  3736. return false;
  3737. }
  3738. stmt = stmt->AsParseNodeBin()->pnode2;
  3739. }
  3740. if (!InvertableStmt(stmt, outerVar, innerLoop, outerLoop, byteCodeGenerator, symCheck))
  3741. {
  3742. return false;
  3743. }
  3744. return (InvertableExprPlus(symCheck, innerLoop->AsParseNodeFor()->pnodeCond, byteCodeGenerator, nullptr) &&
  3745. InvertableExprPlus(symCheck, outerLoop->AsParseNodeFor()->pnodeCond, byteCodeGenerator, outerVar));
  3746. }
  3747. else
  3748. {
  3749. return false;
  3750. }
  3751. }
  3752. // Start of invert loop optimization.
  3753. // For now, find simple cases (only for loops around single assignment).
  3754. // Returns new AST for inverted loop; also returns in out param
  3755. // side effects level, if any that guards the new AST (old AST will be
  3756. // used if guard fails).
  3757. // Should only be called with loopNode representing top-level statement.
  3758. ParseNodeFor* InvertLoop(ParseNode* outerLoop, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  3759. {
  3760. if (byteCodeGenerator->GetScriptContext()->optimizationOverrides.GetSideEffects() != Js::SideEffects_None)
  3761. {
  3762. return nullptr;
  3763. }
  3764. SymCheck symCheck;
  3765. symCheck.Init();
  3766. if (outerLoop->nop == knopFor)
  3767. {
  3768. ParseNode* innerLoop = outerLoop->AsParseNodeFor()->pnodeBody;
  3769. if ((innerLoop == nullptr) || (innerLoop->nop != knopBlock))
  3770. {
  3771. return nullptr;
  3772. }
  3773. else
  3774. {
  3775. innerLoop = innerLoop->AsParseNodeBlock()->pnodeStmt;
  3776. }
  3777. if ((innerLoop != nullptr) && (innerLoop->nop == knopFor))
  3778. {
  3779. if ((outerLoop->AsParseNodeFor()->pnodeInit != nullptr) &&
  3780. (outerLoop->AsParseNodeFor()->pnodeInit->nop == knopVarDecl) &&
  3781. (outerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pnodeInit != nullptr) &&
  3782. (outerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pnodeInit->nop == knopInt) &&
  3783. (outerLoop->AsParseNodeFor()->pnodeIncr != nullptr) &&
  3784. ((outerLoop->AsParseNodeFor()->pnodeIncr->nop == knopIncPre) || (outerLoop->AsParseNodeFor()->pnodeIncr->nop == knopIncPost)) &&
  3785. (outerLoop->AsParseNodeFor()->pnodeIncr->AsParseNodeUni()->pnode1->nop == knopName) &&
  3786. (outerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pid == outerLoop->AsParseNodeFor()->pnodeIncr->AsParseNodeUni()->pnode1->AsParseNodeName()->pid) &&
  3787. (innerLoop->AsParseNodeFor()->pnodeIncr != nullptr) &&
  3788. ((innerLoop->AsParseNodeFor()->pnodeIncr->nop == knopIncPre) || (innerLoop->AsParseNodeFor()->pnodeIncr->nop == knopIncPost)) &&
  3789. (innerLoop->AsParseNodeFor()->pnodeInit != nullptr) &&
  3790. (innerLoop->AsParseNodeFor()->pnodeInit->nop == knopVarDecl) &&
  3791. (innerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pnodeInit != nullptr) &&
  3792. (innerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pnodeInit->nop == knopInt) &&
  3793. (innerLoop->AsParseNodeFor()->pnodeIncr->AsParseNodeUni()->pnode1->nop == knopName) &&
  3794. (innerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->pid == innerLoop->AsParseNodeFor()->pnodeIncr->AsParseNodeUni()->pnode1->AsParseNodeName()->pid))
  3795. {
  3796. Symbol* outerVar = outerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->sym;
  3797. Symbol* innerVar = innerLoop->AsParseNodeFor()->pnodeInit->AsParseNodeVar()->sym;
  3798. if ((outerVar != nullptr) && (innerVar != nullptr))
  3799. {
  3800. ParseNode* block = innerLoop->AsParseNodeFor()->pnodeBody;
  3801. if (InvertableBlock(block, outerVar, innerLoop, outerLoop, byteCodeGenerator, &symCheck))
  3802. {
  3803. return ConstructInvertedLoop(innerLoop, outerLoop, byteCodeGenerator, funcInfo);
  3804. }
  3805. }
  3806. }
  3807. }
  3808. }
  3809. return nullptr;
  3810. }
  3811. void SetAdditionalBindInfoForVariables(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3812. {
  3813. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3814. if (sym == nullptr)
  3815. {
  3816. return;
  3817. }
  3818. FuncInfo* func = byteCodeGenerator->TopFuncInfo();
  3819. if (!sym->GetIsGlobal() && !sym->IsArguments() &&
  3820. (sym->GetScope() == func->GetBodyScope() || sym->GetScope() == func->GetParamScope() || sym->GetScope()->GetCanMerge()))
  3821. {
  3822. if (func->GetChildCallsEval())
  3823. {
  3824. func->SetHasLocalInClosure(true);
  3825. }
  3826. else
  3827. {
  3828. sym->RecordDef();
  3829. }
  3830. }
  3831. if (sym->IsUsedInLdElem())
  3832. {
  3833. Ident::TrySetIsUsedInLdElem(pnode->AsParseNodeVar()->pnodeInit);
  3834. }
  3835. // If this decl does an assignment inside a loop body, then there's a chance
  3836. // that a jitted loop body will expect us to begin with a valid value in this var.
  3837. // So mark the sym as used so that we guarantee the var will at least get "undefined".
  3838. if (byteCodeGenerator->IsInLoop() &&
  3839. pnode->AsParseNodeVar()->pnodeInit)
  3840. {
  3841. sym->SetIsUsed(true);
  3842. }
  3843. }
  3844. // bind references to definitions (prefix pass)
  3845. void Bind(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  3846. {
  3847. if (pnode == nullptr)
  3848. {
  3849. return;
  3850. }
  3851. switch (pnode->nop)
  3852. {
  3853. case knopBreak:
  3854. case knopContinue:
  3855. byteCodeGenerator->AddTargetStmt(pnode->AsParseNodeJump()->pnodeTarget);
  3856. break;
  3857. case knopProg:
  3858. {
  3859. FuncInfo* globFuncInfo = byteCodeGenerator->StartBindGlobalStatements(pnode->AsParseNodeProg());
  3860. pnode->AsParseNodeFnc()->funcInfo = globFuncInfo;
  3861. AddFunctionsToScope(pnode->AsParseNodeFnc()->GetTopLevelScope(), byteCodeGenerator);
  3862. AddVarsToScope(pnode->AsParseNodeFnc()->pnodeVars, byteCodeGenerator);
  3863. // There are no args to add, but "eval" gets a this pointer.
  3864. byteCodeGenerator->SetNumberOfInArgs(!!(byteCodeGenerator->GetFlags() & fscrEvalCode));
  3865. if (!globFuncInfo->IsFakeGlobalFunction(byteCodeGenerator->GetFlags()))
  3866. {
  3867. // Global code: the root function is the global function.
  3868. byteCodeGenerator->SetRootFuncInfo(globFuncInfo);
  3869. }
  3870. else if (globFuncInfo->byteCodeFunction)
  3871. {
  3872. // If the current global code wasn't marked to be treated as global code (e.g. from deferred parsing),
  3873. // we don't need to send a register script event for it.
  3874. globFuncInfo->byteCodeFunction->SetIsTopLevel(false);
  3875. }
  3876. if (pnode->AsParseNodeFnc()->CallsEval())
  3877. {
  3878. globFuncInfo->SetCallsEval(true);
  3879. }
  3880. break;
  3881. }
  3882. case knopFncDecl:
  3883. if (pnode->AsParseNodeFnc()->IsCoroutine())
  3884. {
  3885. // Always assume generator functions escape since tracking them requires tracking
  3886. // the resulting generators in addition to the function.
  3887. byteCodeGenerator->FuncEscapes(byteCodeGenerator->TopFuncInfo()->GetBodyScope());
  3888. }
  3889. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  3890. {
  3891. FuncInfo *funcInfo = byteCodeGenerator->TopFuncInfo();
  3892. if (!funcInfo->IsGlobalFunction() || (byteCodeGenerator->GetFlags() & fscrEval))
  3893. {
  3894. // In the case of a nested function expression, assumes that it escapes.
  3895. // We could try to analyze what it touches to be more precise.
  3896. byteCodeGenerator->FuncEscapes(funcInfo->GetBodyScope());
  3897. }
  3898. byteCodeGenerator->ProcessCapturedSyms(pnode);
  3899. }
  3900. else if (byteCodeGenerator->IsInLoop())
  3901. {
  3902. Symbol *funcSym = pnode->AsParseNodeFnc()->GetFuncSymbol();
  3903. if (funcSym)
  3904. {
  3905. Symbol *funcVarSym = funcSym->GetFuncScopeVarSym();
  3906. if (funcVarSym)
  3907. {
  3908. // We're going to write to the funcVarSym when we do the function instantiation,
  3909. // so treat the funcVarSym as used. That way, we know it will get undef-initialized at the
  3910. // top of the function, so a jitted loop body won't have any issue with boxing if
  3911. // the function instantiation isn't executed.
  3912. Assert(funcVarSym != funcSym);
  3913. funcVarSym->SetIsUsed(true);
  3914. }
  3915. }
  3916. }
  3917. break;
  3918. case knopName:
  3919. {
  3920. ParseNodeName * pnodeName = pnode->AsParseNodeName();
  3921. if (pnodeName->sym == nullptr)
  3922. {
  3923. if (pnodeName->grfpn & fpnMemberReference)
  3924. {
  3925. // This is a member name. No binding.
  3926. break;
  3927. }
  3928. Symbol *sym = byteCodeGenerator->FindSymbol(pnodeName->GetSymRef(), pnodeName->pid);
  3929. if (sym)
  3930. {
  3931. // This is a named load, not just a reference, so if it's a nested function note that all
  3932. // the nested scopes escape.
  3933. Assert(!sym->GetDecl() || (pnodeName->GetSymRef() && *pnodeName->GetSymRef()));
  3934. Assert(!sym->GetDecl() || ((*pnodeName->GetSymRef())->GetDecl() == sym->GetDecl()) ||
  3935. ((*pnodeName->GetSymRef())->GetFuncScopeVarSym() == sym));
  3936. pnodeName->sym = sym;
  3937. if (sym->GetSymbolType() == STFunction &&
  3938. (!sym->GetIsGlobal() || (byteCodeGenerator->GetFlags() & fscrEval)))
  3939. {
  3940. byteCodeGenerator->FuncEscapes(sym->GetScope());
  3941. }
  3942. }
  3943. }
  3944. if (pnodeName->sym)
  3945. {
  3946. pnodeName->sym->SetIsUsed(true);
  3947. }
  3948. break;
  3949. }
  3950. case knopMember:
  3951. case knopMemberShort:
  3952. case knopObjectPatternMember:
  3953. case knopGetMember:
  3954. case knopSetMember:
  3955. {
  3956. // lhs is knopStr, rhs is expr
  3957. ParseNode *id = pnode->AsParseNodeBin()->pnode1;
  3958. if (id->nop == knopStr)
  3959. {
  3960. byteCodeGenerator->AssignPropertyId(id->AsParseNodeStr()->pid);
  3961. id->grfpn |= fpnMemberReference;
  3962. }
  3963. break;
  3964. }
  3965. // TODO: convert index over string to Get/Put Value
  3966. case knopIndex:
  3967. BindReference(pnode, byteCodeGenerator);
  3968. break;
  3969. case knopDot:
  3970. BindInstAndMember(pnode, byteCodeGenerator);
  3971. break;
  3972. case knopTryFinally:
  3973. byteCodeGenerator->SetHasFinally(true);
  3974. case knopTryCatch:
  3975. byteCodeGenerator->SetHasTry(true);
  3976. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  3977. byteCodeGenerator->AddTargetStmt(pnode->AsParseNodeStmt());
  3978. break;
  3979. case knopAsg:
  3980. BindReference(pnode, byteCodeGenerator);
  3981. CheckLocalVarDef(pnode, byteCodeGenerator);
  3982. break;
  3983. case knopVarDecl:
  3984. // "arguments" symbol or decl w/o RHS may have been bound already; otherwise, do the binding here.
  3985. if (pnode->AsParseNodeVar()->sym == nullptr)
  3986. {
  3987. pnode->AsParseNodeVar()->sym = byteCodeGenerator->FindSymbol(pnode->AsParseNodeVar()->symRef, pnode->AsParseNodeVar()->pid);
  3988. }
  3989. SetAdditionalBindInfoForVariables(pnode, byteCodeGenerator);
  3990. break;
  3991. case knopConstDecl:
  3992. case knopLetDecl:
  3993. // "arguments" symbol or decl w/o RHS may have been bound already; otherwise, do the binding here.
  3994. if (!pnode->AsParseNodeVar()->sym)
  3995. {
  3996. AssertMsg(pnode->AsParseNodeVar()->symRef && *pnode->AsParseNodeVar()->symRef, "'const' and 'let' should be binded when we bind block");
  3997. pnode->AsParseNodeVar()->sym = *pnode->AsParseNodeVar()->symRef;
  3998. }
  3999. SetAdditionalBindInfoForVariables(pnode, byteCodeGenerator);
  4000. break;
  4001. case knopCall:
  4002. case knopTypeof:
  4003. case knopDelete:
  4004. BindReference(pnode, byteCodeGenerator);
  4005. break;
  4006. case knopRegExp:
  4007. pnode->AsParseNodeRegExp()->regexPatternIndex = byteCodeGenerator->TopFuncInfo()->GetParsedFunctionBody()->NewLiteralRegex();
  4008. break;
  4009. case knopComma:
  4010. pnode->AsParseNodeBin()->pnode1->SetNotEscapedUse();
  4011. break;
  4012. case knopBlock:
  4013. {
  4014. for (ParseNode *pnodeScope = pnode->AsParseNodeBlock()->pnodeScopes; pnodeScope; /* no increment */)
  4015. {
  4016. switch (pnodeScope->nop)
  4017. {
  4018. case knopFncDecl:
  4019. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  4020. {
  4021. byteCodeGenerator->ProcessCapturedSyms(pnodeScope);
  4022. }
  4023. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  4024. break;
  4025. case knopBlock:
  4026. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  4027. break;
  4028. case knopCatch:
  4029. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  4030. break;
  4031. case knopWith:
  4032. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  4033. break;
  4034. }
  4035. }
  4036. break;
  4037. }
  4038. }
  4039. }
  4040. void ByteCodeGenerator::ProcessCapturedSyms(ParseNode *pnode)
  4041. {
  4042. SymbolTable *capturedSyms = pnode->AsParseNodeFnc()->funcInfo->GetCapturedSyms();
  4043. if (capturedSyms)
  4044. {
  4045. FuncInfo *funcInfo = this->TopFuncInfo();
  4046. CapturedSymMap *capturedSymMap = funcInfo->EnsureCapturedSymMap();
  4047. ParseNode *pnodeStmt = this->GetCurrentTopStatement();
  4048. SList<Symbol*> *capturedSymList;
  4049. if (!pnodeStmt->CapturesSyms())
  4050. {
  4051. capturedSymList = Anew(this->alloc, SList<Symbol*>, this->alloc);
  4052. capturedSymMap->Add(pnodeStmt, capturedSymList);
  4053. pnodeStmt->SetCapturesSyms();
  4054. }
  4055. else
  4056. {
  4057. capturedSymList = capturedSymMap->Item(pnodeStmt);
  4058. }
  4059. capturedSyms->Map([&](Symbol *sym)
  4060. {
  4061. if (!sym->GetIsCommittedToSlot() && !sym->HasVisitedCapturingFunc())
  4062. {
  4063. capturedSymList->Prepend(sym);
  4064. sym->SetHasVisitedCapturingFunc();
  4065. }
  4066. });
  4067. }
  4068. }
  4069. void ByteCodeGenerator::FuncEscapes(Scope *scope)
  4070. {
  4071. while (scope)
  4072. {
  4073. Assert(scope->GetFunc());
  4074. scope->GetFunc()->SetEscapes(true);
  4075. scope = scope->GetEnclosingScope();
  4076. }
  4077. if (this->flags & fscrEval)
  4078. {
  4079. // If a function declared inside eval escapes, we'll need
  4080. // to invalidate the caller's cached scope.
  4081. this->funcEscapes = true;
  4082. }
  4083. }
  4084. bool ByteCodeGenerator::HasInterleavingDynamicScope(Symbol * sym) const
  4085. {
  4086. Js::PropertyId unused;
  4087. return this->InDynamicScope() &&
  4088. sym->GetScope() != this->FindScopeForSym(sym->GetScope(), nullptr, &unused, this->TopFuncInfo());
  4089. }
  4090. void CheckMaybeEscapedUse(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, bool isCall = false)
  4091. {
  4092. if (pnode == nullptr)
  4093. {
  4094. return;
  4095. }
  4096. FuncInfo * topFunc = byteCodeGenerator->TopFuncInfo();
  4097. if (topFunc->IsGlobalFunction())
  4098. {
  4099. return;
  4100. }
  4101. switch (pnode->nop)
  4102. {
  4103. case knopAsg:
  4104. if (pnode->AsParseNodeBin()->pnode1->nop != knopName)
  4105. {
  4106. break;
  4107. }
  4108. // use of an assignment (e.g. (y = function() {}) + "1"), just make y an escaped use.
  4109. pnode = pnode->AsParseNodeBin()->pnode1;
  4110. isCall = false;
  4111. // fall-through
  4112. case knopName:
  4113. if (!isCall)
  4114. {
  4115. // Mark the name has having escaped use
  4116. if (pnode->AsParseNodeName()->sym)
  4117. {
  4118. pnode->AsParseNodeName()->sym->SetHasMaybeEscapedUse(byteCodeGenerator);
  4119. }
  4120. }
  4121. break;
  4122. case knopFncDecl:
  4123. // A function declaration has an unknown use (not assignment nor call),
  4124. // mark the function as having child escaped
  4125. topFunc->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("UnknownUse")));
  4126. break;
  4127. }
  4128. }
  4129. void CheckFuncAssignment(Symbol * sym, ParseNode * pnode2, ByteCodeGenerator * byteCodeGenerator)
  4130. {
  4131. if (pnode2 == nullptr)
  4132. {
  4133. return;
  4134. }
  4135. switch (pnode2->nop)
  4136. {
  4137. default:
  4138. CheckMaybeEscapedUse(pnode2, byteCodeGenerator);
  4139. break;
  4140. case knopFncDecl:
  4141. {
  4142. FuncInfo * topFunc = byteCodeGenerator->TopFuncInfo();
  4143. if (topFunc->IsGlobalFunction())
  4144. {
  4145. return;
  4146. }
  4147. // Use not as an assignment or assignment to an outer function's sym, or assigned to a formal
  4148. // or assigned to multiple names.
  4149. if (sym == nullptr
  4150. || sym->GetScope()->GetFunc() != topFunc)
  4151. {
  4152. topFunc->SetHasMaybeEscapedNestedFunc(DebugOnly(
  4153. sym == nullptr ? _u("UnknownAssignment") :
  4154. (sym->GetScope()->GetFunc() != topFunc) ? _u("CrossFuncAssignment") :
  4155. _u("SomethingIsWrong!"))
  4156. );
  4157. }
  4158. else
  4159. {
  4160. // TODO-STACK-NESTED-FUNC: Since we only support single def functions, we can still put the
  4161. // nested function on the stack and reuse even if the function goes out of the block scope.
  4162. // However, we cannot allocate frame display or slots on the stack if the function is
  4163. // declared in a loop, because there might be multiple functions referencing different
  4164. // iterations of the scope.
  4165. // For now, just disable everything.
  4166. Scope * funcParentScope = pnode2->AsParseNodeFnc()->funcInfo->GetBodyScope()->GetEnclosingScope();
  4167. while (sym->GetScope() != funcParentScope)
  4168. {
  4169. if (funcParentScope->GetMustInstantiate())
  4170. {
  4171. topFunc->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("CrossScopeAssignment")));
  4172. break;
  4173. }
  4174. funcParentScope->SetHasCrossScopeFuncAssignment();
  4175. funcParentScope = funcParentScope->GetEnclosingScope();
  4176. }
  4177. // Need to always detect interleaving dynamic scope ('with') for assignments
  4178. // as those may end up escaping into the 'with' scope.
  4179. // TODO: the with scope is marked as MustInstantiate late during byte code emit
  4180. // We could detect this using the loop above as well, by marking the with
  4181. // scope as must instantiate early, this is just less risky of a fix for RTM.
  4182. if (byteCodeGenerator->HasInterleavingDynamicScope(sym))
  4183. {
  4184. byteCodeGenerator->TopFuncInfo()->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("InterleavingDynamicScope")));
  4185. }
  4186. sym->SetHasFuncAssignment(byteCodeGenerator);
  4187. }
  4188. }
  4189. break;
  4190. };
  4191. }
  4192. // Assign permanent (non-temp) registers for the function.
  4193. // These include constants (null, 3.7, this) and locals that use registers as their home locations.
  4194. // Assign the location fields of parse nodes whose values are constants/locals with permanent/known registers.
  4195. // Re-usable expression temps are assigned during the final Emit pass.
  4196. void AssignRegisters(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator)
  4197. {
  4198. if (pnode == nullptr)
  4199. {
  4200. return;
  4201. }
  4202. Symbol *sym;
  4203. OpCode nop = pnode->nop;
  4204. switch (nop)
  4205. {
  4206. default:
  4207. {
  4208. uint flags = ParseNode::Grfnop(nop);
  4209. if (flags & fnopUni)
  4210. {
  4211. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4212. }
  4213. else if (flags & fnopBin)
  4214. {
  4215. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator);
  4216. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator);
  4217. }
  4218. break;
  4219. }
  4220. case knopParamPattern:
  4221. byteCodeGenerator->AssignUndefinedConstRegister();
  4222. CheckMaybeEscapedUse(pnode->AsParseNodeParamPattern()->pnode1, byteCodeGenerator);
  4223. break;
  4224. case knopObjectPattern:
  4225. case knopArrayPattern:
  4226. byteCodeGenerator->AssignUndefinedConstRegister();
  4227. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4228. break;
  4229. case knopDot:
  4230. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator);
  4231. break;
  4232. case knopMember:
  4233. case knopMemberShort:
  4234. case knopGetMember:
  4235. case knopSetMember:
  4236. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator);
  4237. break;
  4238. case knopAsg:
  4239. {
  4240. Symbol * symName = pnode->AsParseNodeBin()->pnode1->nop == knopName ? pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->sym : nullptr;
  4241. CheckFuncAssignment(symName, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator);
  4242. if (pnode->IsInList())
  4243. {
  4244. // Assignment in array literal
  4245. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator);
  4246. }
  4247. if (byteCodeGenerator->IsES6DestructuringEnabled() && (pnode->AsParseNodeBin()->pnode1->nop == knopArrayPattern || pnode->AsParseNodeBin()->pnode1->nop == knopObjectPattern))
  4248. {
  4249. // Destructured arrays may have default values and need undefined.
  4250. byteCodeGenerator->AssignUndefinedConstRegister();
  4251. // Any rest parameter in a destructured array will need a 0 constant.
  4252. byteCodeGenerator->EnregisterConstant(0);
  4253. }
  4254. break;
  4255. }
  4256. case knopEllipsis:
  4257. if (byteCodeGenerator->InDestructuredPattern())
  4258. {
  4259. // Get a register for the rest array counter.
  4260. pnode->location = byteCodeGenerator->NextVarRegister();
  4261. // Any rest parameter in a destructured array will need a 0 constant.
  4262. byteCodeGenerator->EnregisterConstant(0);
  4263. }
  4264. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4265. break;
  4266. case knopQmark:
  4267. CheckMaybeEscapedUse(pnode->AsParseNodeTri()->pnode1, byteCodeGenerator);
  4268. CheckMaybeEscapedUse(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator);
  4269. CheckMaybeEscapedUse(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator);
  4270. break;
  4271. case knopWith:
  4272. pnode->location = byteCodeGenerator->NextVarRegister();
  4273. CheckMaybeEscapedUse(pnode->AsParseNodeWith()->pnodeObj, byteCodeGenerator);
  4274. break;
  4275. case knopComma:
  4276. if (!pnode->IsNotEscapedUse())
  4277. {
  4278. // Only the last expr in comma expr escape. Mark it if it is escapable.
  4279. CheckMaybeEscapedUse(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator);
  4280. }
  4281. break;
  4282. case knopFncDecl:
  4283. if (!byteCodeGenerator->TopFuncInfo()->IsGlobalFunction())
  4284. {
  4285. if (pnode->AsParseNodeFnc()->IsCoroutine())
  4286. {
  4287. // Assume generators always escape; otherwise need to analyze if
  4288. // the return value of calls to generator function, the generator
  4289. // objects, escape.
  4290. FuncInfo* funcInfo = byteCodeGenerator->TopFuncInfo();
  4291. funcInfo->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("Generator")));
  4292. }
  4293. if (pnode->IsInList() && !pnode->IsNotEscapedUse())
  4294. {
  4295. byteCodeGenerator->TopFuncInfo()->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("InList")));
  4296. }
  4297. ParseNodePtr pnodeName = pnode->AsParseNodeFnc()->pnodeName;
  4298. if (pnodeName != nullptr)
  4299. {
  4300. // REVIEW: does this apply now that compat mode is gone?
  4301. // There is a weird case in compat mode where we may not have a sym assigned to a fnc decl's
  4302. // name node if it is a named function declare inside 'with' that also assigned to something else
  4303. // as well. Instead, We generate two knopFncDecl node one for parent function and one for the assignment.
  4304. // Only the top one gets a sym, not the inner one. The assignment in the 'with' will be using the inner
  4305. // one. Also we will detect that the assignment to a variable is an escape inside a 'with'.
  4306. // Since we need the sym in the fnc decl's name, we just detect the escape here as "WithScopeFuncName".
  4307. if (pnodeName->nop == knopVarDecl && pnodeName->AsParseNodeVar()->sym != nullptr)
  4308. {
  4309. // Unlike in CheckFuncAssignment, we don't check for interleaving
  4310. // dynamic scope ('with') here, because we also generate direct assignment for
  4311. // function decl's names
  4312. pnodeName->AsParseNodeVar()->sym->SetHasFuncAssignment(byteCodeGenerator);
  4313. // Function declaration in block scope and non-strict mode has a
  4314. // corresponding var sym that we assign to as well. Need to
  4315. // mark that symbol as has func assignment as well.
  4316. Symbol * functionScopeVarSym = pnodeName->AsParseNodeVar()->sym->GetFuncScopeVarSym();
  4317. if (functionScopeVarSym)
  4318. {
  4319. functionScopeVarSym->SetHasFuncAssignment(byteCodeGenerator);
  4320. }
  4321. }
  4322. else
  4323. {
  4324. // The function has multiple names, or assign to o.x or o::x
  4325. byteCodeGenerator->TopFuncInfo()->SetHasMaybeEscapedNestedFunc(DebugOnly(
  4326. pnodeName->nop == knopList ? _u("MultipleFuncName") :
  4327. pnodeName->nop == knopDot ? _u("PropFuncName") :
  4328. pnodeName->nop == knopVarDecl && pnodeName->AsParseNodeVar()->sym == nullptr ? _u("WithScopeFuncName") :
  4329. _u("WeirdFuncName")
  4330. ));
  4331. }
  4332. }
  4333. }
  4334. break;
  4335. case knopNew:
  4336. CheckMaybeEscapedUse(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator);
  4337. CheckMaybeEscapedUse(pnode->AsParseNodeCall()->pnodeArgs, byteCodeGenerator);
  4338. break;
  4339. case knopThrow:
  4340. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4341. break;
  4342. // REVIEW: Technically, switch expr or case expr doesn't really escape as strict equal
  4343. // doesn't cause the function to escape.
  4344. case knopSwitch:
  4345. CheckMaybeEscapedUse(pnode->AsParseNodeSwitch()->pnodeVal, byteCodeGenerator);
  4346. break;
  4347. case knopCase:
  4348. CheckMaybeEscapedUse(pnode->AsParseNodeCase()->pnodeExpr, byteCodeGenerator);
  4349. break;
  4350. // REVIEW: Technically, the object for GetForInEnumerator doesn't escape, except when cached,
  4351. // which we can make work.
  4352. case knopForIn:
  4353. CheckMaybeEscapedUse(pnode->AsParseNodeForInOrForOf()->pnodeObj, byteCodeGenerator);
  4354. break;
  4355. case knopForOf:
  4356. case knopForAwaitOf:
  4357. byteCodeGenerator->AssignNullConstRegister();
  4358. byteCodeGenerator->AssignUndefinedConstRegister();
  4359. CheckMaybeEscapedUse(pnode->AsParseNodeForInOrForOf()->pnodeObj, byteCodeGenerator);
  4360. break;
  4361. case knopTrue:
  4362. pnode->location = byteCodeGenerator->AssignTrueConstRegister();
  4363. break;
  4364. case knopFalse:
  4365. pnode->location = byteCodeGenerator->AssignFalseConstRegister();
  4366. break;
  4367. case knopDecPost:
  4368. case knopIncPost:
  4369. case knopDecPre:
  4370. case knopIncPre:
  4371. byteCodeGenerator->EnregisterConstant(1);
  4372. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4373. break;
  4374. case knopObject:
  4375. byteCodeGenerator->AssignNullConstRegister();
  4376. break;
  4377. case knopClassDecl:
  4378. {
  4379. FuncInfo * topFunc = byteCodeGenerator->TopFuncInfo();
  4380. topFunc->SetHasMaybeEscapedNestedFunc(DebugOnly(_u("Class")));
  4381. // We may need undefined for the 'this', e.g. calling a class expression
  4382. byteCodeGenerator->AssignUndefinedConstRegister();
  4383. break;
  4384. }
  4385. case knopNull:
  4386. pnode->location = byteCodeGenerator->AssignNullConstRegister();
  4387. break;
  4388. case knopCall:
  4389. {
  4390. if (pnode->AsParseNodeCall()->pnodeTarget->nop != knopIndex &&
  4391. pnode->AsParseNodeCall()->pnodeTarget->nop != knopDot)
  4392. {
  4393. byteCodeGenerator->AssignUndefinedConstRegister();
  4394. }
  4395. FuncInfo *funcInfo = byteCodeGenerator->TopFuncInfo();
  4396. if (pnode->AsParseNodeCall()->isEvalCall)
  4397. {
  4398. if (!funcInfo->GetParsedFunctionBody()->IsReparsed())
  4399. {
  4400. Assert(funcInfo->IsGlobalFunction() || funcInfo->GetCallsEval());
  4401. funcInfo->SetCallsEval(true);
  4402. funcInfo->GetParsedFunctionBody()->SetCallsEval(true);
  4403. }
  4404. else
  4405. {
  4406. // On reparsing, load the state from function Body, instead of using the state on the parse node,
  4407. // as they might be different.
  4408. pnode->AsParseNodeCall()->isEvalCall = funcInfo->GetParsedFunctionBody()->GetCallsEval();
  4409. }
  4410. }
  4411. // Don't need to check pnode->AsParseNodeCall()->pnodeTarget even if it is a knopFncDecl,
  4412. // e.g. (function(){})();
  4413. // It is only used as a call, so don't count as an escape.
  4414. // Although not assigned to a slot, we will still able to box it by boxing
  4415. // all the stack function on the interpreter frame or the stack function link list
  4416. // on a jitted frame
  4417. break;
  4418. }
  4419. case knopInt:
  4420. pnode->location = byteCodeGenerator->EnregisterConstant(pnode->AsParseNodeInt()->lw);
  4421. break;
  4422. case knopFlt:
  4423. {
  4424. pnode->location = byteCodeGenerator->EnregisterDoubleConstant(pnode->AsParseNodeFloat()->dbl);
  4425. break;
  4426. }
  4427. case knopBigInt:
  4428. pnode->location = byteCodeGenerator->EnregisterBigIntConstant(pnode);
  4429. break;
  4430. case knopStr:
  4431. pnode->location = byteCodeGenerator->EnregisterStringConstant(pnode->AsParseNodeStr()->pid);
  4432. break;
  4433. case knopVarDecl:
  4434. case knopConstDecl:
  4435. case knopLetDecl:
  4436. {
  4437. sym = pnode->AsParseNodeVar()->sym;
  4438. Assert(sym != nullptr);
  4439. Assert(sym->GetScope()->GetEnclosingFunc() == byteCodeGenerator->TopFuncInfo());
  4440. if (pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar())
  4441. {
  4442. break;
  4443. }
  4444. if (!sym->GetIsGlobal())
  4445. {
  4446. FuncInfo *funcInfo = byteCodeGenerator->TopFuncInfo();
  4447. // Check the function assignment for the sym that we have, even if we remap it to function level sym below
  4448. // as we are going assign to the original sym
  4449. CheckFuncAssignment(sym, pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator);
  4450. // If this is a destructured param case then it is a let binding and we don't have to look for duplicate symbol in the body
  4451. if ((sym->GetIsCatch() && pnode->AsParseNodeVar()->sym->GetScope()->GetScopeType() != ScopeType_CatchParamPattern) || (pnode->nop == knopVarDecl && sym->GetIsBlockVar() && !pnode->AsParseNodeVar()->isBlockScopeFncDeclVar))
  4452. {
  4453. // The LHS of the var decl really binds to the local symbol, not the catch or let symbol.
  4454. // But the assignment will go to the catch or let symbol. Just assign a register to the local
  4455. // so that it can get initialized to undefined.
  4456. #if DBG
  4457. if (!sym->GetIsCatch())
  4458. {
  4459. // Catch cannot be at function scope and let and var at function scope is redeclaration error.
  4460. Assert(funcInfo->bodyScope != sym->GetScope());
  4461. }
  4462. #endif
  4463. auto symName = sym->GetName();
  4464. sym = funcInfo->bodyScope->FindLocalSymbol(symName);
  4465. if (sym == nullptr)
  4466. {
  4467. sym = funcInfo->paramScope->FindLocalSymbol(symName);
  4468. }
  4469. Assert((sym && !sym->GetIsCatch() && !sym->GetIsBlockVar()));
  4470. }
  4471. // Don't give the declared var a register if it's in a closure, because the closure slot
  4472. // is its true "home". (Need to check IsGlobal again as the sym may have changed above.)
  4473. if (!sym->GetIsGlobal() && !sym->IsInSlot(byteCodeGenerator, funcInfo))
  4474. {
  4475. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  4476. {
  4477. if (sym->NeedsSlotAlloc(byteCodeGenerator, byteCodeGenerator->TopFuncInfo()))
  4478. {
  4479. Output::Print(_u("--- DelayCapture: Delayed capturing symbol '%s' during initialization.\n"),
  4480. sym->GetName().GetBuffer());
  4481. Output::Flush();
  4482. }
  4483. }
  4484. byteCodeGenerator->AssignRegister(sym);
  4485. }
  4486. }
  4487. else
  4488. {
  4489. Assert(byteCodeGenerator->TopFuncInfo()->IsGlobalFunction());
  4490. }
  4491. break;
  4492. }
  4493. case knopFor:
  4494. if ((pnode->AsParseNodeFor()->pnodeBody != nullptr) && (pnode->AsParseNodeFor()->pnodeBody->nop == knopBlock) &&
  4495. (pnode->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->pnodeStmt != nullptr) &&
  4496. (pnode->AsParseNodeFor()->pnodeBody->AsParseNodeBlock()->pnodeStmt->nop == knopFor) &&
  4497. (!byteCodeGenerator->IsInDebugMode()))
  4498. {
  4499. FuncInfo *funcInfo = byteCodeGenerator->TopFuncInfo();
  4500. pnode->AsParseNodeFor()->pnodeInverted = InvertLoop(pnode, byteCodeGenerator, funcInfo);
  4501. }
  4502. else
  4503. {
  4504. pnode->AsParseNodeFor()->pnodeInverted = nullptr;
  4505. }
  4506. break;
  4507. case knopName:
  4508. sym = pnode->AsParseNodeName()->sym;
  4509. if (sym == nullptr)
  4510. {
  4511. Assert(pnode->AsParseNodeName()->pid->GetPropertyId() != Js::Constants::NoProperty);
  4512. // Referring to 'this' with no var decl needs to load 'this' root value via LdThis from null
  4513. if (ByteCodeGenerator::IsThis(pnode) && !byteCodeGenerator->TopFuncInfo()->GetThisSymbol() && !(byteCodeGenerator->GetFlags() & fscrEval))
  4514. {
  4515. byteCodeGenerator->AssignNullConstRegister();
  4516. byteCodeGenerator->AssignThisConstRegister();
  4517. }
  4518. }
  4519. else
  4520. {
  4521. // Note: don't give a register to a local if it's in a closure, because then the closure
  4522. // is its true home.
  4523. if (!sym->GetIsGlobal() &&
  4524. !sym->GetIsMember() &&
  4525. byteCodeGenerator->TopFuncInfo() == sym->GetScope()->GetEnclosingFunc() &&
  4526. !sym->IsInSlot(byteCodeGenerator, byteCodeGenerator->TopFuncInfo()) &&
  4527. !sym->HasVisitedCapturingFunc())
  4528. {
  4529. if (PHASE_TRACE(Js::DelayCapturePhase, byteCodeGenerator->TopFuncInfo()->byteCodeFunction))
  4530. {
  4531. if (sym->NeedsSlotAlloc(byteCodeGenerator, byteCodeGenerator->TopFuncInfo()))
  4532. {
  4533. Output::Print(_u("--- DelayCapture: Delayed capturing symbol '%s'.\n"),
  4534. sym->GetName().GetBuffer());
  4535. Output::Flush();
  4536. }
  4537. }
  4538. // Local symbol being accessed in its own frame. Even if "with" or event
  4539. // handler semantics make the binding ambiguous, it has a home location,
  4540. // so assign it.
  4541. byteCodeGenerator->AssignRegister(sym);
  4542. // If we're in something like a "with" we'll need a scratch register to hold
  4543. // the multiple possible values of the property.
  4544. if (!byteCodeGenerator->HasInterleavingDynamicScope(sym))
  4545. {
  4546. // We're not in a dynamic scope, or our home scope is nested within the dynamic scope, so we
  4547. // don't have to do dynamic binding. Just use the home location for this reference.
  4548. pnode->location = sym->GetLocation();
  4549. }
  4550. }
  4551. }
  4552. if (pnode->IsInList() && !pnode->IsNotEscapedUse())
  4553. {
  4554. // A node that is in a list is assumed to be escape, unless marked otherwise.
  4555. // This includes array literal list/object literal list
  4556. CheckMaybeEscapedUse(pnode, byteCodeGenerator);
  4557. }
  4558. break;
  4559. case knopProg:
  4560. if (!byteCodeGenerator->HasParentScopeInfo())
  4561. {
  4562. // If we're compiling a nested deferred function, don't pop the scope stack,
  4563. // because we just want to leave it as-is for the emit pass.
  4564. PostVisitFunction(pnode->AsParseNodeFnc(), byteCodeGenerator);
  4565. }
  4566. break;
  4567. case knopReturn:
  4568. {
  4569. ParseNode *pnodeExpr = pnode->AsParseNodeReturn()->pnodeExpr;
  4570. CheckMaybeEscapedUse(pnodeExpr, byteCodeGenerator);
  4571. break;
  4572. }
  4573. case knopStrTemplate:
  4574. {
  4575. ParseNode* pnodeExprs = pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions;
  4576. if (pnodeExprs != nullptr)
  4577. {
  4578. while (pnodeExprs->nop == knopList)
  4579. {
  4580. Assert(pnodeExprs->AsParseNodeBin()->pnode1 != nullptr);
  4581. Assert(pnodeExprs->AsParseNodeBin()->pnode2 != nullptr);
  4582. CheckMaybeEscapedUse(pnodeExprs->AsParseNodeBin()->pnode1, byteCodeGenerator);
  4583. pnodeExprs = pnodeExprs->AsParseNodeBin()->pnode2;
  4584. }
  4585. // Also check the final element in the list
  4586. CheckMaybeEscapedUse(pnodeExprs, byteCodeGenerator);
  4587. }
  4588. if (pnode->AsParseNodeStrTemplate()->isTaggedTemplate)
  4589. {
  4590. pnode->location = byteCodeGenerator->EnregisterStringTemplateCallsiteConstant(pnode);
  4591. }
  4592. break;
  4593. }
  4594. case knopExportDefault:
  4595. {
  4596. ParseNode* expr = pnode->AsParseNodeExportDefault()->pnodeExpr;
  4597. if (expr != nullptr)
  4598. {
  4599. CheckMaybeEscapedUse(expr, byteCodeGenerator);
  4600. }
  4601. break;
  4602. }
  4603. case knopYieldLeaf:
  4604. byteCodeGenerator->AssignUndefinedConstRegister();
  4605. break;
  4606. case knopYield:
  4607. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4608. break;
  4609. case knopYieldStar:
  4610. // Reserve a local for our YieldStar loop so that the backend doesn't complain
  4611. pnode->location = byteCodeGenerator->NextVarRegister();
  4612. byteCodeGenerator->AssignNullConstRegister();
  4613. byteCodeGenerator->AssignUndefinedConstRegister();
  4614. CheckMaybeEscapedUse(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator);
  4615. break;
  4616. }
  4617. }
  4618. // TODO[ianhall]: ApplyEnclosesArgs should be in ByteCodeEmitter.cpp but that becomes complicated because it depends on VisitIndirect
  4619. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck);
  4620. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck);
  4621. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator)
  4622. {
  4623. if (byteCodeGenerator->IsInDebugMode())
  4624. {
  4625. // Inspection of the arguments object will be messed up if we do ApplyArgs.
  4626. return false;
  4627. }
  4628. if (!fncDecl->HasVarArguments()
  4629. && fncDecl->AsParseNodeFnc()->pnodeParams == nullptr
  4630. && fncDecl->AsParseNodeFnc()->pnodeRest == nullptr
  4631. && fncDecl->AsParseNodeFnc()->nestedCount == 0)
  4632. {
  4633. ApplyCheck applyCheck;
  4634. applyCheck.matches = true;
  4635. applyCheck.sawApply = false;
  4636. applyCheck.insideApplyCall = false;
  4637. VisitIndirect<ApplyCheck>(fncDecl->AsParseNodeFnc()->pnodeBody, byteCodeGenerator, &applyCheck, &CheckApplyEnclosesArgs, &PostCheckApplyEnclosesArgs);
  4638. return applyCheck.matches&&applyCheck.sawApply;
  4639. }
  4640. return false;
  4641. }
  4642. // TODO[ianhall]: VisitClearTmpRegs should be in ByteCodeEmitter.cpp but that becomes complicated because it depends on VisitIndirect
  4643. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc);
  4644. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo)
  4645. {
  4646. VisitIndirect<FuncInfo>(pnode, byteCodeGenerator, funcInfo, &ClearTmpRegs, nullptr);
  4647. }
  4648. Js::FunctionBody * ByteCodeGenerator::MakeGlobalFunctionBody(ParseNode *pnode)
  4649. {
  4650. Js::FunctionBody * func;
  4651. func =
  4652. Js::FunctionBody::NewFromRecycler(
  4653. scriptContext,
  4654. Js::Constants::GlobalFunction,
  4655. Js::Constants::GlobalFunctionLength,
  4656. 0,
  4657. pnode->AsParseNodeFnc()->nestedCount,
  4658. m_utf8SourceInfo,
  4659. m_utf8SourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId,
  4660. pnode->AsParseNodeFnc()->functionId,
  4661. Js::FunctionInfo::Attributes::None,
  4662. Js::FunctionBody::FunctionBodyFlags::Flags_HasNoExplicitReturnValue
  4663. #ifdef PERF_COUNTERS
  4664. , false /* is function from deferred deserialized proxy */
  4665. #endif
  4666. );
  4667. func->SetIsGlobalFunc(true);
  4668. scriptContext->GetLibrary()->RegisterDynamicFunctionReference(func);
  4669. return func;
  4670. }
  4671. bool ByteCodeGenerator::NeedScopeObjectForArguments(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc) const
  4672. {
  4673. // We can avoid creating a scope object with arguments present if:
  4674. bool dontNeedScopeObject =
  4675. // We have arguments, and
  4676. funcInfo->GetHasHeapArguments()
  4677. // Either we are in strict mode, or have strict mode formal semantics from a non-simple parameter list, and
  4678. && (funcInfo->GetIsStrictMode()
  4679. || pnodeFnc->HasNonSimpleParameterList())
  4680. // We're not in eval or event handler, which will force the scope(s) to be objects
  4681. && !(this->flags & (fscrEval | fscrImplicitThis))
  4682. // Neither of the scopes are objects
  4683. && !funcInfo->paramScope->GetIsObject()
  4684. && !funcInfo->bodyScope->GetIsObject();
  4685. return funcInfo->GetHasHeapArguments()
  4686. // Regardless of the conditions above, we won't need a scope object if there aren't any formals.
  4687. && (pnodeFnc->pnodeParams != nullptr || pnodeFnc->pnodeRest != nullptr)
  4688. && !dontNeedScopeObject;
  4689. }
  4690. Js::FunctionBody *ByteCodeGenerator::EnsureFakeGlobalFuncForUndefer(ParseNode *pnode)
  4691. {
  4692. Js::FunctionBody *func = scriptContext->GetLibrary()->GetFakeGlobalFuncForUndefer();
  4693. if (!func)
  4694. {
  4695. func = this->MakeGlobalFunctionBody(pnode);
  4696. scriptContext->GetLibrary()->SetFakeGlobalFuncForUndefer(func);
  4697. }
  4698. if (pnode->AsParseNodeFnc()->GetStrictMode() != 0)
  4699. {
  4700. func->SetIsStrictMode();
  4701. }
  4702. return func;
  4703. }