ByteCodeGenerator.cpp 196 KB

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