ByteCodeGenerator.cpp 202 KB

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