FunctionBody.h 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. #include "AuxPtrs.h"
  7. #include "CompactCounters.h"
  8. // Where should I include this file?
  9. #include "FunctionExecutionStateMachine.h"
  10. struct CodeGenWorkItem;
  11. class SourceContextInfo;
  12. struct DeferredFunctionStub;
  13. struct CodeGenNumberChunk;
  14. #ifdef DYNAMIC_PROFILE_MUTATOR
  15. class DynamicProfileMutator;
  16. class DynamicProfileMutatorImpl;
  17. #endif
  18. #define MAX_FUNCTION_BODY_DEBUG_STRING_SIZE 42 //11*3+8+1
  19. typedef BVSparse<ArenaAllocator> ActiveFunctionSet;
  20. namespace Js
  21. {
  22. #pragma region Class Forward Declarations
  23. class ByteCodeBufferReader;
  24. class ByteCodeBufferBuilder;
  25. class ByteCodeCache;
  26. class ScopeInfo;
  27. class SmallSpanSequence;
  28. struct StatementLocation;
  29. class SmallSpanSequenceIter;
  30. struct StatementData;
  31. struct PropertyIdOnRegSlotsContainer;
  32. struct InlineCache;
  33. class PolymorphicInlineCache;
  34. struct IsInstInlineCache;
  35. class ScopeObjectChain;
  36. class EntryPointInfo;
  37. class FunctionProxy;
  38. class ParseableFunctionInfo;
  39. class FunctionBody;
  40. class DebuggerScopeProperty;
  41. class DebuggerScope;
  42. class FunctionEntryPointInfo;
  43. #ifdef ASMJS_PLAT
  44. class AsmJsFunctionInfo;
  45. class AmsJsModuleInfo;
  46. #endif
  47. class ArrayBuffer;
  48. class SharedArrayBuffer;
  49. class FunctionCodeGenRuntimeData;
  50. class JavascriptNumber;
  51. #pragma endregion
  52. typedef JsUtil::BaseDictionary<Js::PropertyId, const Js::PropertyRecord*, RecyclerNonLeafAllocator, PowerOf2SizePolicy, DefaultComparer, JsUtil::SimpleDictionaryEntry> PropertyRecordList;
  53. typedef JsUtil::BaseHashSet<void*, Recycler, PowerOf2SizePolicy> TypeRefSet;
  54. // Definition of scopes such as With, Catch and Block which will be used further in the debugger for additional look-ups.
  55. enum DiagExtraScopesType
  56. {
  57. DiagUnknownScope, // Unknown scope set when deserializing bytecode and the scope is not yet known.
  58. DiagWithScope, // With scope.
  59. DiagCatchScopeDirect, // Catch scope in regslot
  60. DiagCatchScopeInSlot, // Catch scope in slot array
  61. DiagCatchScopeInObject, // Catch scope in scope object
  62. DiagBlockScopeDirect, // Block scope in regslot
  63. DiagBlockScopeInSlot, // Block scope in slot array
  64. DiagBlockScopeInObject, // Block scope in activation object
  65. DiagBlockScopeRangeEnd, // Used to end a block scope range.
  66. DiagParamScope, // The scope represents symbols at formals
  67. DiagParamScopeInObject, // The scope represents symbols at formals and formal scope in activation object
  68. };
  69. struct ForInCache
  70. {
  71. Type * type;
  72. void * data;
  73. };
  74. #pragma region Inline Cache Info class declarations
  75. class PolymorphicCacheUtilizationArray
  76. {
  77. private:
  78. Field(byte *) utilArray;
  79. public:
  80. PolymorphicCacheUtilizationArray()
  81. : utilArray(nullptr)
  82. {
  83. }
  84. void EnsureUtilArray(Recycler * const recycler, Js::FunctionBody * functionBody);
  85. byte* GetByteArray() { return utilArray; }
  86. void SetUtil(Js::FunctionBody* functionBody, uint index, byte util);
  87. byte GetUtil(Js::FunctionBody* functionBody, uint index);
  88. };
  89. class PolymorphicInlineCacheInfo sealed
  90. {
  91. private:
  92. Field(InlineCachePointerArray<PolymorphicInlineCache>) polymorphicInlineCaches;
  93. Field(PolymorphicCacheUtilizationArray) polymorphicCacheUtilizationArray;
  94. Field(FunctionBody *) functionBody;
  95. public:
  96. PolymorphicInlineCacheInfo(FunctionBody * functionBody)
  97. : functionBody(functionBody)
  98. {
  99. }
  100. InlineCachePointerArray<PolymorphicInlineCache> * GetPolymorphicInlineCaches() { return &polymorphicInlineCaches; }
  101. PolymorphicCacheUtilizationArray * GetUtilArray() { return &polymorphicCacheUtilizationArray; }
  102. byte * GetUtilByteArray() { return polymorphicCacheUtilizationArray.GetByteArray(); }
  103. FunctionBody * GetFunctionBody() const { return functionBody; }
  104. };
  105. class EntryPointPolymorphicInlineCacheInfo sealed
  106. {
  107. private:
  108. Field(PolymorphicInlineCacheInfo) selfInfo;
  109. typedef SListCounted<PolymorphicInlineCacheInfo*, Recycler> PolymorphicInlineCacheInfoListType;
  110. Field(PolymorphicInlineCacheInfoListType) inlineeInfo;
  111. static void SetPolymorphicInlineCache(PolymorphicInlineCacheInfo * polymorphicInlineCacheInfo, FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, byte polyCacheUtil);
  112. public:
  113. EntryPointPolymorphicInlineCacheInfo(FunctionBody * functionBody);
  114. PolymorphicInlineCacheInfo * GetSelfInfo() { return &selfInfo; }
  115. PolymorphicInlineCacheInfo * EnsureInlineeInfo(Recycler * recycler, FunctionBody * inlineeFunctionBody);
  116. PolymorphicInlineCacheInfo * GetInlineeInfo(FunctionBody * inlineeFunctionBody);
  117. SListCounted<PolymorphicInlineCacheInfo*, Recycler> * GetInlineeInfo() { return &this->inlineeInfo; }
  118. void SetPolymorphicInlineCache(FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, bool isInlinee, byte polyCacheUtil);
  119. template <class Fn>
  120. void MapInlinees(Fn fn)
  121. {
  122. SListCounted<PolymorphicInlineCacheInfo*, Recycler>::Iterator iter(&inlineeInfo);
  123. while (iter.Next())
  124. {
  125. fn(iter.Data());
  126. }
  127. }
  128. };
  129. #pragma endregion
  130. #ifdef FIELD_ACCESS_STATS
  131. struct FieldAccessStats
  132. {
  133. Field(uint) totalInlineCacheCount;
  134. Field(uint) noInfoInlineCacheCount;
  135. Field(uint) monoInlineCacheCount;
  136. Field(uint) emptyMonoInlineCacheCount;
  137. Field(uint) polyInlineCacheCount;
  138. Field(uint) nullPolyInlineCacheCount;
  139. Field(uint) emptyPolyInlineCacheCount;
  140. Field(uint) ignoredPolyInlineCacheCount;
  141. Field(uint) highUtilPolyInlineCacheCount;
  142. Field(uint) lowUtilPolyInlineCacheCount;
  143. Field(uint) equivPolyInlineCacheCount;
  144. Field(uint) nonEquivPolyInlineCacheCount;
  145. Field(uint) disabledPolyInlineCacheCount;
  146. Field(uint) clonedMonoInlineCacheCount;
  147. Field(uint) clonedPolyInlineCacheCount;
  148. FieldAccessStats() :
  149. totalInlineCacheCount(0), noInfoInlineCacheCount(0), monoInlineCacheCount(0), emptyMonoInlineCacheCount(0),
  150. polyInlineCacheCount(0), nullPolyInlineCacheCount(0), emptyPolyInlineCacheCount(0), ignoredPolyInlineCacheCount(0),
  151. highUtilPolyInlineCacheCount(0), lowUtilPolyInlineCacheCount(0),
  152. equivPolyInlineCacheCount(0), nonEquivPolyInlineCacheCount(0), disabledPolyInlineCacheCount(0),
  153. clonedMonoInlineCacheCount(0), clonedPolyInlineCacheCount(0) {}
  154. void Add(FieldAccessStats* other);
  155. };
  156. typedef FieldAccessStats* FieldAccessStatsPtr;
  157. #else
  158. typedef void* FieldAccessStatsPtr;
  159. #endif
  160. #pragma region Entry point class declarations
  161. class ProxyEntryPointInfo: public ExpirableObject
  162. {
  163. public:
  164. // These are public because we don't manage them nor their consistency;
  165. // the user of this class does.
  166. FieldNoBarrier(Js::JavascriptMethod) jsMethod;
  167. ProxyEntryPointInfo(Js::JavascriptMethod jsMethod, ThreadContext* context = nullptr):
  168. ExpirableObject(context),
  169. jsMethod(jsMethod)
  170. {
  171. }
  172. static DWORD GetAddressOffset() { return offsetof(ProxyEntryPointInfo, jsMethod); }
  173. virtual void Expire()
  174. {
  175. AssertMsg(false, "Expire called on object that doesn't support expiration");
  176. }
  177. virtual void EnterExpirableCollectMode()
  178. {
  179. AssertMsg(false, "EnterExpirableCollectMode called on object that doesn't support expiration");
  180. }
  181. virtual bool IsFunctionEntryPointInfo() const { return false; }
  182. };
  183. struct TypeGuardTransferData
  184. {
  185. Field(unsigned int) propertyGuardCount;
  186. FieldNoBarrier(TypeGuardTransferEntryIDL*) entries;
  187. };
  188. struct CtorCacheTransferData
  189. {
  190. Field(unsigned int) ctorCachesCount;
  191. FieldNoBarrier(CtorCacheTransferEntryIDL **) entries;
  192. };
  193. // Not thread safe.
  194. // Note that instances of this class are read from and written to from the
  195. // main and JIT threads.
  196. class EntryPointInfo : public ProxyEntryPointInfo
  197. {
  198. private:
  199. enum State : BYTE
  200. {
  201. NotScheduled, // code gen has not been scheduled
  202. CodeGenPending, // code gen job has been scheduled
  203. CodeGenQueued, // code gen has been queued and all the code gen data has been gathered.
  204. CodeGenRecorded, // backend completed, but job still pending
  205. CodeGenDone, // code gen job successfully completed
  206. JITCapReached, // workitem created but JIT cap reached
  207. PendingCleanup, // workitem needs to be cleaned up but couldn't for some reason- it'll be cleaned up at the next opportunity
  208. CleanedUp // the entry point has been cleaned up
  209. };
  210. // The following fields are packed into a 32-bit/64-bit, and the tag to avoid fals positive.
  211. Field(const bool) tag : 1;
  212. Field(bool) isLoopBody : 1;
  213. Field(bool) hasJittedStackClosure : 1;
  214. Field(bool) isAsmJsFunction : 1; // true if entrypoint is for asmjs function
  215. Field(State) state; // Single state member so users can query state w/o a lock
  216. #if ENABLE_NATIVE_CODEGEN
  217. Field(BYTE) pendingInlinerVersion;
  218. Field(ImplicitCallFlags) pendingImplicitCallFlags;
  219. Field(uint32) pendingPolymorphicCacheState;
  220. class JitTransferData
  221. {
  222. friend EntryPointInfo;
  223. private:
  224. Field(TypeRefSet*) jitTimeTypeRefs;
  225. Field(PinnedTypeRefsIDL*) runtimeTypeRefs;
  226. Field(int) propertyGuardCount;
  227. // This is a dynamically sized array of dynamically sized TypeGuardTransferEntries. It's heap allocated by the JIT
  228. // thread and lives until entry point is installed, at which point it is explicitly freed.
  229. FieldNoBarrier(TypeGuardTransferEntry*) propertyGuardsByPropertyId;
  230. Field(size_t) propertyGuardsByPropertyIdPlusSize;
  231. // This is a dynamically sized array of dynamically sized CtorCacheGuardTransferEntry. It's heap allocated by the JIT
  232. // thread and lives until entry point is installed, at which point it is explicitly freed.
  233. FieldNoBarrier(CtorCacheGuardTransferEntry*) ctorCacheGuardsByPropertyId;
  234. Field(size_t) ctorCacheGuardsByPropertyIdPlusSize;
  235. Field(int) equivalentTypeGuardCount;
  236. Field(int) lazyBailoutPropertyCount;
  237. // This is a dynamically sized array of JitEquivalentTypeGuards. It's heap allocated by the JIT thread and lives
  238. // until entry point is installed, at which point it is explicitly freed. We need it during installation so as to
  239. // swap the cache associated with each guard from the heap to the recycler (so the types in the cache are kept alive).
  240. FieldNoBarrier(JitEquivalentTypeGuard**) equivalentTypeGuards;
  241. FieldNoBarrier(Js::PropertyId*) lazyBailoutProperties;
  242. FieldNoBarrier(NativeCodeData*) jitTransferRawData;
  243. FieldNoBarrier(EquivalentTypeGuardOffsets*) equivalentTypeGuardOffsets;
  244. Field(TypeGuardTransferData) typeGuardTransferData;
  245. Field(CtorCacheTransferData) ctorCacheTransferData;
  246. Field(bool) falseReferencePreventionBit;
  247. Field(bool) isReady;
  248. public:
  249. JitTransferData():
  250. jitTimeTypeRefs(nullptr), runtimeTypeRefs(nullptr),
  251. propertyGuardCount(0), propertyGuardsByPropertyId(nullptr), propertyGuardsByPropertyIdPlusSize(0),
  252. ctorCacheGuardsByPropertyId(nullptr), ctorCacheGuardsByPropertyIdPlusSize(0),
  253. equivalentTypeGuardCount(0), equivalentTypeGuards(nullptr), jitTransferRawData(nullptr),
  254. falseReferencePreventionBit(true), isReady(false), lazyBailoutProperties(nullptr), lazyBailoutPropertyCount(0){}
  255. void SetRawData(NativeCodeData* rawData) { jitTransferRawData = rawData; }
  256. void AddJitTimeTypeRef(void* typeRef, Recycler* recycler);
  257. int GetRuntimeTypeRefCount() { return this->runtimeTypeRefs ? this->runtimeTypeRefs->count : 0; }
  258. void** GetRuntimeTypeRefs() { return this->runtimeTypeRefs ? (void**)this->runtimeTypeRefs->typeRefs : nullptr; }
  259. void SetRuntimeTypeRefs(PinnedTypeRefsIDL* pinnedTypeRefs) { this->runtimeTypeRefs = pinnedTypeRefs;}
  260. JitEquivalentTypeGuard** GetEquivalentTypeGuards() const { return this->equivalentTypeGuards; }
  261. void SetEquivalentTypeGuards(JitEquivalentTypeGuard** guards, int count)
  262. {
  263. this->equivalentTypeGuardCount = count;
  264. this->equivalentTypeGuards = guards;
  265. }
  266. void SetLazyBailoutProperties(Js::PropertyId* properties, int count)
  267. {
  268. this->lazyBailoutProperties = properties;
  269. this->lazyBailoutPropertyCount = count;
  270. }
  271. void SetEquivalentTypeGuardOffsets(EquivalentTypeGuardOffsets* offsets)
  272. {
  273. equivalentTypeGuardOffsets = offsets;
  274. }
  275. void SetTypeGuardTransferData(JITOutputIDL* data)
  276. {
  277. typeGuardTransferData.entries = data->typeGuardEntries;
  278. typeGuardTransferData.propertyGuardCount = data->propertyGuardCount;
  279. }
  280. void SetCtorCacheTransferData(JITOutputIDL * data)
  281. {
  282. ctorCacheTransferData.entries = data->ctorCacheEntries;
  283. ctorCacheTransferData.ctorCachesCount = data->ctorCachesCount;
  284. }
  285. bool GetIsReady() { return this->isReady; }
  286. void SetIsReady() { this->isReady = true; }
  287. private:
  288. void EnsureJitTimeTypeRefs(Recycler* recycler);
  289. };
  290. Field(NativeCodeData *) inProcJITNaticeCodedata;
  291. FieldNoBarrier(char*) nativeDataBuffer;
  292. union
  293. {
  294. Field(Field(JavascriptNumber*)*) numberArray;
  295. Field(CodeGenNumberChunk*) numberChunks;
  296. };
  297. Field(XProcNumberPageSegment*) numberPageSegments;
  298. FieldNoBarrier(SmallSpanSequence *) nativeThrowSpanSequence;
  299. typedef JsUtil::BaseHashSet<RecyclerWeakReference<FunctionBody>*, Recycler, PowerOf2SizePolicy> WeakFuncRefSet;
  300. Field(WeakFuncRefSet *) weakFuncRefSet;
  301. // Need to keep strong references to the guards here so they don't get collected while the entry point is alive.
  302. typedef JsUtil::BaseDictionary<Js::PropertyId, PropertyGuard*, Recycler, PowerOf2SizePolicy> SharedPropertyGuardDictionary;
  303. Field(SharedPropertyGuardDictionary*) sharedPropertyGuards;
  304. typedef JsUtil::List<LazyBailOutRecord, HeapAllocator> BailOutRecordMap;
  305. Field(BailOutRecordMap*) bailoutRecordMap;
  306. // This array holds fake weak references to type property guards. We need it to zero out the weak references when the
  307. // entry point is finalized and the guards are about to be freed. Otherwise, if one of the guards was to be invalidated
  308. // from the thread context, we would AV trying to access freed memory. Note that the guards themselves are allocated by
  309. // NativeCodeData::Allocator and are kept alive by the data field. The weak references are recycler allocated, and so
  310. // the array must be recycler allocated also, so that the recycler doesn't collect the weak references.
  311. Field(Field(FakePropertyGuardWeakReference*)*) propertyGuardWeakRefs;
  312. Field(EquivalentTypeCache*) equivalentTypeCaches;
  313. Field(EntryPointInfo **) registeredEquivalentTypeCacheRef;
  314. Field(int) propertyGuardCount;
  315. Field(int) equivalentTypeCacheCount;
  316. Field(uint) inlineeFrameOffsetArrayOffset;
  317. Field(uint) inlineeFrameOffsetArrayCount;
  318. typedef SListCounted<ConstructorCache*, Recycler> ConstructorCacheList;
  319. Field(ConstructorCacheList*) constructorCaches;
  320. Field(EntryPointPolymorphicInlineCacheInfo *) polymorphicInlineCacheInfo;
  321. // This field holds any recycler allocated references that must be kept alive until
  322. // we install the entry point. It is freed at that point, so anything that must survive
  323. // until the EntryPointInfo itself goes away, must be copied somewhere else.
  324. Field(JitTransferData*) jitTransferData;
  325. // If we pin types this array contains strong references to types, otherwise it holds weak references.
  326. Field(Field(void*)*) runtimeTypeRefs;
  327. protected:
  328. #if PDATA_ENABLED
  329. Field(XDataAllocation *) xdataInfo;
  330. #endif
  331. #endif // ENABLE_NATIVE_CODEGEN
  332. Field(CodeGenWorkItem *) workItem;
  333. FieldNoBarrier(Js::JavascriptMethod) nativeAddress;
  334. FieldNoBarrier(Js::JavascriptMethod) thunkAddress;
  335. Field(ptrdiff_t) codeSize;
  336. protected:
  337. Field(JavascriptLibrary*) library;
  338. #if ENABLE_NATIVE_CODEGEN
  339. typedef JsUtil::List<NativeOffsetInlineeFramePair, HeapAllocator> InlineeFrameMap;
  340. Field(InlineeFrameMap*) inlineeFrameMap;
  341. #endif
  342. #if ENABLE_DEBUG_STACK_BACK_TRACE
  343. FieldNoBarrier(StackBackTrace*) cleanupStack; // NoCheckHeapAllocator
  344. #endif
  345. public:
  346. Field(uint) frameHeight;
  347. Field(bool) nativeEntryPointProcessed;
  348. #if ENABLE_DEBUG_CONFIG_OPTIONS
  349. public:
  350. enum CleanupReason
  351. {
  352. NotCleanedUp,
  353. CodeGenFailedOOM,
  354. CodeGenFailedStackOverflow,
  355. CodeGenFailedAborted,
  356. CodeGenFailedExceedJITLimit,
  357. CodeGenFailedUnknown,
  358. NativeCodeInstallFailure,
  359. CleanUpForFinalize
  360. };
  361. private:
  362. Field(CleanupReason) cleanupReason;
  363. #endif
  364. #ifdef FIELD_ACCESS_STATS
  365. private:
  366. Field(FieldAccessStatsPtr) fieldAccessStats;
  367. #endif
  368. public:
  369. virtual void Finalize(bool isShutdown) override;
  370. virtual bool IsFunctionEntryPointInfo() const override { return true; }
  371. #if ENABLE_NATIVE_CODEGEN
  372. char** GetNativeDataBufferRef() { return &nativeDataBuffer; }
  373. char* GetNativeDataBuffer() { return nativeDataBuffer; }
  374. void SetInProcJITNativeCodeData(NativeCodeData* nativeCodeData) { inProcJITNaticeCodedata = nativeCodeData; }
  375. void SetNumberChunks(CodeGenNumberChunk* chunks)
  376. {
  377. Assert(numberPageSegments == nullptr);
  378. numberChunks = chunks;
  379. }
  380. void SetNumberArray(Field(Js::JavascriptNumber*)* array)
  381. {
  382. Assert(numberPageSegments != nullptr);
  383. numberArray = array;
  384. }
  385. void SetNumberPageSegment(XProcNumberPageSegment * segments)
  386. {
  387. Assert(numberPageSegments == nullptr);
  388. numberPageSegments = segments;
  389. }
  390. #endif
  391. protected:
  392. EntryPointInfo(Js::JavascriptMethod method, JavascriptLibrary* library, void* validationCookie, ThreadContext* context = nullptr, bool isLoopBody = false) :
  393. ProxyEntryPointInfo(method, context), tag(1), nativeEntryPointProcessed(false),
  394. #if ENABLE_NATIVE_CODEGEN
  395. nativeThrowSpanSequence(nullptr), workItem(nullptr), weakFuncRefSet(nullptr),
  396. jitTransferData(nullptr), sharedPropertyGuards(nullptr), propertyGuardCount(0), propertyGuardWeakRefs(nullptr),
  397. equivalentTypeCacheCount(0), equivalentTypeCaches(nullptr), constructorCaches(nullptr), state(NotScheduled), inProcJITNaticeCodedata(nullptr),
  398. numberChunks(nullptr), numberPageSegments(nullptr), polymorphicInlineCacheInfo(nullptr), runtimeTypeRefs(nullptr),
  399. isLoopBody(isLoopBody), hasJittedStackClosure(false), registeredEquivalentTypeCacheRef(nullptr), bailoutRecordMap(nullptr), inlineeFrameMap(nullptr),
  400. #if PDATA_ENABLED
  401. xdataInfo(nullptr),
  402. #endif
  403. #endif
  404. library(library), codeSize(0), nativeAddress(nullptr), isAsmJsFunction(false), validationCookie(validationCookie)
  405. #if ENABLE_DEBUG_STACK_BACK_TRACE
  406. , cleanupStack(nullptr)
  407. #endif
  408. #if ENABLE_DEBUG_CONFIG_OPTIONS
  409. , cleanupReason(NotCleanedUp)
  410. #endif
  411. #if DBG_DUMP | defined(VTUNE_PROFILING)
  412. , nativeOffsetMaps(&HeapAllocator::Instance)
  413. #endif
  414. #ifdef FIELD_ACCESS_STATS
  415. , fieldAccessStats(nullptr)
  416. #endif
  417. {}
  418. virtual void ReleasePendingWorkItem() {};
  419. virtual void OnCleanup(bool isShutdown) = 0;
  420. #ifdef PERF_COUNTERS
  421. virtual void OnRecorded() = 0;
  422. #endif
  423. private:
  424. State GetState() const
  425. {
  426. Assert(this->state >= NotScheduled && this->state <= CleanedUp);
  427. return this->state;
  428. }
  429. public:
  430. ScriptContext* GetScriptContext();
  431. virtual FunctionBody *GetFunctionBody() const = 0;
  432. #if ENABLE_NATIVE_CODEGEN
  433. EntryPointPolymorphicInlineCacheInfo * EnsurePolymorphicInlineCacheInfo(Recycler * recycler, FunctionBody * functionBody);
  434. EntryPointPolymorphicInlineCacheInfo * GetPolymorphicInlineCacheInfo() { return polymorphicInlineCacheInfo; }
  435. JitTransferData* GetJitTransferData() { return this->jitTransferData; }
  436. JitTransferData* EnsureJitTransferData(Recycler* recycler);
  437. #if PDATA_ENABLED
  438. XDataAllocation* GetXDataInfo() { return this->xdataInfo; }
  439. void SetXDataInfo(XDataAllocation* xdataInfo) { this->xdataInfo = xdataInfo; }
  440. #endif
  441. #ifdef FIELD_ACCESS_STATS
  442. FieldAccessStats* GetFieldAccessStats() { return this->fieldAccessStats; }
  443. FieldAccessStats* EnsureFieldAccessStats(Recycler* recycler);
  444. #endif
  445. void PinTypeRefs(ScriptContext* scriptContext);
  446. void InstallGuards(ScriptContext* scriptContext);
  447. #endif
  448. void Cleanup(bool isShutdown, bool captureCleanupStack);
  449. #if ENABLE_DEBUG_STACK_BACK_TRACE
  450. void CaptureCleanupStackTrace();
  451. #endif
  452. bool IsNotScheduled() const
  453. {
  454. return this->GetState() == NotScheduled;
  455. }
  456. bool IsCodeGenPending() const
  457. {
  458. return this->GetState() == CodeGenPending;
  459. }
  460. bool IsCodeGenRecorded() const
  461. {
  462. return this->GetState() == CodeGenRecorded;
  463. }
  464. bool IsNativeCode() const
  465. {
  466. #if ENABLE_NATIVE_CODEGEN
  467. return this->GetState() == CodeGenRecorded ||
  468. this->GetState() == CodeGenDone;
  469. #else
  470. return false;
  471. #endif
  472. }
  473. bool IsCodeGenDone() const
  474. {
  475. #if ENABLE_NATIVE_CODEGEN
  476. return this->GetState() == CodeGenDone;
  477. #else
  478. return false;
  479. #endif
  480. }
  481. bool IsCodeGenQueued() const
  482. {
  483. #if ENABLE_NATIVE_CODEGEN
  484. return this->GetState() == CodeGenQueued;
  485. #else
  486. return false;
  487. #endif
  488. }
  489. bool IsJITCapReached() const
  490. {
  491. #if ENABLE_NATIVE_CODEGEN
  492. return this->GetState() == JITCapReached;
  493. #else
  494. return false;
  495. #endif
  496. }
  497. bool IsCleanedUp() const
  498. {
  499. return this->GetState() == CleanedUp;
  500. }
  501. bool IsPendingCleanup() const
  502. {
  503. return this->GetState() == PendingCleanup;
  504. }
  505. void SetPendingCleanup()
  506. {
  507. this->state = PendingCleanup;
  508. }
  509. #if ENABLE_DEBUG_CONFIG_OPTIONS
  510. void SetCleanupReason(CleanupReason reason)
  511. {
  512. this->cleanupReason = reason;
  513. }
  514. #endif
  515. bool IsLoopBody() const
  516. {
  517. return this->isLoopBody;
  518. }
  519. #if ENABLE_NATIVE_CODEGEN
  520. bool HasJittedStackClosure() const
  521. {
  522. return this->hasJittedStackClosure;
  523. }
  524. void SetHasJittedStackClosure()
  525. {
  526. this->hasJittedStackClosure = true;
  527. }
  528. #endif
  529. void Reset(bool resetStateToNotScheduled = true);
  530. #if ENABLE_NATIVE_CODEGEN
  531. void SetCodeGenPending(CodeGenWorkItem * workItem)
  532. {
  533. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  534. Assert(workItem != nullptr);
  535. this->workItem = workItem;
  536. this->state = CodeGenPending;
  537. }
  538. void SetCodeGenPending()
  539. {
  540. Assert(this->GetState() == CodeGenQueued);
  541. this->state = CodeGenPending;
  542. }
  543. void SetCodeGenQueued()
  544. {
  545. Assert(this->GetState() == CodeGenPending);
  546. this->state = CodeGenQueued;
  547. }
  548. void RevertToNotScheduled()
  549. {
  550. Assert(this->GetState() == CodeGenPending);
  551. Assert(this->workItem != nullptr);
  552. this->workItem = nullptr;
  553. this->state = NotScheduled;
  554. }
  555. void SetCodeGenPendingWithStackAllocatedWorkItem()
  556. {
  557. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  558. this->workItem = nullptr;
  559. this->state = CodeGenPending;
  560. }
  561. void SetCodeGenRecorded(Js::JavascriptMethod thunkAddress, Js::JavascriptMethod nativeAddress, ptrdiff_t codeSize)
  562. {
  563. Assert(this->GetState() == CodeGenQueued);
  564. Assert(codeSize > 0);
  565. this->nativeAddress = nativeAddress;
  566. this->thunkAddress = thunkAddress;
  567. this->codeSize = codeSize;
  568. this->state = CodeGenRecorded;
  569. #ifdef PERF_COUNTERS
  570. this->OnRecorded();
  571. #endif
  572. }
  573. void SetCodeGenDone();
  574. void SetJITCapReached()
  575. {
  576. Assert(this->GetState() == CodeGenQueued);
  577. this->state = JITCapReached;
  578. this->workItem = nullptr;
  579. }
  580. SmallSpanSequence* GetNativeThrowSpanSequence() const
  581. {
  582. Assert(this->GetState() != NotScheduled);
  583. Assert(this->GetState() != CleanedUp);
  584. return nativeThrowSpanSequence;
  585. }
  586. void SetNativeThrowSpanSequence(SmallSpanSequence* seq)
  587. {
  588. Assert(this->GetState() == CodeGenQueued);
  589. Assert(this->nativeThrowSpanSequence == nullptr);
  590. nativeThrowSpanSequence = seq;
  591. }
  592. bool IsInNativeAddressRange(DWORD_PTR codeAddress) {
  593. return (IsNativeCode() &&
  594. codeAddress >= GetNativeAddress() &&
  595. codeAddress < GetNativeAddress() + GetCodeSize());
  596. }
  597. #endif
  598. DWORD_PTR GetNativeAddress() const
  599. {
  600. // need the assert to skip for asmjsFunction as nativeAddress can be interpreter too for asmjs
  601. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone || this->isAsmJsFunction);
  602. // !! this is illegal, however (by design) `IsInNativeAddressRange` (right above) needs it
  603. return reinterpret_cast<DWORD_PTR>(this->nativeAddress);
  604. }
  605. Js::JavascriptMethod GetThunkAddress() const
  606. {
  607. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone);
  608. return this->thunkAddress;
  609. }
  610. Js::JavascriptMethod GetNativeEntrypoint() const
  611. {
  612. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone || this->isAsmJsFunction);
  613. return this->thunkAddress ? this->thunkAddress : this->nativeAddress;
  614. }
  615. ptrdiff_t GetCodeSize() const
  616. {
  617. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone);
  618. return codeSize;
  619. }
  620. CodeGenWorkItem * GetWorkItem() const
  621. {
  622. State state = this->GetState();
  623. Assert(state != NotScheduled || this->workItem == nullptr);
  624. Assert(state == CleanedUp && this->workItem == nullptr ||
  625. state != CleanedUp);
  626. if (state == PendingCleanup)
  627. {
  628. return nullptr;
  629. }
  630. return this->workItem;
  631. }
  632. #ifdef ASMJS_PLAT
  633. // set code size, used by TJ to set the code size
  634. void SetCodeSize(ptrdiff_t size)
  635. {
  636. Assert(isAsmJsFunction);
  637. this->codeSize = size;
  638. }
  639. void SetNativeAddress(Js::JavascriptMethod address)
  640. {
  641. Assert(isAsmJsFunction);
  642. this->nativeAddress = address;
  643. }
  644. void SetIsAsmJSFunction(bool value)
  645. {
  646. this->isAsmJsFunction = value;
  647. }
  648. #endif
  649. bool GetIsAsmJSFunction()const
  650. {
  651. return this->isAsmJsFunction;
  652. }
  653. #ifdef ASMJS_PLAT
  654. void SetTJCodeGenDone()
  655. {
  656. Assert(isAsmJsFunction);
  657. this->state = CodeGenDone;
  658. this->workItem = nullptr;
  659. }
  660. #endif
  661. #if ENABLE_NATIVE_CODEGEN
  662. void AddWeakFuncRef(RecyclerWeakReference<FunctionBody> *weakFuncRef, Recycler *recycler);
  663. WeakFuncRefSet *EnsureWeakFuncRefSet(Recycler *recycler);
  664. void EnsureIsReadyToCall();
  665. void ProcessJitTransferData();
  666. void ResetOnLazyBailoutFailure();
  667. void OnNativeCodeInstallFailure();
  668. virtual void ResetOnNativeCodeInstallFailure() = 0;
  669. Js::PropertyGuard* RegisterSharedPropertyGuard(Js::PropertyId propertyId, ScriptContext* scriptContext);
  670. Js::PropertyId* GetSharedPropertyGuards(_Out_ unsigned int& count);
  671. bool TryGetSharedPropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard*& guard);
  672. void RecordTypeGuards(int propertyGuardCount, TypeGuardTransferEntry* typeGuardTransferRecord, size_t typeGuardTransferPlusSize);
  673. void RecordCtorCacheGuards(CtorCacheGuardTransferEntry* ctorCacheTransferRecord, size_t ctorCacheTransferPlusSize);
  674. void FreePropertyGuards();
  675. void FreeJitTransferData();
  676. void RegisterEquivalentTypeCaches();
  677. void UnregisterEquivalentTypeCaches();
  678. bool ClearEquivalentTypeCaches();
  679. void RegisterConstructorCache(Js::ConstructorCache* constructorCache, Recycler* recycler);
  680. uint GetConstructorCacheCount() const { return this->constructorCaches != nullptr ? this->constructorCaches->Count() : 0; }
  681. uint32 GetPendingPolymorphicCacheState() const { return this->pendingPolymorphicCacheState; }
  682. void SetPendingPolymorphicCacheState(uint32 state) { this->pendingPolymorphicCacheState = state; }
  683. BYTE GetPendingInlinerVersion() const { return this->pendingInlinerVersion; }
  684. void SetPendingInlinerVersion(BYTE version) { this->pendingInlinerVersion = version; }
  685. ImplicitCallFlags GetPendingImplicitCallFlags() const { return this->pendingImplicitCallFlags; }
  686. void SetPendingImplicitCallFlags(ImplicitCallFlags flags) { this->pendingImplicitCallFlags = flags; }
  687. virtual void Invalidate(bool prolongEntryPoint) { Assert(false); }
  688. void RecordBailOutMap(JsUtil::List<LazyBailOutRecord, ArenaAllocator>* bailoutMap);
  689. void RecordInlineeFrameMap(JsUtil::List<NativeOffsetInlineeFramePair, ArenaAllocator>* tempInlineeFrameMap);
  690. void RecordInlineeFrameOffsetsInfo(unsigned int offsetsArrayOffset, unsigned int offsetsArrayCount);
  691. InlineeFrameRecord* FindInlineeFrame(void* returnAddress);
  692. bool HasInlinees() { return this->frameHeight > 0; }
  693. void DoLazyBailout(BYTE** addressOfReturnAddress, Js::FunctionBody* functionBody, const PropertyRecord* propertyRecord);
  694. #endif
  695. #if DBG_DUMP
  696. public:
  697. #elif defined(VTUNE_PROFILING)
  698. private:
  699. #endif
  700. #if DBG_DUMP || defined(VTUNE_PROFILING)
  701. // NativeOffsetMap is public for DBG_DUMP, private for VTUNE_PROFILING
  702. struct NativeOffsetMap
  703. {
  704. uint32 statementIndex;
  705. regex::Interval nativeOffsetSpan;
  706. };
  707. private:
  708. typedef JsUtil::List<NativeOffsetMap, HeapAllocator> NativeOffsetMapListType;
  709. Field(NativeOffsetMapListType) nativeOffsetMaps;
  710. public:
  711. void RecordNativeMap(uint32 offset, uint32 statementIndex);
  712. int GetNativeOffsetMapCount() const;
  713. #endif
  714. #if DBG_DUMP && ENABLE_NATIVE_CODEGEN
  715. void DumpNativeOffsetMaps();
  716. void DumpNativeThrowSpanSequence();
  717. NativeOffsetMap* GetNativeOffsetMap(int index)
  718. {
  719. Assert(index >= 0);
  720. Assert(index < GetNativeOffsetMapCount());
  721. return &nativeOffsetMaps.Item(index);
  722. }
  723. #endif
  724. #ifdef VTUNE_PROFILING
  725. public:
  726. uint PopulateLineInfo(void* pLineInfo, FunctionBody* body);
  727. #endif
  728. protected:
  729. Field(void*) validationCookie;
  730. };
  731. class FunctionEntryPointInfo : public EntryPointInfo
  732. {
  733. public:
  734. Field(FunctionProxy *) functionProxy;
  735. Field(FunctionEntryPointInfo*) nextEntryPoint;
  736. // The offset on the native stack, from which the locals are located (Populated at RegAlloc phase). Used for debug purpose.
  737. Field(int32) localVarSlotsOffset;
  738. // The offset which stores that any of the locals are changed from the debugger.
  739. Field(int32) localVarChangedOffset;
  740. Field(uint) entryPointIndex;
  741. Field(uint32) callsCount;
  742. Field(uint32) lastCallsCount;
  743. private:
  744. Field(ExecutionMode) jitMode;
  745. Field(bool) mIsTemplatizedJitMode; // true only if in TJ mode, used only for debugging
  746. public:
  747. FunctionEntryPointInfo(FunctionProxy * functionInfo, Js::JavascriptMethod method, ThreadContext* context, void* validationCookie);
  748. #ifdef ASMJS_PLAT
  749. void SetIsTJMode(bool value);
  750. bool GetIsTJMode()const;
  751. //End AsmJS Support
  752. #endif
  753. bool ExecutedSinceCallCountCollection() const;
  754. void CollectCallCounts();
  755. virtual FunctionBody *GetFunctionBody() const override;
  756. #if ENABLE_NATIVE_CODEGEN
  757. ExecutionMode GetJitMode() const;
  758. void SetJitMode(const ExecutionMode jitMode);
  759. virtual void Invalidate(bool prolongEntryPoint) override;
  760. virtual void Expire() override;
  761. virtual void EnterExpirableCollectMode() override;
  762. virtual void ResetOnNativeCodeInstallFailure() override;
  763. static const uint8 GetDecrCallCountPerBailout()
  764. {
  765. return (uint8)CONFIG_FLAG(CallsToBailoutsRatioForRejit) + 1;
  766. }
  767. #endif
  768. virtual void OnCleanup(bool isShutdown) override;
  769. virtual void ReleasePendingWorkItem() override;
  770. #ifdef PERF_COUNTERS
  771. virtual void OnRecorded() override;
  772. #endif
  773. };
  774. class LoopEntryPointInfo : public EntryPointInfo
  775. {
  776. public:
  777. Field(LoopHeader*) loopHeader;
  778. Field(uint) jittedLoopIterationsSinceLastBailout; // number of times the loop iterated in the jitted code before bailing out
  779. Field(uint) totalJittedLoopIterations; // total number of times the loop has iterated in the jitted code for this entry point for a particular invocation of the loop
  780. LoopEntryPointInfo(LoopHeader* loopHeader, Js::JavascriptLibrary* library, void* validationCookie) :
  781. EntryPointInfo(nullptr, library, validationCookie, /*threadContext*/ nullptr, /*isLoopBody*/ true),
  782. loopHeader(loopHeader),
  783. jittedLoopIterationsSinceLastBailout(0),
  784. totalJittedLoopIterations(0),
  785. mIsTemplatizedJitMode(false)
  786. #ifdef BGJIT_STATS
  787. ,used(false)
  788. #endif
  789. { }
  790. virtual FunctionBody *GetFunctionBody() const override;
  791. virtual void OnCleanup(bool isShutdown) override;
  792. #if ENABLE_NATIVE_CODEGEN
  793. virtual void ResetOnNativeCodeInstallFailure() override;
  794. static const uint8 GetDecrLoopCountPerBailout()
  795. {
  796. return (uint8)CONFIG_FLAG(LoopIterationsToBailoutsRatioForRejit) + 1;
  797. }
  798. #endif
  799. #ifdef ASMJS_PLAT
  800. void SetIsTJMode(bool value)
  801. {
  802. Assert(this->GetIsAsmJSFunction());
  803. mIsTemplatizedJitMode = value;
  804. }
  805. bool GetIsTJMode()const
  806. {
  807. return mIsTemplatizedJitMode;
  808. };
  809. #endif
  810. #ifdef PERF_COUNTERS
  811. virtual void OnRecorded() override;
  812. #endif
  813. #ifdef BGJIT_STATS
  814. bool IsUsed() const
  815. {
  816. return this->used;
  817. }
  818. void MarkAsUsed()
  819. {
  820. this->used = true;
  821. }
  822. #endif
  823. private:
  824. #ifdef BGJIT_STATS
  825. Field(bool) used;
  826. #endif
  827. Field(bool) mIsTemplatizedJitMode;
  828. };
  829. typedef RecyclerWeakReference<FunctionEntryPointInfo> FunctionEntryPointWeakRef;
  830. typedef SynchronizableList<FunctionEntryPointWeakRef*, JsUtil::List<FunctionEntryPointWeakRef*>> FunctionEntryPointList;
  831. typedef SynchronizableList<LoopEntryPointInfo*, JsUtil::List<LoopEntryPointInfo*>> LoopEntryPointList;
  832. #pragma endregion
  833. struct LoopHeader
  834. {
  835. private:
  836. Field(LoopEntryPointList*) entryPoints;
  837. public:
  838. Field(uint) startOffset;
  839. Field(uint) endOffset;
  840. Field(uint) interpretCount;
  841. Field(uint) profiledLoopCounter;
  842. #if ENABLE_NATIVE_CODEGEN
  843. Field(uint) rejitCount;
  844. #endif
  845. Field(bool) isNested;
  846. Field(bool) isInTry;
  847. Field(FunctionBody *) functionBody;
  848. #if DBG_DUMP
  849. Field(uint) nativeCount;
  850. #endif
  851. static const uint NoLoop = (uint)-1;
  852. static const uint GetOffsetOfProfiledLoopCounter() { return offsetof(LoopHeader, profiledLoopCounter); }
  853. static const uint GetOffsetOfInterpretCount() { return offsetof(LoopHeader, interpretCount); }
  854. bool Contains(Js::LoopHeader * loopHeader) const
  855. {
  856. return (this->startOffset <= loopHeader->startOffset && loopHeader->endOffset <= this->endOffset);
  857. }
  858. bool Contains(uint offset) const
  859. {
  860. return this->startOffset <= offset && offset < this->endOffset;
  861. }
  862. Js::JavascriptMethod GetCurrentEntryPoint() const
  863. {
  864. LoopEntryPointInfo * entryPoint = GetCurrentEntryPointInfo();
  865. if (entryPoint != nullptr)
  866. {
  867. return this->entryPoints->Item(this->GetCurrentEntryPointIndex())->jsMethod;
  868. }
  869. return nullptr;
  870. }
  871. LoopEntryPointInfo * GetCurrentEntryPointInfo() const
  872. {
  873. Assert(this->entryPoints->Count() > 0);
  874. return this->entryPoints->Item(this->GetCurrentEntryPointIndex());
  875. }
  876. uint GetByteCodeCount()
  877. {
  878. return (endOffset - startOffset);
  879. }
  880. int GetCurrentEntryPointIndex() const
  881. {
  882. return this->entryPoints->Count() - 1;
  883. }
  884. LoopEntryPointInfo * GetEntryPointInfo(int index) const
  885. {
  886. return this->entryPoints->Item(index);
  887. }
  888. template <class Fn>
  889. void MapEntryPoints(Fn fn) const
  890. {
  891. if (this->entryPoints) // ETW rundown may call this before entryPoints initialization
  892. {
  893. this->entryPoints->Map([&](int index, LoopEntryPointInfo * entryPoint)
  894. {
  895. if (entryPoint != nullptr)
  896. {
  897. fn(index, entryPoint);
  898. }
  899. });
  900. }
  901. }
  902. template <class Fn>
  903. bool MapEntryPointsUntil(Fn fn) const
  904. {
  905. if (this->entryPoints) // ETW rundown may call this before entryPoints initialization
  906. {
  907. return this->entryPoints->MapUntil([&](int index, LoopEntryPointInfo * entryPoint)
  908. {
  909. if (entryPoint != nullptr)
  910. {
  911. return fn(index, entryPoint);
  912. }
  913. return false;
  914. });
  915. }
  916. return false;
  917. }
  918. template <class DebugSite, class Fn>
  919. HRESULT MapEntryPoints(DebugSite site, Fn fn) const // external debugging version
  920. {
  921. return Map(site, PointerValue(this->entryPoints), [&](int index, LoopEntryPointInfo * entryPoint)
  922. {
  923. if (entryPoint != nullptr)
  924. {
  925. fn(index, entryPoint);
  926. }
  927. });
  928. }
  929. void Init(FunctionBody * functionBody);
  930. #if ENABLE_NATIVE_CODEGEN
  931. int CreateEntryPoint();
  932. void ReleaseEntryPoints();
  933. void IncRejitCount() { ++rejitCount; }
  934. uint GetRejitCount() { return rejitCount; }
  935. #endif
  936. void ResetInterpreterCount()
  937. {
  938. this->interpretCount = 0;
  939. }
  940. void ResetProfiledLoopCounter()
  941. {
  942. this->profiledLoopCounter = 0;
  943. }
  944. };
  945. // ----------------------------------------------------------------------------
  946. // SWB-TODO: Below explicitly uses write barrier. Move top code to new header file.
  947. //
  948. class FunctionProxy;
  949. typedef Field(FunctionInfo*)* FunctionInfoArray;
  950. typedef Field(FunctionInfo*)* FunctionInfoPtrPtr;
  951. //
  952. // FunctionProxy represents a user defined function
  953. // This could be either from a source file or the byte code cache
  954. // The function need not have been compiled yet- it could be parsed or compiled
  955. // at a later time
  956. //
  957. class FunctionProxy : public FinalizableObject
  958. {
  959. public:
  960. typedef RecyclerWeakReference<ScriptFunctionType> FunctionTypeWeakRef;
  961. typedef JsUtil::List<FunctionTypeWeakRef*, Recycler, false, WeakRefFreeListedRemovePolicy> FunctionTypeWeakRefList;
  962. protected:
  963. FunctionProxy(ScriptContext* scriptContext, Utf8SourceInfo* utf8SourceInfo, uint functionNumber);
  964. DEFINE_VTABLE_CTOR_NOBASE(FunctionProxy);
  965. enum class AuxPointerType : uint8 {
  966. DeferredStubs = 0,
  967. CachedSourceString = 1,
  968. AsmJsFunctionInfo = 2,
  969. AsmJsModuleInfo = 3,
  970. StatementMaps = 4,
  971. StackNestedFuncParent = 5,
  972. SimpleJitEntryPointInfo = 6,
  973. FunctionObjectTypeList = 7, // Script function types not including the deferred prototype type
  974. CodeGenGetSetRuntimeData = 8,
  975. PropertyIdOnRegSlotsContainer = 9, // This is used for showing locals for the current frame.
  976. LoopHeaderArray = 10,
  977. CodeGenRuntimeData = 11,
  978. PolymorphicInlineCachesHead = 12, // DList of all polymorphic inline caches that aren't finalized yet
  979. PropertyIdsForScopeSlotArray = 13, // For SourceInfo
  980. PolymorphicCallSiteInfoHead = 14,
  981. AuxBlock = 15, // Optional auxiliary information
  982. AuxContextBlock = 16, // Optional auxiliary context specific information
  983. ReferencedPropertyIdMap = 17,
  984. LiteralRegexes = 18,
  985. ObjLiteralTypes = 19,
  986. ScopeInfo = 20,
  987. FormalsPropIdArray = 21,
  988. ForInCacheArray = 22,
  989. SlotIdInCachedScopeToNestedIndexArray = 23,
  990. Max,
  991. Invalid = 0xff
  992. };
  993. typedef AuxPtrs<FunctionProxy, AuxPointerType> AuxPtrsT;
  994. friend AuxPtrsT;
  995. FieldWithBarrier(AuxPtrsT*) auxPtrs;
  996. void* GetAuxPtr(AuxPointerType e) const;
  997. void* GetAuxPtrWithLock(AuxPointerType e) const;
  998. void SetAuxPtr(AuxPointerType e, void* ptr);
  999. FieldWithBarrier(FunctionInfo *) functionInfo;
  1000. public:
  1001. enum SetDisplayNameFlags
  1002. {
  1003. SetDisplayNameFlagsNone = 0,
  1004. SetDisplayNameFlagsDontCopy = 1,
  1005. SetDisplayNameFlagsRecyclerAllocated = 2
  1006. };
  1007. virtual void Dispose(bool isShutdown) override
  1008. {
  1009. }
  1010. virtual void Mark(Recycler *recycler) override { AssertMsg(false, "Mark called on object that isn't TrackableObject"); }
  1011. static const uint GetOffsetOfFunctionInfo() { return offsetof(FunctionProxy, functionInfo); }
  1012. FunctionInfo * GetFunctionInfo() const
  1013. {
  1014. return this->functionInfo;
  1015. }
  1016. void SetFunctionInfo(FunctionInfo * functionInfo)
  1017. {
  1018. this->functionInfo = functionInfo;
  1019. }
  1020. LocalFunctionId GetLocalFunctionId() const;
  1021. void SetLocalFunctionId(LocalFunctionId functionId);
  1022. ParseableFunctionInfo* GetParseableFunctionInfo() const;
  1023. void SetParseableFunctionInfo(ParseableFunctionInfo* func);
  1024. DeferDeserializeFunctionInfo* GetDeferDeserializeFunctionInfo() const;
  1025. FunctionBody * GetFunctionBody() const;
  1026. void VerifyOriginalEntryPoint() const;
  1027. JavascriptMethod GetOriginalEntryPoint() const;
  1028. JavascriptMethod GetOriginalEntryPoint_Unchecked() const;
  1029. void SetOriginalEntryPoint(const JavascriptMethod originalEntryPoint);
  1030. bool IsAsync() const;
  1031. bool IsDeferred() const;
  1032. bool IsLambda() const;
  1033. bool IsConstructor() const;
  1034. bool IsGenerator() const;
  1035. bool IsClassConstructor() const;
  1036. bool IsClassMethod() const;
  1037. bool IsModule() const;
  1038. bool IsWasmFunction() const;
  1039. bool HasSuperReference() const;
  1040. bool IsCoroutine() const;
  1041. bool GetCapturesThis() const;
  1042. void SetCapturesThis();
  1043. bool GetEnclosedByGlobalFunc() const;
  1044. void SetEnclosedByGlobalFunc();
  1045. bool CanBeDeferred() const;
  1046. BOOL IsDeferredDeserializeFunction() const;
  1047. BOOL IsDeferredParseFunction() const;
  1048. FunctionInfo::Attributes GetAttributes() const;
  1049. void SetAttributes(FunctionInfo::Attributes attributes);
  1050. Recycler* GetRecycler() const;
  1051. uint32 GetSourceContextId() const;
  1052. char16* GetDebugNumberSet(wchar(&bufferToWriteTo)[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]) const;
  1053. bool GetIsTopLevel() { return m_isTopLevel; }
  1054. void SetIsTopLevel(bool set) { m_isTopLevel = set; }
  1055. bool GetIsAnonymousFunction() const { return this->GetDisplayName() == Js::Constants::AnonymousFunction; }
  1056. void Copy(FunctionProxy* other);
  1057. ParseableFunctionInfo* EnsureDeserialized();
  1058. ScriptContext* GetScriptContext() const;
  1059. Utf8SourceInfo* GetUtf8SourceInfo() const { return this->m_utf8SourceInfo; }
  1060. void SetUtf8SourceInfo(Utf8SourceInfo* utf8SourceInfo) { m_utf8SourceInfo = utf8SourceInfo; }
  1061. bool IsInDebugMode() const { return this->m_utf8SourceInfo->IsInDebugMode(); }
  1062. DWORD_PTR GetSecondaryHostSourceContext() const;
  1063. DWORD_PTR GetHostSourceContext() const;
  1064. SourceContextInfo * GetSourceContextInfo() const;
  1065. SRCINFO const * GetHostSrcInfo() const;
  1066. uint GetFunctionNumber() const { return m_functionNumber; }
  1067. virtual void Finalize(bool isShutdown) override;
  1068. void UpdateFunctionBodyImpl(FunctionBody* body);
  1069. bool IsFunctionBody() const;
  1070. uint GetCompileCount() const;
  1071. void SetCompileCount(uint count);
  1072. ProxyEntryPointInfo* GetDefaultEntryPointInfo() const;
  1073. ScriptFunctionType * GetDeferredPrototypeType() const;
  1074. ScriptFunctionType * EnsureDeferredPrototypeType();
  1075. JavascriptMethod GetDirectEntryPoint(ProxyEntryPointInfo* entryPoint) const;
  1076. // Function object type list methods
  1077. FunctionTypeWeakRefList* EnsureFunctionObjectTypeList();
  1078. FunctionTypeWeakRefList* GetFunctionObjectTypeList() const;
  1079. void SetFunctionObjectTypeList(FunctionTypeWeakRefList* list);
  1080. void RegisterFunctionObjectType(ScriptFunctionType* functionType);
  1081. template <typename Fn>
  1082. void MapFunctionObjectTypes(Fn func);
  1083. static uint GetOffsetOfDeferredPrototypeType() { return static_cast<uint>(offsetof(Js::FunctionProxy, deferredPrototypeType)); }
  1084. static Js::ScriptFunctionType * EnsureFunctionProxyDeferredPrototypeType(FunctionProxy * proxy)
  1085. {
  1086. return proxy->EnsureDeferredPrototypeType();
  1087. }
  1088. void SetIsPublicLibraryCode() { m_isPublicLibraryCode = true; }
  1089. bool IsPublicLibraryCode() const { return m_isPublicLibraryCode; }
  1090. #if DBG
  1091. bool HasValidEntryPoint() const;
  1092. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1093. bool HasValidProfileEntryPoint() const;
  1094. #endif
  1095. bool HasValidNonProfileEntryPoint() const;
  1096. #endif
  1097. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) = 0;
  1098. virtual const char16* GetDisplayName() const = 0;
  1099. virtual uint GetDisplayNameLength() const = 0;
  1100. virtual uint GetShortDisplayNameOffset() const = 0;
  1101. static const char16* WrapWithBrackets(const char16* name, charcount_t sz, ScriptContext* scriptContext);
  1102. // Used only in the library function stringify (toString, DiagGetValueString).
  1103. // If we need more often to give the short name, we should create a member variable which points to the short name
  1104. // this is also now being used for function.name.
  1105. const char16* GetShortDisplayName(charcount_t * shortNameLength);
  1106. bool GetDisplayNameIsRecyclerAllocated() { return m_displayNameIsRecyclerAllocated; }
  1107. bool IsJitLoopBodyPhaseEnabled() const
  1108. {
  1109. // Consider: Allow JitLoopBody in generator functions for loops that do not yield.
  1110. return !PHASE_OFF(JITLoopBodyPhase, this) && !PHASE_OFF(FullJitPhase, this) && !this->IsCoroutine();
  1111. }
  1112. bool IsJitLoopBodyPhaseForced() const
  1113. {
  1114. return
  1115. IsJitLoopBodyPhaseEnabled() &&
  1116. (
  1117. PHASE_FORCE(JITLoopBodyPhase, this)
  1118. #ifdef ENABLE_PREJIT
  1119. || Configuration::Global.flags.Prejit
  1120. #endif
  1121. );
  1122. }
  1123. ULONG GetHostStartLine() const;
  1124. ULONG GetHostStartColumn() const;
  1125. protected:
  1126. // Static method(s)
  1127. static bool SetDisplayName(const char16* srcName, FieldWithBarrier(const char16*)* destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  1128. static bool SetDisplayName(const char16* srcName, const char16** destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  1129. static bool IsConstantFunctionName(const char16* srcName);
  1130. protected:
  1131. FieldNoBarrier(ScriptContext*) m_scriptContext; // Memory context for this function body
  1132. FieldWithBarrier(Utf8SourceInfo*) m_utf8SourceInfo;
  1133. FieldWithBarrier(ScriptFunctionType*) deferredPrototypeType;
  1134. FieldWithBarrier(ProxyEntryPointInfo*) m_defaultEntryPointInfo; // The default entry point info for the function proxy
  1135. FieldWithBarrier(uint) m_functionNumber; // Per thread global function number
  1136. FieldWithBarrier(bool) m_tag11 : 1;
  1137. FieldWithBarrier(bool) m_isTopLevel : 1; // Indicates that this function is top-level function, currently being used in script profiler and debugger
  1138. FieldWithBarrier(bool) m_isPublicLibraryCode: 1; // Indicates this function is public boundary library code that should be visible in JS stack
  1139. FieldWithBarrier(bool) m_canBeDeferred : 1;
  1140. FieldWithBarrier(bool) m_displayNameIsRecyclerAllocated : 1;
  1141. void CleanupFunctionProxyCounters()
  1142. {
  1143. PERF_COUNTER_DEC(Code, TotalFunction);
  1144. }
  1145. ULONG ComputeAbsoluteLineNumber(ULONG relativeLineNumber) const;
  1146. ULONG ComputeAbsoluteColumnNumber(ULONG relativeLineNumber, ULONG relativeColumnNumber) const;
  1147. ULONG GetLineNumberInHostBuffer(ULONG relativeLineNumber) const;
  1148. private:
  1149. ScriptFunctionType * AllocDeferredPrototypeType();
  1150. };
  1151. inline Js::LocalFunctionId FunctionProxy::GetLocalFunctionId() const
  1152. {
  1153. Assert(GetFunctionInfo());
  1154. return GetFunctionInfo()->GetLocalFunctionId();
  1155. }
  1156. inline void FunctionProxy::SetLocalFunctionId(LocalFunctionId functionId)
  1157. {
  1158. Assert(GetFunctionInfo());
  1159. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1160. return GetFunctionInfo()->SetLocalFunctionId(functionId);
  1161. }
  1162. inline void FunctionProxy::VerifyOriginalEntryPoint() const
  1163. {
  1164. Assert(GetFunctionInfo());
  1165. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1166. return GetFunctionInfo()->VerifyOriginalEntryPoint();
  1167. }
  1168. inline JavascriptMethod FunctionProxy::GetOriginalEntryPoint() const
  1169. {
  1170. Assert(GetFunctionInfo());
  1171. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1172. return GetFunctionInfo()->GetOriginalEntryPoint();
  1173. }
  1174. inline JavascriptMethod FunctionProxy::GetOriginalEntryPoint_Unchecked() const
  1175. {
  1176. Assert(GetFunctionInfo());
  1177. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1178. return GetFunctionInfo()->GetOriginalEntryPoint_Unchecked();
  1179. }
  1180. inline void FunctionProxy::SetOriginalEntryPoint(const JavascriptMethod originalEntryPoint)
  1181. {
  1182. Assert(GetFunctionInfo());
  1183. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1184. GetFunctionInfo()->SetOriginalEntryPoint(originalEntryPoint);
  1185. }
  1186. inline bool FunctionProxy::IsAsync() const
  1187. {
  1188. Assert(GetFunctionInfo());
  1189. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1190. return GetFunctionInfo()->IsAsync();
  1191. }
  1192. inline bool FunctionProxy::IsDeferred() const
  1193. {
  1194. Assert(GetFunctionInfo());
  1195. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1196. return GetFunctionInfo()->IsDeferred();
  1197. }
  1198. inline bool FunctionProxy::IsConstructor() const
  1199. {
  1200. Assert(GetFunctionInfo());
  1201. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1202. return GetFunctionInfo()->IsConstructor();
  1203. }
  1204. inline bool FunctionProxy::IsGenerator() const
  1205. {
  1206. Assert(GetFunctionInfo());
  1207. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1208. return GetFunctionInfo()->IsGenerator();
  1209. }
  1210. inline bool FunctionProxy::HasSuperReference() const
  1211. {
  1212. Assert(GetFunctionInfo());
  1213. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1214. return GetFunctionInfo()->HasSuperReference();
  1215. }
  1216. inline bool FunctionProxy::IsCoroutine() const
  1217. {
  1218. Assert(GetFunctionInfo());
  1219. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1220. return GetFunctionInfo()->IsCoroutine();
  1221. }
  1222. inline bool FunctionProxy::GetCapturesThis() const
  1223. {
  1224. Assert(GetFunctionInfo());
  1225. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1226. return GetFunctionInfo()->GetCapturesThis();
  1227. }
  1228. inline void FunctionProxy::SetCapturesThis()
  1229. {
  1230. Assert(GetFunctionInfo());
  1231. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1232. GetFunctionInfo()->SetCapturesThis();
  1233. }
  1234. inline bool FunctionProxy::GetEnclosedByGlobalFunc() const
  1235. {
  1236. Assert(GetFunctionInfo());
  1237. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1238. return GetFunctionInfo()->GetEnclosedByGlobalFunc();
  1239. }
  1240. inline void FunctionProxy::SetEnclosedByGlobalFunc()
  1241. {
  1242. Assert(GetFunctionInfo());
  1243. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1244. GetFunctionInfo()->SetEnclosedByGlobalFunc();
  1245. }
  1246. inline BOOL FunctionProxy::IsDeferredDeserializeFunction() const
  1247. {
  1248. Assert(GetFunctionInfo());
  1249. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1250. return GetFunctionInfo()->IsDeferredDeserializeFunction();
  1251. }
  1252. inline BOOL FunctionProxy::IsDeferredParseFunction() const
  1253. {
  1254. Assert(GetFunctionInfo());
  1255. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1256. return GetFunctionInfo()->IsDeferredParseFunction();
  1257. }
  1258. inline FunctionInfo::Attributes FunctionProxy::GetAttributes() const
  1259. {
  1260. Assert(GetFunctionInfo());
  1261. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1262. return GetFunctionInfo()->GetAttributes();
  1263. }
  1264. inline void FunctionProxy::SetAttributes(FunctionInfo::Attributes attributes)
  1265. {
  1266. Assert(GetFunctionInfo());
  1267. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1268. GetFunctionInfo()->SetAttributes(attributes);
  1269. }
  1270. inline void FunctionProxy::SetParseableFunctionInfo(ParseableFunctionInfo* func)
  1271. {
  1272. Assert(GetFunctionInfo());
  1273. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1274. GetFunctionInfo()->SetParseableFunctionInfo(func);
  1275. }
  1276. inline bool FunctionProxy::IsLambda() const
  1277. {
  1278. Assert(GetFunctionInfo());
  1279. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1280. return GetFunctionInfo()->IsLambda();
  1281. }
  1282. inline bool FunctionProxy::CanBeDeferred() const
  1283. {
  1284. Assert(GetFunctionInfo());
  1285. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1286. return GetFunctionInfo()->CanBeDeferred();
  1287. }
  1288. inline bool FunctionProxy::IsClassConstructor() const
  1289. {
  1290. Assert(GetFunctionInfo());
  1291. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1292. return GetFunctionInfo()->IsClassConstructor();
  1293. }
  1294. inline bool FunctionProxy::IsClassMethod() const
  1295. {
  1296. Assert(GetFunctionInfo());
  1297. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1298. return GetFunctionInfo()->IsClassMethod();
  1299. }
  1300. inline bool FunctionProxy::IsModule() const
  1301. {
  1302. Assert(GetFunctionInfo());
  1303. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1304. return GetFunctionInfo()->IsModule();
  1305. }
  1306. inline uint FunctionProxy::GetCompileCount() const
  1307. {
  1308. Assert(GetFunctionInfo());
  1309. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1310. return GetFunctionInfo()->GetCompileCount();
  1311. }
  1312. inline void FunctionProxy::SetCompileCount(uint count)
  1313. {
  1314. Assert(GetFunctionInfo());
  1315. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1316. GetFunctionInfo()->SetCompileCount(count);
  1317. }
  1318. inline ParseableFunctionInfo* FunctionProxy::GetParseableFunctionInfo() const
  1319. {
  1320. Assert(!IsDeferredDeserializeFunction());
  1321. return (ParseableFunctionInfo*)this;
  1322. }
  1323. inline DeferDeserializeFunctionInfo* FunctionProxy::GetDeferDeserializeFunctionInfo() const
  1324. {
  1325. Assert(IsDeferredDeserializeFunction());
  1326. return (DeferDeserializeFunctionInfo*)this;
  1327. }
  1328. inline FunctionBody * FunctionProxy::GetFunctionBody() const
  1329. {
  1330. AssertOrFailFast(IsFunctionBody());
  1331. return (FunctionBody*)this;
  1332. }
  1333. // Represents a function from the byte code cache which will
  1334. // be deserialized upon use
  1335. class DeferDeserializeFunctionInfo: public FunctionProxy
  1336. {
  1337. friend struct ByteCodeSerializer;
  1338. private:
  1339. DeferDeserializeFunctionInfo(int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes);
  1340. public:
  1341. static DeferDeserializeFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* utf8SourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes);
  1342. virtual void Finalize(bool isShutdown) override;
  1343. FunctionBody* Deserialize();
  1344. virtual const char16* GetDisplayName() const override;
  1345. void SetDisplayName(const char16* displayName);
  1346. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1347. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1348. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1349. LPCWSTR GetSourceInfo(int& lineNumber, int& columnNumber) const;
  1350. private:
  1351. Field(const byte*) m_functionBytes;
  1352. Field(ByteCodeCache*) m_cache;
  1353. Field(const char16 *) m_displayName; // Optional name
  1354. Field(uint) m_displayNameLength;
  1355. Field(uint) m_displayShortNameOffset;
  1356. Field(NativeModule *) m_nativeModule;
  1357. };
  1358. class ParseableFunctionInfo: public FunctionProxy
  1359. {
  1360. friend class ByteCodeBufferReader;
  1361. public:
  1362. enum FunctionBodyFlags : byte
  1363. {
  1364. Flags_None = 0x00,
  1365. Flags_StackNestedFunc = 0x01,
  1366. Flags_HasOrParentHasArguments = 0x02,
  1367. Flags_HasTry = 0x04,
  1368. Flags_HasThis = 0x08,
  1369. Flags_NonUserCode = 0x10,
  1370. Flags_HasOnlyThisStatements = 0x20,
  1371. Flags_HasNoExplicitReturnValue = 0x40, // Returns undefined, i.e. has no return statements or return with no expression
  1372. Flags_HasRestParameter = 0x80
  1373. };
  1374. protected:
  1375. ParseableFunctionInfo(JavascriptMethod method, int nestedFunctionCount, LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint m_displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, Js::PropertyRecordList* propertyRecordList, FunctionBodyFlags flags);
  1376. ParseableFunctionInfo(ParseableFunctionInfo * proxy);
  1377. public:
  1378. struct NestedArray
  1379. {
  1380. NestedArray(uint32 count): nestedCount(count) {}
  1381. Field(uint32) nestedCount;
  1382. Field(FunctionInfo*) functionInfoArray[];
  1383. };
  1384. template<typename Fn>
  1385. void ForEachNestedFunc(Fn fn)
  1386. {
  1387. NestedArray* nestedArray = GetNestedArray();
  1388. if (nestedArray != nullptr)
  1389. {
  1390. for (uint i = 0; i < nestedArray->nestedCount; i++)
  1391. {
  1392. if (!fn(nestedArray->functionInfoArray[i]->GetFunctionProxy(), i))
  1393. {
  1394. break;
  1395. }
  1396. }
  1397. }
  1398. }
  1399. NestedArray* GetNestedArray() const { return nestedArray; }
  1400. uint GetNestedCount() const { return nestedArray == nullptr ? 0 : nestedArray->nestedCount; }
  1401. public:
  1402. static ParseableFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, Utf8SourceInfo* utf8SourceInfo, const char16* displayName, uint m_displayNameLength, uint displayShortNameOffset, Js::PropertyRecordList* propertyRecordList, FunctionInfo::Attributes attributes, FunctionBodyFlags flags);
  1403. static ParseableFunctionInfo* NewDeferredFunctionFromFunctionBody(FunctionBody *functionBody);
  1404. DEFINE_VTABLE_CTOR_NO_REGISTER(ParseableFunctionInfo, FunctionProxy);
  1405. FunctionBody* Parse(ScriptFunction ** functionRef = nullptr, bool isByteCodeDeserialization = false);
  1406. #ifdef ASMJS_PLAT
  1407. FunctionBody* ParseAsmJs(Parser * p, __out CompileScriptException * se, __out ParseNodePtr * ptree);
  1408. #endif
  1409. FunctionBodyFlags GetFlags() const { return flags; }
  1410. static bool GetHasThis(FunctionBodyFlags flags) { return (flags & Flags_HasThis) != 0; }
  1411. bool GetHasThis() const { return GetHasThis(flags); }
  1412. void SetHasThis(bool has) { SetFlags(has, Flags_HasThis); }
  1413. static bool GetHasTry(FunctionBodyFlags flags) { return (flags & Flags_HasTry) != 0; }
  1414. bool GetHasTry() const { return GetHasTry(flags); }
  1415. void SetHasTry(bool has) { SetFlags(has, Flags_HasTry); }
  1416. static bool GetHasOrParentHasArguments(FunctionBodyFlags flags) { return (flags & Flags_HasOrParentHasArguments) != 0; }
  1417. bool GetHasOrParentHasArguments() const { return GetHasOrParentHasArguments(flags); }
  1418. void SetHasOrParentHasArguments(bool has) { SetFlags(has, Flags_HasOrParentHasArguments); }
  1419. static bool DoStackNestedFunc(FunctionBodyFlags flags) { return (flags & Flags_StackNestedFunc) != 0; }
  1420. bool DoStackNestedFunc() const { return DoStackNestedFunc(flags); }
  1421. void SetStackNestedFunc(bool does) { SetFlags(does, Flags_StackNestedFunc); }
  1422. bool IsNonUserCode() const { return (flags & Flags_NonUserCode) != 0; }
  1423. void SetIsNonUserCode(bool set);
  1424. bool GetHasNoExplicitReturnValue() { return (flags & Flags_HasNoExplicitReturnValue) != 0; }
  1425. void SetHasNoExplicitReturnValue(bool has) { SetFlags(has, Flags_HasNoExplicitReturnValue); }
  1426. bool GetHasOnlyThisStmts() const { return (flags & Flags_HasOnlyThisStatements) != 0; }
  1427. void SetHasOnlyThisStmts(bool has) { SetFlags(has, Flags_HasOnlyThisStatements); }
  1428. static bool GetHasRestParameter(FunctionBodyFlags flags) { return (flags & Flags_HasRestParameter) != 0; }
  1429. bool GetHasRestParameter() const { return GetHasRestParameter(flags); }
  1430. void SetHasRestParameter() { SetFlags(true, Flags_HasRestParameter); }
  1431. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1432. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1433. bool GetIsDeclaration() const { return m_isDeclaration; }
  1434. void SetIsDeclaration(const bool is) { m_isDeclaration = is; }
  1435. bool GetIsAccessor() const { return m_isAccessor; }
  1436. void SetIsAccessor(const bool is) { m_isAccessor = is; }
  1437. bool GetIsGlobalFunc() const { return m_isGlobalFunc; }
  1438. void SetIsStaticNameFunction(const bool is) { m_isStaticNameFunction = is; }
  1439. bool GetIsStaticNameFunction() const { return m_isStaticNameFunction; }
  1440. void SetIsNamedFunctionExpression(const bool is) { m_isNamedFunctionExpression = is; }
  1441. bool GetIsNamedFunctionExpression() const { return m_isNamedFunctionExpression; }
  1442. void SetIsNameIdentifierRef (const bool is) { m_isNameIdentifierRef = is; }
  1443. bool GetIsNameIdentifierRef () const { return m_isNameIdentifierRef ; }
  1444. // Fake global ->
  1445. // 1) new Function code's global code
  1446. // 2) global code generated from the reparsing deferred parse function
  1447. bool IsFakeGlobalFunc(uint32 flags) const;
  1448. void SetIsGlobalFunc(bool is) { m_isGlobalFunc = is; }
  1449. bool GetIsStrictMode() const { return m_isStrictMode; }
  1450. void SetIsStrictMode() { m_isStrictMode = true; }
  1451. bool GetIsAsmjsMode() const { return m_isAsmjsMode; }
  1452. void SetIsAsmjsMode(bool value)
  1453. {
  1454. m_isAsmjsMode = value;
  1455. #if DBG
  1456. if (value)
  1457. {
  1458. m_wasEverAsmjsMode = true;
  1459. }
  1460. #endif
  1461. }
  1462. #if DBG
  1463. bool WasEverAsmJsMode() const { return m_wasEverAsmjsMode; }
  1464. #endif
  1465. void SetIsWasmFunction(bool val)
  1466. {
  1467. m_isWasmFunction = val;
  1468. }
  1469. bool IsWasmFunction() const
  1470. {
  1471. return m_isWasmFunction;
  1472. }
  1473. bool GetHasImplicitArgIns() { return m_hasImplicitArgIns; }
  1474. void SetHasImplicitArgIns(bool has) { m_hasImplicitArgIns = has; }
  1475. uint32 GetGrfscr() const;
  1476. void SetGrfscr(uint32 grfscr);
  1477. ///----------------------------------------------------------------------------
  1478. ///
  1479. /// ParseableFunctionInfo::GetInParamsCount
  1480. ///
  1481. /// GetInParamsCount() returns the number of "in parameters" that have
  1482. /// currently been declared for this function:
  1483. /// - If this is "RegSlot_VariableCount", the function takes a variable number
  1484. /// of parameters.
  1485. ///
  1486. /// Consider: Change to store type information about parameters- names, type,
  1487. /// direction, etc.
  1488. ///
  1489. ///----------------------------------------------------------------------------
  1490. ArgSlot GetInParamsCount() const { return m_inParamCount; }
  1491. void SetInParamsCount(ArgSlot newInParamCount);
  1492. ArgSlot GetReportedInParamsCount() const;
  1493. void SetReportedInParamsCount(ArgSlot newReportedInParamCount);
  1494. void ResetInParams();
  1495. ScopeInfo* GetScopeInfo() const { return static_cast<ScopeInfo*>(this->GetAuxPtr(AuxPointerType::ScopeInfo)); }
  1496. void SetScopeInfo(ScopeInfo* scopeInfo) { this->SetAuxPtr(AuxPointerType::ScopeInfo, scopeInfo); }
  1497. PropertyId GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName);
  1498. bool IsTrackedPropertyId(PropertyId pid);
  1499. void SetScopeSlotArraySizes(uint scopeSlotCount, uint scopeSlotCountForParamScope)
  1500. {
  1501. this->scopeSlotArraySize = scopeSlotCount;
  1502. this->paramScopeSlotArraySize = scopeSlotCountForParamScope;
  1503. }
  1504. PropertyId * GetPropertyIdsForScopeSlotArray() const { return static_cast<Js::PropertyId *>(this->GetAuxPtr(AuxPointerType::PropertyIdsForScopeSlotArray)); }
  1505. void SetPropertyIdsForScopeSlotArray(Js::PropertyId * propertyIdsForScopeSlotArray, uint scopeSlotCount, uint scopeSlotCountForParamScope = 0)
  1506. {
  1507. SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1508. this->SetAuxPtr(AuxPointerType::PropertyIdsForScopeSlotArray, propertyIdsForScopeSlotArray);
  1509. }
  1510. Js::PropertyRecordList* GetBoundPropertyRecords() { return this->m_boundPropertyRecords; }
  1511. void SetBoundPropertyRecords(Js::PropertyRecordList* boundPropertyRecords)
  1512. {
  1513. Assert(this->m_boundPropertyRecords == nullptr);
  1514. this->m_boundPropertyRecords = boundPropertyRecords;
  1515. }
  1516. void ClearBoundPropertyRecords()
  1517. {
  1518. this->m_boundPropertyRecords = nullptr;
  1519. }
  1520. void SetInitialDefaultEntryPoint();
  1521. void SetDeferredParsingEntryPoint();
  1522. void SetEntryPoint(ProxyEntryPointInfo* entryPoint, Js::JavascriptMethod jsMethod) {
  1523. entryPoint->jsMethod = jsMethod;
  1524. }
  1525. bool IsDynamicScript() const;
  1526. uint LengthInBytes() const { return m_cbLength; }
  1527. uint StartOffset() const;
  1528. ULONG GetLineNumber() const;
  1529. ULONG GetColumnNumber() const;
  1530. template <class T>
  1531. LPCWSTR GetSourceName(const T& sourceContextInfo) const;
  1532. template <class T>
  1533. static LPCWSTR GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction);
  1534. LPCWSTR GetSourceName() const;
  1535. ULONG GetRelativeLineNumber() const { return m_lineNumber; }
  1536. ULONG GetRelativeColumnNumber() const { return m_columnNumber; }
  1537. uint GetSourceIndex() const;
  1538. LPCUTF8 GetSource(const char16* reason = nullptr) const;
  1539. charcount_t LengthInChars() const { return m_cchLength; }
  1540. charcount_t StartInDocument() const;
  1541. bool IsEval() const { return m_isEval; }
  1542. bool IsDynamicFunction() const;
  1543. bool GetDontInline() { return m_dontInline; }
  1544. void SetDontInline(bool is) { m_dontInline = is; }
  1545. LPCUTF8 GetStartOfDocument(const char16* reason = nullptr) const;
  1546. bool IsReparsed() const { return m_reparsed; }
  1547. void SetReparsed(bool set) { m_reparsed = set; }
  1548. #ifdef NTBUILD
  1549. bool GetExternalDisplaySourceName(BSTR* sourceName);
  1550. #endif
  1551. void CleanupToReparse();
  1552. void CleanupToReparseHelper();
  1553. bool EndsAfter(size_t offset) const;
  1554. void SetDoBackendArgumentsOptimization(bool set)
  1555. {
  1556. m_doBackendArgumentsOptimization = set;
  1557. }
  1558. bool GetDoBackendArgumentsOptimization()
  1559. {
  1560. return m_doBackendArgumentsOptimization;
  1561. }
  1562. void SetDoScopeObjectCreation(bool set)
  1563. {
  1564. m_doScopeObjectCreation = set;
  1565. }
  1566. bool GetDoScopeObjectCreation()
  1567. {
  1568. return m_doScopeObjectCreation;
  1569. }
  1570. void SetUsesArgumentsObject(bool set)
  1571. {
  1572. if (!m_usesArgumentsObject)
  1573. {
  1574. m_usesArgumentsObject = set;
  1575. }
  1576. }
  1577. bool GetUsesArgumentsObject()
  1578. {
  1579. return m_usesArgumentsObject;
  1580. }
  1581. bool IsFunctionParsed()
  1582. {
  1583. return !IsDeferredParseFunction() || m_hasBeenParsed;
  1584. }
  1585. void SetFunctionParsed(bool hasBeenParsed)
  1586. {
  1587. m_hasBeenParsed = hasBeenParsed;
  1588. }
  1589. void SetSourceInfo(uint sourceIndex, ParseNodePtr node, bool isEval, bool isDynamicFunction);
  1590. void SetSourceInfo(uint sourceIndex);
  1591. void Copy(ParseableFunctionInfo * other);
  1592. void Copy(FunctionBody* other);
  1593. void CopyNestedArray(ParseableFunctionInfo * other);
  1594. const char16* GetExternalDisplayName() const;
  1595. //
  1596. // Algorithm to retrieve a function body's external display name. Template supports both
  1597. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1598. //
  1599. template <class T>
  1600. static const char16* GetExternalDisplayName(const T* funcBody)
  1601. {
  1602. Assert(funcBody != nullptr);
  1603. Assert(funcBody->GetDisplayName() != nullptr);
  1604. return funcBody->GetDisplayName();
  1605. }
  1606. virtual const char16* GetDisplayName() const override;
  1607. void SetDisplayName(const char16* displayName);
  1608. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1609. virtual void Finalize(bool isShutdown) override;
  1610. Var GetCachedSourceString() { return this->GetAuxPtr(AuxPointerType::CachedSourceString); }
  1611. void SetCachedSourceString(Var sourceString)
  1612. {
  1613. Assert(this->GetCachedSourceString() == nullptr);
  1614. this->SetAuxPtr(AuxPointerType::CachedSourceString, sourceString);
  1615. }
  1616. FunctionInfoArray GetNestedFuncArray();
  1617. FunctionInfo* GetNestedFunc(uint index);
  1618. FunctionInfoPtrPtr GetNestedFuncReference(uint index);
  1619. FunctionProxy* GetNestedFunctionProxy(uint index);
  1620. ParseableFunctionInfo* GetNestedFunctionForExecution(uint index);
  1621. void SetNestedFunc(FunctionInfo* nestedFunc, uint index, uint32 flags);
  1622. void BuildDeferredStubs(ParseNode *pnodeFnc);
  1623. DeferredFunctionStub *GetDeferredStubs() const { return static_cast<DeferredFunctionStub *>(this->GetAuxPtr(AuxPointerType::DeferredStubs)); }
  1624. void SetDeferredStubs(DeferredFunctionStub *stub) { this->SetAuxPtr(AuxPointerType::DeferredStubs, stub); }
  1625. void RegisterFuncToDiag(ScriptContext * scriptContext, char16 const * pszTitle);
  1626. bool IsES6ModuleCode() const;
  1627. protected:
  1628. static HRESULT MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se);
  1629. void SetFlags(bool does, FunctionBodyFlags newFlags)
  1630. {
  1631. if (does)
  1632. {
  1633. flags = (FunctionBodyFlags)(flags | newFlags);
  1634. }
  1635. else
  1636. {
  1637. flags = (FunctionBodyFlags)(flags & ~newFlags);
  1638. }
  1639. }
  1640. FieldWithBarrier(bool) m_tag21 : 1;
  1641. FieldWithBarrier(bool) m_hasBeenParsed : 1; // Has function body been parsed- true for actual function bodies, false for deferparse
  1642. FieldWithBarrier(bool) m_isDeclaration : 1;
  1643. FieldWithBarrier(bool) m_isAccessor : 1; // Function is a property getter or setter
  1644. FieldWithBarrier(bool) m_isStaticNameFunction : 1;
  1645. FieldWithBarrier(bool) m_isNamedFunctionExpression : 1;
  1646. FieldWithBarrier(bool) m_isNameIdentifierRef : 1;
  1647. FieldWithBarrier(bool) m_isClassMember : 1;
  1648. // 8 bits from last tag
  1649. FieldWithBarrier(bool) m_isStrictMode : 1;
  1650. FieldWithBarrier(bool) m_isAsmjsMode : 1;
  1651. FieldWithBarrier(bool) m_isAsmJsFunction : 1;
  1652. FieldWithBarrier(bool) m_isWasmFunction : 1;
  1653. FieldWithBarrier(bool) m_isGlobalFunc : 1;
  1654. FieldWithBarrier(bool) m_doBackendArgumentsOptimization : 1;
  1655. FieldWithBarrier(bool) m_doScopeObjectCreation : 1;
  1656. FieldWithBarrier(bool) m_usesArgumentsObject : 1;
  1657. // 16 bits from last tag
  1658. FieldWithBarrier(bool) m_isEval : 1; // Source code is in 'eval'
  1659. FieldWithBarrier(bool) m_isDynamicFunction : 1; // Source code is in 'Function'
  1660. FieldWithBarrier(bool) m_hasImplicitArgIns : 1;
  1661. FieldWithBarrier(bool) m_dontInline : 1; // Used by the JIT's inliner
  1662. // Indicates if the function has been reparsed for debug attach/detach scenario.
  1663. FieldWithBarrier(bool) m_reparsed : 1;
  1664. #if DBG
  1665. FieldWithBarrier(bool) m_wasEverAsmjsMode : 1; // has m_isAsmjsMode ever been true
  1666. #endif
  1667. // This field is not required for deferred parsing but because our thunks can't handle offsets > 128 bytes
  1668. // yet, leaving this here for now. We can look at optimizing the function info and function proxy structures some
  1669. // more and also fix our thunks to handle 8 bit offsets
  1670. FieldWithBarrier(bool) m_utf8SourceHasBeenSet; // start of UTF8-encoded source
  1671. FieldWithBarrier(uint) m_sourceIndex; // index into the scriptContext's list of saved sources
  1672. #if DYNAMIC_INTERPRETER_THUNK
  1673. FieldNoBarrier(void*) m_dynamicInterpreterThunk; // Unique 'thunk' for every interpreted function - used for ETW symbol decoding.
  1674. #endif
  1675. FieldWithBarrier(uint) m_cbStartOffset; // pUtf8Source is this many bytes from the start of the scriptContext's source buffer.
  1676. // This is generally the same as m_cchStartOffset unless the buffer has a BOM
  1677. #define DEFINE_PARSEABLE_FUNCTION_INFO_FIELDS 1
  1678. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1679. #define CURRENT_ACCESS_MODIFIER protected:
  1680. #include "SerializableFunctionFields.h"
  1681. FieldWithBarrier(ULONG) m_lineNumber;
  1682. FieldWithBarrier(ULONG) m_columnNumber;
  1683. FieldWithBarrier(const char16*) m_displayName; // Optional name
  1684. FieldWithBarrier(uint) m_displayNameLength;
  1685. FieldWithBarrier(PropertyRecordList*) m_boundPropertyRecords;
  1686. FieldWithBarrier(NestedArray*) nestedArray;
  1687. public:
  1688. #if DBG
  1689. FieldWithBarrier(Js::LocalFunctionId) deferredParseNextFunctionId;
  1690. #endif
  1691. #if DBG
  1692. FieldWithBarrier(UINT) scopeObjectSize; // If the scope is an activation object - its size
  1693. #endif
  1694. };
  1695. //
  1696. // Algorithm to retrieve a function body's source name (url). Template supports both
  1697. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1698. //
  1699. template <class T>
  1700. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo) const
  1701. {
  1702. return GetSourceName<T>(sourceContextInfo, this->m_isEval, this->m_isDynamicFunction);
  1703. }
  1704. template <class T>
  1705. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction)
  1706. {
  1707. if (sourceContextInfo->IsDynamic())
  1708. {
  1709. if (m_isEval)
  1710. {
  1711. return Constants::EvalCode;
  1712. }
  1713. else if (m_isDynamicFunction)
  1714. {
  1715. return Constants::FunctionCode;
  1716. }
  1717. else
  1718. {
  1719. return Constants::UnknownScriptCode;
  1720. }
  1721. }
  1722. else
  1723. {
  1724. return sourceContextInfo->url;
  1725. }
  1726. }
  1727. class FunctionBody : public ParseableFunctionInfo
  1728. {
  1729. DEFINE_VTABLE_CTOR_NO_REGISTER(FunctionBody, ParseableFunctionInfo);
  1730. friend class ByteCodeBufferBuilder;
  1731. friend class ByteCodeBufferReader;
  1732. #ifdef DYNAMIC_PROFILE_MUTATOR
  1733. friend class ::DynamicProfileMutator;
  1734. friend class ::DynamicProfileMutatorImpl;
  1735. #endif
  1736. friend class RemoteFunctionBody;
  1737. public:
  1738. // same as MachDouble, used in the Func.h
  1739. static const uint DIAGLOCALSLOTSIZE = 8;
  1740. enum class CounterFields : uint8
  1741. {
  1742. VarCount = 0,
  1743. ConstantCount = 1,
  1744. OutParamMaxDepth = 2,
  1745. ByteCodeCount = 3,
  1746. ByteCodeWithoutLDACount = 4,
  1747. ByteCodeInLoopCount = 5,
  1748. LoopCount = 6,
  1749. ForInLoopDepth = 7,
  1750. ProfiledForInLoopCount = 8,
  1751. InlineCacheCount = 9,
  1752. RootObjectLoadInlineCacheStart = 10,
  1753. RootObjectLoadMethodInlineCacheStart = 11,
  1754. RootObjectStoreInlineCacheStart = 12,
  1755. IsInstInlineCacheCount = 13,
  1756. ReferencedPropertyIdCount = 14,
  1757. ObjLiteralCount = 15,
  1758. LiteralRegexCount = 16,
  1759. InnerScopeCount = 17,
  1760. // Following counters uses ((uint32)-1) as default value
  1761. LocalClosureRegister = 18,
  1762. ParamClosureRegister = 19,
  1763. LocalFrameDisplayRegister = 20,
  1764. EnvRegister = 21,
  1765. ThisRegisterForEventHandler = 22,
  1766. FirstInnerScopeRegister = 23,
  1767. FuncExprScopeRegister = 24,
  1768. FirstTmpRegister = 25,
  1769. Max
  1770. };
  1771. private:
  1772. typedef CompactCounters<FunctionBody> CounterT;
  1773. FieldWithBarrier(CounterT) counters;
  1774. friend CounterT;
  1775. public:
  1776. uint32 GetCountField(FunctionBody::CounterFields fieldEnum) const;
  1777. uint32 SetCountField(FunctionBody::CounterFields fieldEnum, uint32 val);
  1778. uint32 IncreaseCountField(FunctionBody::CounterFields fieldEnum);
  1779. #if DBG
  1780. void LockDownCounters() { counters.isLockedDown = true; };
  1781. void UnlockCounters() { counters.isLockedDown = false; };
  1782. #endif
  1783. struct StatementMap
  1784. {
  1785. StatementMap() : isSubexpression(false) {}
  1786. static StatementMap * New(Recycler* recycler)
  1787. {
  1788. return RecyclerNew(recycler, StatementMap);
  1789. }
  1790. FieldWithBarrier(regex::Interval) sourceSpan;
  1791. FieldWithBarrier(regex::Interval) byteCodeSpan;
  1792. FieldWithBarrier(bool) isSubexpression;
  1793. };
  1794. // The type of StatementAdjustmentRecord.
  1795. // A bitmask that can be OR'ed of multiple values of the enum.
  1796. enum StatementAdjustmentType : ushort
  1797. {
  1798. SAT_None = 0,
  1799. // Specifies an adjustment for next statement when going from current to next.
  1800. // Used for transitioning from current stmt to next during normal control-flow,
  1801. // such as offset of Br after if-block when there is else block present,
  1802. // when throw happens inside if and we ignore exceptions (next statement in the list
  1803. // would be 'else' but we need to pass flow control to Br target rather than entering 'else').
  1804. SAT_FromCurrentToNext = 0x01,
  1805. // Specifies an adjustment for beginning of next statement.
  1806. // If there is adjustment record, the statement following it starts at specified offset and not at offset specified in statementMap.
  1807. // Used for set next statement from arbitrary location.
  1808. SAT_NextStatementStart = 0x02,
  1809. SAT_All = SAT_FromCurrentToNext | SAT_NextStatementStart
  1810. };
  1811. class StatementAdjustmentRecord
  1812. {
  1813. uint m_byteCodeOffset;
  1814. StatementAdjustmentType m_adjustmentType;
  1815. public:
  1816. StatementAdjustmentRecord();
  1817. StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset);
  1818. StatementAdjustmentRecord(const StatementAdjustmentRecord& other);
  1819. uint GetByteCodeOffset();
  1820. StatementAdjustmentType GetAdjustmentType();
  1821. };
  1822. // Offset and entry/exit of a block that must be processed in new interpreter frame rather than current.
  1823. // Used for try and catch blocks.
  1824. class CrossFrameEntryExitRecord
  1825. {
  1826. uint m_byteCodeOffset;
  1827. // true means enter, false means exit.
  1828. bool m_isEnterBlock;
  1829. public:
  1830. CrossFrameEntryExitRecord();
  1831. CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  1832. CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other);
  1833. uint GetByteCodeOffset() const;
  1834. bool GetIsEnterBlock();
  1835. };
  1836. typedef JsUtil::List<Js::FunctionBody::StatementMap*, ArenaAllocator> ArenaStatementMapList;
  1837. typedef JsUtil::List<Js::FunctionBody::StatementMap*> StatementMapList;
  1838. // Note: isLeaf = true template param below means that recycler should not be used to dispose the items.
  1839. typedef JsUtil::List<StatementAdjustmentRecord, Recycler, /* isLeaf = */ true> StatementAdjustmentRecordList;
  1840. typedef JsUtil::List<CrossFrameEntryExitRecord, Recycler, /* isLeaf = */ true> CrossFrameEntryExitRecordList;
  1841. // Contains recorded at bytecode generation time information about statements and try-catch blocks.
  1842. // Used by debugger.
  1843. struct AuxStatementData
  1844. {
  1845. // Contains statement adjustment data:
  1846. // For given bytecode, following statement needs an adjustment, see StatementAdjustmentType for details.
  1847. Field(StatementAdjustmentRecordList*) m_statementAdjustmentRecords;
  1848. // Contain data about entry/exit of blocks that cause processing in different interpreter stack frame, such as try or catch.
  1849. Field(CrossFrameEntryExitRecordList*) m_crossFrameBlockEntryExisRecords;
  1850. AuxStatementData();
  1851. };
  1852. class SourceInfo
  1853. {
  1854. friend class RemoteFunctionBody;
  1855. friend class ByteCodeBufferReader;
  1856. friend class ByteCodeBufferBuilder;
  1857. public:
  1858. FieldNoBarrier(SmallSpanSequence*) pSpanSequence;
  1859. FieldWithBarrier(RegSlot) frameDisplayRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1860. FieldWithBarrier(RegSlot) objectRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1861. FieldWithBarrier(ScopeObjectChain*) pScopeObjectChain;
  1862. FieldWithBarrier(ByteBlock*) m_probeBackingBlock; // NULL if no Probes, otherwise a copy of the unmodified the byte-codeblock //Delay
  1863. FieldWithBarrier(int32) m_probeCount; // The number of installed probes (such as breakpoints).
  1864. // List of bytecode offset for the Branch bytecode.
  1865. FieldWithBarrier(AuxStatementData*) m_auxStatementData;
  1866. SourceInfo():
  1867. frameDisplayRegister(0),
  1868. objectRegister(0),
  1869. pScopeObjectChain(nullptr),
  1870. m_probeBackingBlock(nullptr),
  1871. m_probeCount(0),
  1872. m_auxStatementData(nullptr),
  1873. pSpanSequence(nullptr)
  1874. {
  1875. }
  1876. };
  1877. private:
  1878. FieldWithBarrier(ByteBlock*) byteCodeBlock; // Function byte-code for script functions
  1879. FieldWithBarrier(FunctionEntryPointList*) entryPoints;
  1880. FieldWithBarrier(Field(Var)*) m_constTable;
  1881. FieldWithBarrier(void**) inlineCaches;
  1882. FieldWithBarrier(InlineCachePointerArray<PolymorphicInlineCache>) polymorphicInlineCaches; // Contains the latest polymorphic inline caches
  1883. FieldWithBarrier(PropertyId*) cacheIdToPropertyIdMap;
  1884. #if DBG
  1885. #define InlineCacheTypeNone 0x00
  1886. #define InlineCacheTypeInlineCache 0x01
  1887. #define InlineCacheTypeIsInst 0x02
  1888. FieldWithBarrier(byte*) m_inlineCacheTypes;
  1889. #endif
  1890. public:
  1891. PropertyId * GetCacheIdToPropertyIdMap()
  1892. {
  1893. return cacheIdToPropertyIdMap;
  1894. }
  1895. static DWORD GetAsmJsTotalLoopCountOffset() { return offsetof(FunctionBody, m_asmJsTotalLoopCount); }
  1896. #if DBG
  1897. FieldWithBarrier(int) m_DEBUG_executionCount; // Count of outstanding on InterpreterStackFrame
  1898. FieldWithBarrier(bool) m_nativeEntryPointIsInterpreterThunk; // NativeEntry entry point is in fact InterpreterThunk.
  1899. // Set by bgjit in OutOfMemory scenario during codegen.
  1900. #endif
  1901. //#if ENABLE_DEBUG_CONFIG_OPTIONS //TODO: need this?
  1902. FieldWithBarrier(uint) regAllocStoreCount;
  1903. FieldWithBarrier(uint) regAllocLoadCount;
  1904. FieldWithBarrier(uint) callCountStats;
  1905. //#endif
  1906. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1907. //
  1908. // If you add compile-time attributes to this set, be sure to add them to the attributes that are
  1909. // copied in FunctionBody::Clone
  1910. //
  1911. FieldWithBarrier(SourceInfo) m_sourceInfo; // position of the source
  1912. // Data needed by profiler:
  1913. FieldWithBarrier(uint) m_uScriptId; // Delay //Script Block it belongs to. This is function no. of the global function created by engine for each block
  1914. #if DBG
  1915. FieldWithBarrier(int) m_iProfileSession; // Script profile session the meta data of this function is reported to.
  1916. #endif // DEBUG
  1917. // R0 is reserved for the return value, R1 for the root object
  1918. static const RegSlot ReturnValueRegSlot = 0;
  1919. static const RegSlot RootObjectRegSlot = 1;
  1920. static const RegSlot FirstRegSlot = 1;
  1921. // This value be set on the stack (on a particular offset), when the frame value got changed.
  1922. static const int LocalsChangeDirtyValue = 1;
  1923. #define DEFINE_FUNCTION_BODY_FIELDS 1
  1924. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1925. #define CURRENT_ACCESS_MODIFIER public:
  1926. #include "SerializableFunctionFields.h"
  1927. private:
  1928. FieldWithBarrier(uint) inactiveCount;
  1929. // aligned with 8
  1930. FieldWithBarrier(bool) m_tag32 : 1;
  1931. FieldWithBarrier(bool) m_nativeEntryPointUsed : 1; // Code might have been generated but not yet used.
  1932. FieldWithBarrier(bool) hasDoneLoopBodyCodeGen : 1; // Code generated for loop body, but not necessary available to execute yet.
  1933. FieldWithBarrier(bool) m_isFuncRegistered : 1;
  1934. FieldWithBarrier(bool) m_isFuncRegisteredToDiag : 1; // Mentions the function's context is registered with diagprobe.
  1935. FieldWithBarrier(bool) funcEscapes : 1;
  1936. FieldWithBarrier(bool) m_hasBailoutInstrInJittedCode : 1; // Indicates whether function has bailout instructions. Valid only if hasDoneCodeGen is true
  1937. FieldWithBarrier(bool) m_pendingLoopHeaderRelease : 1; // Indicates whether loop headers need to be released
  1938. // 8 bits from last tag
  1939. FieldWithBarrier(bool) hasExecutionDynamicProfileInfo : 1;
  1940. FieldWithBarrier(bool) cleanedUp: 1;
  1941. FieldWithBarrier(bool) sourceInfoCleanedUp: 1;
  1942. FieldWithBarrier(bool) dontRethunkAfterBailout : 1;
  1943. FieldWithBarrier(bool) disableInlineApply : 1;
  1944. FieldWithBarrier(bool) disableInlineSpread : 1;
  1945. FieldWithBarrier(bool) hasHotLoop: 1;
  1946. FieldWithBarrier(bool) wasCalledFromLoop : 1;
  1947. // 16 bits from last tag
  1948. FieldWithBarrier(bool) hasNestedLoop : 1;
  1949. FieldWithBarrier(bool) recentlyBailedOutOfJittedLoopBody : 1;
  1950. FieldWithBarrier(bool) m_firstFunctionObject: 1;
  1951. FieldWithBarrier(bool) m_inlineCachesOnFunctionObject: 1;
  1952. // Used for the debug re-parse. Saves state of function on the first parse, and restores it on a reparse. The state below is either dependent on
  1953. // the state of the script context, or on other factors like whether it was defer parsed or not.
  1954. FieldWithBarrier(bool) m_hasSetIsObject : 1;
  1955. // Used for the debug purpose, this info will be stored (in the non-debug mode), when a function has all locals marked as non-local-referenced.
  1956. // So when we got to no-refresh debug mode, and try to re-use the same function body we can then enforce all locals to be non-local-referenced.
  1957. FieldWithBarrier(bool) m_hasAllNonLocalReferenced : 1;
  1958. FieldWithBarrier(bool) m_hasFunExprNameReference : 1;
  1959. FieldWithBarrier(bool) m_ChildCallsEval : 1;
  1960. // 24 bits from last tag
  1961. FieldWithBarrier(bool) m_CallsEval : 1;
  1962. FieldWithBarrier(bool) m_hasReferenceableBuiltInArguments : 1;
  1963. FieldWithBarrier(bool) m_isParamAndBodyScopeMerged : 1;
  1964. // Used in the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple times for each child function.
  1965. FieldWithBarrier(bool) m_hasDoneAllNonLocalReferenced : 1;
  1966. // Used by the script profiler, once the function compiled is sent this will be set to true.
  1967. FieldWithBarrier(bool) m_hasFunctionCompiledSent : 1;
  1968. FieldWithBarrier(bool) m_isFromNativeCodeModule : 1;
  1969. FieldWithBarrier(bool) m_isPartialDeserializedFunction : 1;
  1970. FieldWithBarrier(bool) m_isAsmJsScheduledForFullJIT : 1;
  1971. // 32 bits from last tag
  1972. FieldWithBarrier(bool) m_tag33 : 1;
  1973. FieldWithBarrier(bool) m_hasLocalClosureRegister : 1;
  1974. FieldWithBarrier(bool) m_hasParamClosureRegister : 1;
  1975. FieldWithBarrier(bool) m_hasLocalFrameDisplayRegister : 1;
  1976. FieldWithBarrier(bool) m_hasEnvRegister : 1;
  1977. FieldWithBarrier(bool) m_hasThisRegisterForEventHandler : 1;
  1978. FieldWithBarrier(bool) m_hasFirstInnerScopeRegister : 1;
  1979. FieldWithBarrier(bool) m_hasFuncExprScopeRegister : 1;
  1980. // 8 bits from last tag
  1981. FieldWithBarrier(bool) m_hasFirstTmpRegister : 1;
  1982. FieldWithBarrier(bool) m_hasActiveReference : 1;
  1983. #if DBG
  1984. FieldWithBarrier(bool) m_isSerialized : 1;
  1985. #endif
  1986. #ifdef PERF_COUNTERS
  1987. FieldWithBarrier(bool) m_isDeserializedFunction : 1;
  1988. #endif
  1989. #if DBG
  1990. // Indicates that nested functions can be allocated on the stack (but may not be)
  1991. FieldWithBarrier(bool) m_canDoStackNestedFunc : 1;
  1992. #endif
  1993. #ifdef IR_VIEWER
  1994. // whether IR Dump is enabled for this function (used by parseIR)
  1995. FieldWithBarrier(bool) m_isIRDumpEnabled : 1;
  1996. FieldWithBarrier(Js::DynamicObject*) m_irDumpBaseObject;
  1997. #endif /* IR_VIEWER */
  1998. FieldWithBarrier(uint8) bailOnMisingProfileCount;
  1999. FieldWithBarrier(uint8) bailOnMisingProfileRejitCount;
  2000. FieldWithBarrier(byte) inlineDepth; // Used by inlining to avoid recursively inlining functions excessively
  2001. FieldWithBarrier(FunctionExecutionStateMachine) executionState;
  2002. // Indicates how many times the function has been entered (so increases by one on each recursive call, decreases by one when we're done)
  2003. FieldWithBarrier(uint) m_depth;
  2004. FieldWithBarrier(uint32) loopInterpreterLimit;
  2005. FieldWithBarrier(uint32) debuggerScopeIndex;
  2006. FieldWithBarrier(uint32) savedPolymorphicCacheState;
  2007. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  2008. //
  2009. // If you add compile-time attributes to the above set, be sure to add them to the attributes that are
  2010. // copied in FunctionBody::Clone
  2011. //
  2012. FieldNoBarrier(Js::ByteCodeCache*) byteCodeCache; // Not GC allocated so naked pointer
  2013. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2014. static bool shareInlineCaches;
  2015. #endif
  2016. FieldWithBarrier(FunctionEntryPointInfo*) defaultFunctionEntryPointInfo;
  2017. #if ENABLE_PROFILE_INFO
  2018. FieldWithBarrier(DynamicProfileInfo*) dynamicProfileInfo;
  2019. #endif
  2020. // select dynamic profile info saved off when we codegen and later
  2021. // used for rejit decisions (see bailout.cpp)
  2022. FieldWithBarrier(BYTE) savedInlinerVersion;
  2023. #if ENABLE_NATIVE_CODEGEN
  2024. FieldWithBarrier(ImplicitCallFlags) savedImplicitCallsFlags;
  2025. #endif
  2026. FunctionBody(ScriptContext* scriptContext, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount, Utf8SourceInfo* sourceInfo,
  2027. uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* propRecordList, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  2028. #ifdef PERF_COUNTERS
  2029. , bool isDeserializedFunction = false
  2030. #endif
  2031. );
  2032. FunctionBody(ParseableFunctionInfo * parseableFunctionInfo);
  2033. void SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, JavascriptMethod directEntryPoint);
  2034. #if DYNAMIC_INTERPRETER_THUNK
  2035. void GenerateDynamicInterpreterThunk();
  2036. #endif
  2037. void CloneByteCodeInto(ScriptContext * scriptContext, FunctionBody *newFunctionBody, uint sourceIndex);
  2038. Js::JavascriptMethod GetEntryPoint(ProxyEntryPointInfo* entryPoint) const { return entryPoint->jsMethod; }
  2039. void CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo);
  2040. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2041. void DumpRegStats(FunctionBody *funcBody);
  2042. #endif
  2043. public:
  2044. FunctionBody(ByteCodeCache* cache, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext):
  2045. ParseableFunctionInfo((JavascriptMethod) nullptr, 0, (LocalFunctionId) 0, sourceInfo, scriptContext, 0, nullptr, 0, 0, FunctionInfo::Attributes::None, nullptr, Flags_None)
  2046. {
  2047. // Dummy constructor- does nothing
  2048. // Must be stack allocated
  2049. // Used during deferred bytecode serialization
  2050. }
  2051. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  2052. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, FunctionInfo::Attributes attributes
  2053. , FunctionBodyFlags flags
  2054. #ifdef PERF_COUNTERS
  2055. , bool isDeserializedFunction
  2056. #endif
  2057. );
  2058. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  2059. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, FunctionInfo::Attributes attributes
  2060. , FunctionBodyFlags flags
  2061. #ifdef PERF_COUNTERS
  2062. , bool isDeserializedFunction
  2063. #endif
  2064. );
  2065. static FunctionBody * NewFromParseableFunctionInfo(ParseableFunctionInfo * info, PropertyRecordList *boundPropertyRecords);
  2066. FunctionEntryPointInfo * GetEntryPointInfo(int index) const;
  2067. FunctionEntryPointInfo * TryGetEntryPointInfo(int index) const;
  2068. bool DoRedeferFunction(uint inactiveThreshold) const;
  2069. void RedeferFunction();
  2070. void RedeferFunctionObjectTypes();
  2071. bool IsActiveFunction(ActiveFunctionSet * pActiveFuncs) const;
  2072. bool TestAndUpdateActiveFunctions(ActiveFunctionSet * pActiveFuncs) const;
  2073. void UpdateActiveFunctionSet(ActiveFunctionSet * pActiveFuncs, FunctionCodeGenRuntimeData *callSiteData) const;
  2074. void UpdateActiveFunctionsForOneDataSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *parentData, Field(FunctionCodeGenRuntimeData*)* dataSet, uint count) const;
  2075. uint GetInactiveCount() const { return inactiveCount; }
  2076. void SetInactiveCount(uint count) { inactiveCount = count; }
  2077. void IncrInactiveCount(uint increment);
  2078. bool InterpretedSinceCallCountCollection() const;
  2079. void CollectInterpretedCounts();
  2080. void ResetRedeferralAttributes() { this->m_hasActiveReference = false; }
  2081. Js::RootObjectBase * LoadRootObject() const;
  2082. Js::RootObjectBase * GetRootObject() const;
  2083. ByteBlock* GetAuxiliaryData() const { return static_cast<ByteBlock*>(this->GetAuxPtr(AuxPointerType::AuxBlock)); }
  2084. ByteBlock* GetAuxiliaryDataWithLock() const { return static_cast<ByteBlock*>(this->GetAuxPtrWithLock(AuxPointerType::AuxBlock)); }
  2085. void SetAuxiliaryData(ByteBlock* auxBlock) { this->SetAuxPtr(AuxPointerType::AuxBlock, auxBlock); }
  2086. ByteBlock* GetAuxiliaryContextData()const { return static_cast<ByteBlock*>(this->GetAuxPtr(AuxPointerType::AuxContextBlock)); }
  2087. ByteBlock* GetAuxiliaryContextDataWithLock()const { return static_cast<ByteBlock*>(this->GetAuxPtrWithLock(AuxPointerType::AuxContextBlock)); }
  2088. void SetAuxiliaryContextData(ByteBlock* auxContextBlock) { this->SetAuxPtr(AuxPointerType::AuxContextBlock, auxContextBlock); }
  2089. void SetFormalsPropIdArray(PropertyIdArray * propIdArray);
  2090. PropertyIdArray* GetFormalsPropIdArray(bool checkForNull = true);
  2091. Var GetFormalsPropIdArrayOrNullObj();
  2092. ByteBlock* GetByteCode() const;
  2093. ByteBlock* GetOriginalByteCode(); // Returns original bytecode without probes (such as BPs).
  2094. Js::ByteCodeCache * GetByteCodeCache() const { return this->byteCodeCache; }
  2095. void SetByteCodeCache(Js::ByteCodeCache *byteCodeCache)
  2096. {
  2097. if (byteCodeCache != nullptr)
  2098. {
  2099. this->byteCodeCache = byteCodeCache;
  2100. }
  2101. }
  2102. #if DBG
  2103. void SetIsSerialized(bool serialized) { m_isSerialized = serialized; }
  2104. bool GetIsSerialized()const { return m_isSerialized; }
  2105. #endif
  2106. uint GetByteCodeCount() const { return GetCountField(CounterFields::ByteCodeCount); }
  2107. void SetByteCodeCount(uint count) { SetCountField(CounterFields::ByteCodeCount, count); }
  2108. uint GetByteCodeWithoutLDACount() const { return GetCountField(CounterFields::ByteCodeWithoutLDACount); }
  2109. void SetByteCodeWithoutLDACount(uint count) { SetCountField(CounterFields::ByteCodeWithoutLDACount, count); }
  2110. uint GetByteCodeInLoopCount() const { return GetCountField(CounterFields::ByteCodeInLoopCount); }
  2111. void SetByteCodeInLoopCount(uint count) { SetCountField(CounterFields::ByteCodeInLoopCount, count); }
  2112. uint16 GetEnvDepth() const { return m_envDepth; }
  2113. void SetEnvDepth(uint16 depth) { m_envDepth = depth; }
  2114. void SetEnvRegister(RegSlot reg);
  2115. void MapAndSetEnvRegister(RegSlot reg);
  2116. RegSlot GetEnvRegister() const;
  2117. void SetThisRegisterForEventHandler(RegSlot reg);
  2118. void MapAndSetThisRegisterForEventHandler(RegSlot reg);
  2119. RegSlot GetThisRegisterForEventHandler() const;
  2120. void SetLocalClosureRegister(RegSlot reg);
  2121. void MapAndSetLocalClosureRegister(RegSlot reg);
  2122. RegSlot GetLocalClosureRegister() const;
  2123. void SetParamClosureRegister(RegSlot reg);
  2124. void MapAndSetParamClosureRegister(RegSlot reg);
  2125. RegSlot GetParamClosureRegister() const;
  2126. void SetLocalFrameDisplayRegister(RegSlot reg);
  2127. void MapAndSetLocalFrameDisplayRegister(RegSlot reg);
  2128. RegSlot GetLocalFrameDisplayRegister() const;
  2129. void SetFirstInnerScopeRegister(RegSlot reg);
  2130. void MapAndSetFirstInnerScopeRegister(RegSlot reg);
  2131. RegSlot GetFirstInnerScopeRegister() const;
  2132. void SetFuncExprScopeRegister(RegSlot reg);
  2133. void MapAndSetFuncExprScopeRegister(RegSlot reg);
  2134. RegSlot GetFuncExprScopeRegister() const;
  2135. bool HasScopeObject() const { return hasScopeObject; }
  2136. void SetHasScopeObject(bool has) { hasScopeObject = has; }
  2137. uint GetInnerScopeCount() const { return GetCountField(CounterFields::InnerScopeCount); }
  2138. void SetInnerScopeCount(uint count) { SetCountField(CounterFields::InnerScopeCount, count); }
  2139. bool HasCachedScopePropIds() const { return hasCachedScopePropIds; }
  2140. void SetHasCachedScopePropIds(bool has) { hasCachedScopePropIds = has; }
  2141. uint32 GetInterpretedCount() const;
  2142. uint32 IncreaseInterpretedCount();
  2143. uint32 GetLoopInterpreterLimit() const { return loopInterpreterLimit; }
  2144. uint32 SetLoopInterpreterLimit(uint32 val) { return loopInterpreterLimit = val; }
  2145. // Gets the next index for tracking debugger scopes (increments the internal counter as well).
  2146. uint32 GetNextDebuggerScopeIndex() { return debuggerScopeIndex++; }
  2147. void SetDebuggerScopeIndex(uint32 index) { debuggerScopeIndex = index; }
  2148. size_t GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars);
  2149. void AllocateLoopHeaders();
  2150. void ReleaseLoopHeaders();
  2151. Js::LoopHeader * GetLoopHeader(uint index) const;
  2152. Js::LoopHeader * GetLoopHeaderWithLock(uint index) const;
  2153. Js::Var GetLoopHeaderArrayPtr() const
  2154. {
  2155. Assert(this->GetLoopHeaderArray() != nullptr);
  2156. return this->GetLoopHeaderArray();
  2157. }
  2158. #ifdef ASMJS_PLAT
  2159. void SetIsAsmJsFullJitScheduled(bool val){ m_isAsmJsScheduledForFullJIT = val; }
  2160. bool GetIsAsmJsFullJitScheduled(){ return m_isAsmJsScheduledForFullJIT; }
  2161. uint32 GetAsmJSTotalLoopCount() const
  2162. {
  2163. return m_asmJsTotalLoopCount;
  2164. }
  2165. void SetIsAsmJsFunction(bool isAsmJsFunction)
  2166. {
  2167. m_isAsmJsFunction = isAsmJsFunction;
  2168. }
  2169. #endif
  2170. const bool GetIsAsmJsFunction() const
  2171. {
  2172. return m_isAsmJsFunction;
  2173. }
  2174. #ifdef ASMJS_PLAT
  2175. bool IsHotAsmJsLoop()
  2176. {
  2177. // Negative MinTemplatizedJitLoopRunCount treats all loops as hot asm loop
  2178. if (CONFIG_FLAG(MinTemplatizedJitLoopRunCount) < 0 || m_asmJsTotalLoopCount > static_cast<uint>(CONFIG_FLAG(MinTemplatizedJitLoopRunCount)))
  2179. {
  2180. return true;
  2181. }
  2182. return false;
  2183. }
  2184. #endif
  2185. private:
  2186. void ResetLoops();
  2187. public:
  2188. static bool Is(void* ptr);
  2189. uint GetScriptId() const { return m_uScriptId; }
  2190. void* GetAddressOfScriptId() const
  2191. {
  2192. return (void*)&m_uScriptId;
  2193. }
  2194. static uint *GetJittedLoopIterationsSinceLastBailoutAddress(EntryPointInfo* info)
  2195. {
  2196. LoopEntryPointInfo* entryPoint = (LoopEntryPointInfo*)info;
  2197. return &entryPoint->jittedLoopIterationsSinceLastBailout;
  2198. }
  2199. FunctionEntryPointInfo* GetDefaultFunctionEntryPointInfo() const;
  2200. void SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint);
  2201. FunctionEntryPointInfo *GetSimpleJitEntryPointInfo() const;
  2202. void SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo);
  2203. ExecutionMode GetDefaultInterpreterExecutionMode() const;
  2204. ExecutionMode GetExecutionMode() const;
  2205. ExecutionMode GetInterpreterExecutionMode(const bool isPostBailout);
  2206. void SetExecutionMode(const ExecutionMode executionMode);
  2207. private:
  2208. bool IsInterpreterExecutionMode() const;
  2209. public:
  2210. bool TryTransitionToNextExecutionMode();
  2211. void TryTransitionToNextInterpreterExecutionMode();
  2212. void SetIsSpeculativeJitCandidate();
  2213. bool TryTransitionToJitExecutionMode();
  2214. void TransitionToSimpleJitExecutionMode();
  2215. void TransitionToFullJitExecutionMode();
  2216. void ReinitializeExecutionModeAndLimits();
  2217. private:
  2218. uint16 GetSimpleJitExecutedIterations() const;
  2219. public:
  2220. void ResetSimpleJitLimitAndCallCount();
  2221. private:
  2222. void SetSimpleJitCallCount(const uint16 simpleJitLimit) const;
  2223. void ResetSimpleJitCallCount();
  2224. public:
  2225. uint16 GetProfiledIterations() const;
  2226. public:
  2227. void OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo);
  2228. public:
  2229. void TraceExecutionMode(const char *const eventDescription = nullptr) const;
  2230. void TraceInterpreterExecutionMode() const;
  2231. private:
  2232. void DoTraceExecutionMode(const char *const eventDescription) const;
  2233. public:
  2234. bool DoSimpleJit() const;
  2235. bool DoSimpleJitWithLock() const;
  2236. bool DoSimpleJitDynamicProfile() const;
  2237. bool DoInterpreterProfile() const;
  2238. bool DoInterpreterProfileWithLock() const;
  2239. bool DoInterpreterAutoProfile() const;
  2240. public:
  2241. bool WasCalledFromLoop() const;
  2242. void SetWasCalledFromLoop();
  2243. public:
  2244. bool RecentlyBailedOutOfJittedLoopBody() const;
  2245. void SetRecentlyBailedOutOfJittedLoopBody(const bool value);
  2246. private:
  2247. static uint16 GetMinProfileIterations();
  2248. public:
  2249. static uint16 GetMinFunctionProfileIterations();
  2250. private:
  2251. static uint GetMinLoopProfileIterations(const uint loopInterpreterLimit);
  2252. public:
  2253. uint GetLoopProfileThreshold(const uint loopInterpreterLimit) const;
  2254. private:
  2255. static uint GetReducedLoopInterpretCount();
  2256. public:
  2257. uint GetLoopInterpretCount(LoopHeader* loopHeader) const;
  2258. private:
  2259. static bool DoObjectHeaderInlining();
  2260. static bool DoObjectHeaderInliningForConstructors();
  2261. public:
  2262. static bool DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity);
  2263. private:
  2264. static bool DoObjectHeaderInliningForObjectLiterals();
  2265. public:
  2266. static bool DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity);
  2267. static bool DoObjectHeaderInliningForObjectLiteral(const PropertyIdArray *const propIds);
  2268. static bool DoObjectHeaderInliningForEmptyObjects();
  2269. public:
  2270. #if DBG
  2271. int GetProfileSession() { return m_iProfileSession; }
  2272. #endif
  2273. virtual void Finalize(bool isShutdown) override;
  2274. virtual void OnMark() override;
  2275. void Cleanup(bool isScriptContextClosing);
  2276. void CleanupSourceInfo(bool isScriptContextClosing);
  2277. template<bool IsScriptContextShutdown>
  2278. void CleanUpInlineCaches();
  2279. void CleanupRecyclerData(bool isRecyclerShutdown, bool doEntryPointCleanupCaptureStack);
  2280. #ifdef PERF_COUNTERS
  2281. void CleanupPerfCounter();
  2282. #endif
  2283. bool HasRejit() const
  2284. {
  2285. if(this->entryPoints)
  2286. {
  2287. return this->entryPoints->Count() > 1;
  2288. }
  2289. return false;
  2290. }
  2291. #pragma region SourceInfo Methods
  2292. void CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo);
  2293. void FinishSourceInfo();
  2294. RegSlot GetFrameDisplayRegister() const;
  2295. void SetFrameDisplayRegister(RegSlot frameDisplayRegister);
  2296. RegSlot GetObjectRegister() const;
  2297. void SetObjectRegister(RegSlot objectRegister);
  2298. bool HasObjectRegister() const { return GetObjectRegister() != 0; }
  2299. ScopeObjectChain *GetScopeObjectChain() const;
  2300. void SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain);
  2301. // fetch the Catch scope object which encloses the passed bytecode offset, returns NULL otherwise
  2302. Js::DebuggerScope * GetDiagCatchScopeObjectAt(int byteCodeOffset);
  2303. ByteBlock *GetProbeBackingBlock();
  2304. void SetProbeBackingBlock(ByteBlock* probeBackingBlock);
  2305. bool HasLineBreak() const;
  2306. bool HasLineBreak(charcount_t start, charcount_t end) const;
  2307. bool HasGeneratedFromByteCodeCache() const { return this->byteCodeCache != nullptr; }
  2308. void TrackLoad(int ichMin);
  2309. SmallSpanSequence* GetStatementMapSpanSequence() const { return m_sourceInfo.pSpanSequence; }
  2310. void RecordStatementMap(StatementMap* statementMap);
  2311. void RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data);
  2312. void RecordLoad(int ichMin, int bytecodeAfterLoad);
  2313. DebuggerScope* RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index = nullptr);
  2314. void RecordEndScopeObject(DebuggerScope* currentScope, int end);
  2315. DebuggerScope* AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  2316. bool TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope);
  2317. StatementMapList * GetStatementMaps() const { return static_cast<StatementMapList *>(this->GetAuxPtrWithLock(AuxPointerType::StatementMaps)); }
  2318. void SetStatementMaps(StatementMapList *pStatementMaps) { this->SetAuxPtr(AuxPointerType::StatementMaps, pStatementMaps); }
  2319. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeData() const { return static_cast<Field(FunctionCodeGenRuntimeData*)*>(this->GetAuxPtr(AuxPointerType::CodeGenGetSetRuntimeData)); }
  2320. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeDataWithLock() const { return static_cast<Field(FunctionCodeGenRuntimeData*)*>(this->GetAuxPtrWithLock(AuxPointerType::CodeGenGetSetRuntimeData)); }
  2321. void SetCodeGenGetSetRuntimeData(FunctionCodeGenRuntimeData** codeGenGetSetRuntimeData) { this->SetAuxPtr(AuxPointerType::CodeGenGetSetRuntimeData, codeGenGetSetRuntimeData); }
  2322. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeData() const { return static_cast<Field(FunctionCodeGenRuntimeData*)*>(this->GetAuxPtr(AuxPointerType::CodeGenRuntimeData)); }
  2323. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeDataWithLock() const { return static_cast<Field(FunctionCodeGenRuntimeData*)*>(this->GetAuxPtrWithLock(AuxPointerType::CodeGenRuntimeData)); }
  2324. void SetCodeGenRuntimeData(FunctionCodeGenRuntimeData** codeGenRuntimeData) { this->SetAuxPtr(AuxPointerType::CodeGenRuntimeData, codeGenRuntimeData); }
  2325. template <typename TStatementMapList>
  2326. static StatementMap * GetNextNonSubexpressionStatementMap(TStatementMapList *statementMapList, int & startingAtIndex);
  2327. static StatementMap * GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex);
  2328. void RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType);
  2329. void RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  2330. // Find out an offset falls within the range. returns TRUE if found.
  2331. BOOL GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record);
  2332. bool GetLineCharOffset(int byteCodeOffset, ULONG* line, LONG* charOffset, bool canAllocateLineCache = true);
  2333. bool GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache = true);
  2334. // Given bytecode position, returns the start position of the statement and length of the statement.
  2335. bool GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength);
  2336. // skip any utf-8/utf-16 byte-order-mark. Returns the number of chars skipped.
  2337. static charcount_t SkipByteOrderMark(__in_bcount_z(4) LPCUTF8& documentStart)
  2338. {
  2339. charcount_t retValue = 0;
  2340. Assert(documentStart != nullptr);
  2341. if (documentStart[0] == 0xEF &&
  2342. documentStart[1] == 0xBB &&
  2343. documentStart[2] == 0xBF)
  2344. {
  2345. // UTF-8 - EF BB BF
  2346. // 3 bytes skipped - reports one char skipped
  2347. documentStart += 3;
  2348. retValue = 1;
  2349. }
  2350. else if ((documentStart[0] == 0xFF && documentStart[1] == 0xFE) ||
  2351. (documentStart[0] == 0xFE && documentStart[1] == 0xFF))
  2352. {
  2353. // UTF-16 LE - FF FE
  2354. // UTF-16 BE - FE FF
  2355. // 2 bytes skipped - reports one char skipped
  2356. documentStart += 2;
  2357. retValue = 1;
  2358. }
  2359. return retValue;
  2360. }
  2361. StatementMap* GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2362. int GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2363. StatementMap* GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2364. StatementMap* GetMatchingStatementMapFromSource(int byteCodeOffset, int* pMapIndex = nullptr);
  2365. void RecordFrameDisplayRegister(RegSlot slot);
  2366. void RecordObjectRegister(RegSlot slot);
  2367. CrossFrameEntryExitRecordList* GetCrossFrameEntryExitRecords();
  2368. #ifdef VTUNE_PROFILING
  2369. uint GetStartOffset(uint statementIndex) const;
  2370. ULONG GetSourceLineNumber(uint statementIndex);
  2371. #endif
  2372. #pragma endregion
  2373. // Field accessors
  2374. bool GetHasBailoutInstrInJittedCode() const { return this->m_hasBailoutInstrInJittedCode; }
  2375. void SetHasBailoutInstrInJittedCode(bool hasBailout) { this->m_hasBailoutInstrInJittedCode = hasBailout; }
  2376. bool GetCanDefer() const { return this->functionInfo->CanBeDeferred() && this->m_depth == 0 && !this->m_hasActiveReference; }
  2377. bool GetCanReleaseLoopHeaders() const { return (this->m_depth == 0); }
  2378. void SetPendingLoopHeaderRelease(bool pendingLoopHeaderRelease) { this->m_pendingLoopHeaderRelease = pendingLoopHeaderRelease; }
  2379. bool GetIsFromNativeCodeModule() const { return m_isFromNativeCodeModule; }
  2380. void SetIsFromNativeCodeModule(bool isFromNativeCodeModule) { m_isFromNativeCodeModule = isFromNativeCodeModule; }
  2381. uint GetLoopNumber(LoopHeader const * loopHeader) const;
  2382. uint GetLoopNumberWithLock(LoopHeader const * loopHeader) const;
  2383. bool GetHasAllocatedLoopHeaders() { return this->GetLoopHeaderArray() != nullptr; }
  2384. Js::LoopHeader* GetLoopHeaderArray() const { return static_cast<Js::LoopHeader*>(this->GetAuxPtr(AuxPointerType::LoopHeaderArray)); }
  2385. Js::LoopHeader* GetLoopHeaderArrayWithLock() const { return static_cast<Js::LoopHeader*>(this->GetAuxPtrWithLock(AuxPointerType::LoopHeaderArray)); }
  2386. void SetLoopHeaderArray(Js::LoopHeader* loopHeaderArray) { this->SetAuxPtr(AuxPointerType::LoopHeaderArray, loopHeaderArray); }
  2387. #if ENABLE_NATIVE_CODEGEN
  2388. Js::JavascriptMethod GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex);
  2389. void SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint, uint loopNum);
  2390. #endif
  2391. void RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPoint, JavascriptMethod oldOriginalEntryPoint, FunctionEntryPointInfo* newEntryPoint);
  2392. FunctionEntryPointInfo* CreateNewDefaultEntryPoint();
  2393. void AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPoint);
  2394. // Kind of entry point for original entry point
  2395. #if DBG
  2396. BOOL IsInterpreterThunk() const;
  2397. BOOL IsDynamicInterpreterThunk() const;
  2398. #endif
  2399. BOOL IsNativeOriginalEntryPoint() const;
  2400. bool IsSimpleJitOriginalEntryPoint() const;
  2401. #if DYNAMIC_INTERPRETER_THUNK
  2402. static BYTE GetOffsetOfDynamicInterpreterThunk() { return static_cast<BYTE>(offsetof(FunctionBody, m_dynamicInterpreterThunk)); }
  2403. void* GetDynamicInterpreterEntryPoint() const
  2404. {
  2405. return m_dynamicInterpreterThunk;
  2406. }
  2407. bool HasInterpreterThunkGenerated() const
  2408. {
  2409. return m_dynamicInterpreterThunk != nullptr;
  2410. }
  2411. DWORD GetDynamicInterpreterThunkSize() const;
  2412. #endif
  2413. bool GetHasHotLoop() const { return hasHotLoop; };
  2414. void SetHasHotLoop();
  2415. bool GetHasNestedLoop() const { return hasNestedLoop; };
  2416. void SetHasNestedLoop(bool nest) { hasNestedLoop = nest; };
  2417. bool IsInlineApplyDisabled();
  2418. void InitDisableInlineApply();
  2419. void SetDisableInlineApply(bool set);
  2420. bool IsInlineSpreadDisabled() const { return disableInlineSpread; }
  2421. void InitDisableInlineSpread() { disableInlineSpread = this->GetLocalFunctionId() != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this); }
  2422. void SetDisableInlineSpread(bool set) { disableInlineSpread = set; }
  2423. bool CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy);
  2424. #if DBG
  2425. bool HasValidSourceInfo();
  2426. #endif
  2427. #if DYNAMIC_INTERPRETER_THUNK
  2428. JavascriptMethod EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo);
  2429. #endif
  2430. void SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint);
  2431. #if ENABLE_NATIVE_CODEGEN
  2432. typedef void (*SetNativeEntryPointFuncType)(FunctionEntryPointInfo* entryPointInfo, Js::FunctionBody * functionBody, Js::JavascriptMethod entryPoint);
  2433. static void DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2434. static void ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2435. bool GetNativeEntryPointUsed() const { return m_nativeEntryPointUsed; }
  2436. void SetNativeEntryPointUsed(bool nativeEntryPointUsed) { this->m_nativeEntryPointUsed = nativeEntryPointUsed; }
  2437. bool GetHasDoneLoopBodyCodeGen() const { return hasDoneLoopBodyCodeGen; }
  2438. void SetHasDoneLoopBodyCodeGen(bool hasDoneLoopBodyCodeGen) { this->hasDoneLoopBodyCodeGen = hasDoneLoopBodyCodeGen; }
  2439. #endif
  2440. bool GetIsFuncRegistered() { return m_isFuncRegistered; }
  2441. void SetIsFuncRegistered(bool isRegistered) { m_isFuncRegistered = isRegistered; }
  2442. bool GetHasLoops() const { return this->GetLoopCount() != 0; }
  2443. uint IncrLoopCount() { return this->IncreaseCountField(CounterFields::LoopCount); }
  2444. uint GetLoopCount() const { return this->GetCountField(CounterFields::LoopCount); }
  2445. uint SetLoopCount(uint count) { return this->SetCountField(CounterFields::LoopCount, count); }
  2446. uint GetForInLoopDepth() const { return this->GetCountField(CounterFields::ForInLoopDepth); }
  2447. uint SetForInLoopDepth(uint count) { return this->SetCountField(CounterFields::ForInLoopDepth, count); }
  2448. bool AllocProfiledForInLoopCount(ProfileId* profileId)
  2449. {
  2450. ProfileId profiledForInLoopCount = this->GetProfiledForInLoopCount();
  2451. if (profiledForInLoopCount != Constants::NoProfileId)
  2452. {
  2453. *profileId = profiledForInLoopCount;
  2454. this->IncreaseCountField(CounterFields::ProfiledForInLoopCount);
  2455. return true;
  2456. }
  2457. return false;
  2458. }
  2459. ProfileId GetProfiledForInLoopCount() const { return (ProfileId)this->GetCountField(CounterFields::ProfiledForInLoopCount); }
  2460. void SetProfiledForInLoopCount(ProfileId count) { this->SetCountField(CounterFields::ProfiledForInLoopCount, count); }
  2461. bool AllocProfiledDivOrRem(ProfileId* profileId) { if (this->profiledDivOrRemCount != Constants::NoProfileId) { *profileId = this->profiledDivOrRemCount++; return true; } return false; }
  2462. ProfileId GetProfiledDivOrRemCount() { return this->profiledDivOrRemCount; }
  2463. bool AllocProfiledSwitch(ProfileId* profileId) { if (this->profiledSwitchCount != Constants::NoProfileId) { *profileId = this->profiledSwitchCount++; return true; } return false; }
  2464. ProfileId GetProfiledSwitchCount() { return this->profiledSwitchCount; }
  2465. bool AllocProfiledCallSiteId(ProfileId* profileId) { if (this->profiledCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledCallSiteCount++; return true; } return false; }
  2466. ProfileId GetProfiledCallSiteCount() const { return this->profiledCallSiteCount; }
  2467. void SetProfiledCallSiteCount(ProfileId callSiteId) { this->profiledCallSiteCount = callSiteId; }
  2468. bool AllocProfiledArrayCallSiteId(ProfileId* profileId) { if (this->profiledArrayCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledArrayCallSiteCount++; return true; } return false; }
  2469. ProfileId GetProfiledArrayCallSiteCount() const { return this->profiledArrayCallSiteCount; }
  2470. bool AllocProfiledReturnTypeId(ProfileId* profileId) { if (this->profiledReturnTypeCount != Constants::NoProfileId) { *profileId = this->profiledReturnTypeCount++; return true; } return false; }
  2471. ProfileId GetProfiledReturnTypeCount() const { return this->profiledReturnTypeCount; }
  2472. bool AllocProfiledSlotId(ProfileId* profileId) { if (this->profiledSlotCount != Constants::NoProfileId) { *profileId = this->profiledSlotCount++; return true; } return false; }
  2473. ProfileId GetProfiledSlotCount() const { return this->profiledSlotCount; }
  2474. ProfileId AllocProfiledLdElemId(ProfileId* profileId) { if (this->profiledLdElemCount != Constants::NoProfileId) { *profileId = this->profiledLdElemCount++; return true; } return false; }
  2475. ProfileId GetProfiledLdElemCount() const { return this->profiledLdElemCount; }
  2476. bool AllocProfiledStElemId(ProfileId* profileId) { if (this->profiledStElemCount != Constants::NoProfileId) { *profileId = this->profiledStElemCount++; return true; } return false; }
  2477. ProfileId GetProfiledStElemCount() const { return this->profiledStElemCount; }
  2478. uint GetProfiledFldCount() const { return this->GetInlineCacheCount(); }
  2479. ArgSlot GetProfiledInParamsCount() const { return this->GetInParamsCount() > 1? this->GetInParamsCount() - 1 : 0; }
  2480. bool IsPartialDeserializedFunction() { return this->m_isPartialDeserializedFunction; }
  2481. #ifdef PERF_COUNTERS
  2482. bool IsDeserializedFunction() { return this->m_isDeserializedFunction; }
  2483. #endif
  2484. #ifdef IR_VIEWER
  2485. bool IsIRDumpEnabled() const { return this->m_isIRDumpEnabled; }
  2486. void SetIRDumpEnabled(bool enabled) { this->m_isIRDumpEnabled = enabled; }
  2487. Js::DynamicObject * GetIRDumpBaseObject();
  2488. #endif /* IR_VIEWER */
  2489. #if ENABLE_NATIVE_CODEGEN
  2490. void SetPolymorphicCallSiteInfoHead(PolymorphicCallSiteInfo *polyCallSiteInfo) { this->SetAuxPtr(AuxPointerType::PolymorphicCallSiteInfoHead, polyCallSiteInfo); }
  2491. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoHead() { return static_cast<PolymorphicCallSiteInfo *>(this->GetAuxPtr(AuxPointerType::PolymorphicCallSiteInfoHead)); }
  2492. #endif
  2493. FunctionBodyPolymorphicInlineCache * GetPolymorphicInlineCachesHead() { return static_cast<FunctionBodyPolymorphicInlineCache *>(this->GetAuxPtr(AuxPointerType::PolymorphicInlineCachesHead)); }
  2494. void SetPolymorphicInlineCachesHead(FunctionBodyPolymorphicInlineCache * cache) { this->SetAuxPtr(AuxPointerType::PolymorphicInlineCachesHead, cache); }
  2495. bool PolyInliningUsingFixedMethodsAllowedByConfigFlags(FunctionBody* topFunctionBody)
  2496. {
  2497. return !PHASE_OFF(Js::InlinePhase, this) && !PHASE_OFF(Js::InlinePhase, topFunctionBody) &&
  2498. !PHASE_OFF(Js::PolymorphicInlinePhase, this) && !PHASE_OFF(Js::PolymorphicInlinePhase, topFunctionBody) &&
  2499. !PHASE_OFF(Js::FixedMethodsPhase, this) && !PHASE_OFF(Js::FixedMethodsPhase, topFunctionBody) &&
  2500. !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, this) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, topFunctionBody);
  2501. }
  2502. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainer() const
  2503. {
  2504. return static_cast<Js::PropertyIdOnRegSlotsContainer *>(this->GetAuxPtr(AuxPointerType::PropertyIdOnRegSlotsContainer));
  2505. }
  2506. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainerWithLock() const
  2507. {
  2508. return static_cast<Js::PropertyIdOnRegSlotsContainer *>(this->GetAuxPtrWithLock(AuxPointerType::PropertyIdOnRegSlotsContainer));
  2509. }
  2510. void SetPropertyIdOnRegSlotsContainer(Js::PropertyIdOnRegSlotsContainer *propertyIdOnRegSlotsContainer)
  2511. {
  2512. this->SetAuxPtr(AuxPointerType::PropertyIdOnRegSlotsContainer, propertyIdOnRegSlotsContainer);
  2513. }
  2514. private:
  2515. void ResetProfileIds();
  2516. public:
  2517. bool GetHasFinally() const { return m_hasFinally; }
  2518. void SetHasFinally(bool has){ m_hasFinally = has; }
  2519. bool GetFuncEscapes() const { return funcEscapes; }
  2520. void SetFuncEscapes(bool does) { funcEscapes = does; }
  2521. #if DBG
  2522. bool CanDoStackNestedFunc() const { return m_canDoStackNestedFunc; }
  2523. void SetCanDoStackNestedFunc() { m_canDoStackNestedFunc = true; }
  2524. #endif
  2525. RecyclerWeakReference<FunctionInfo> * GetStackNestedFuncParent();
  2526. FunctionInfo * GetStackNestedFuncParentStrongRef();
  2527. FunctionInfo * GetAndClearStackNestedFuncParent();
  2528. void ClearStackNestedFuncParent();
  2529. void SetStackNestedFuncParent(FunctionInfo * parentFunctionInfo);
  2530. uint GetScopeSlotArraySize() const
  2531. {
  2532. return scopeSlotArraySize;
  2533. }
  2534. #if defined(_M_IX86) || defined(_M_X64)
  2535. template <typename T>
  2536. static bool DoStackClosure(T functionBody)
  2537. {
  2538. return functionBody->DoStackNestedFunc()
  2539. && functionBody->GetNestedCount() != 0
  2540. && functionBody->GetScopeSlotArraySize() != 0
  2541. && functionBody->GetEnvDepth() != (uint16)-1;
  2542. }
  2543. #else
  2544. template <typename T>
  2545. static bool DoStackClosure(T functionBody)
  2546. {
  2547. return false;
  2548. }
  2549. #endif
  2550. bool DoStackFrameDisplay() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2551. bool DoStackScopeSlots() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2552. bool GetIsFirstFunctionObject() const { return m_firstFunctionObject; }
  2553. void SetIsNotFirstFunctionObject() { m_firstFunctionObject = false; }
  2554. bool GetInlineCachesOnFunctionObject() { return m_inlineCachesOnFunctionObject; }
  2555. void SetInlineCachesOnFunctionObject(bool has) { m_inlineCachesOnFunctionObject = has; }
  2556. bool NeedScopeObjectForArguments(bool hasNonSimpleParams)
  2557. {
  2558. Assert(HasReferenceableBuiltInArguments());
  2559. // We can avoid creating a scope object with arguments present if:
  2560. bool dontNeedScopeObject =
  2561. // Either we are in strict mode, or have strict mode formal semantics from a non-simple parameter list, and
  2562. (GetIsStrictMode() || hasNonSimpleParams)
  2563. // Neither of the scopes are objects
  2564. && !HasScopeObject();
  2565. return
  2566. // Regardless of the conditions above, we won't need a scope object if there aren't any formals.
  2567. (GetInParamsCount() > 1 || GetHasRestParameter())
  2568. && !dontNeedScopeObject;
  2569. }
  2570. uint GetNumberOfRecursiveCallSites();
  2571. bool CanInlineRecursively(uint depth, bool tryAggressive = true);
  2572. public:
  2573. bool CanInlineAgain() const
  2574. {
  2575. // Block excessive recursive inlining of the same function
  2576. return inlineDepth < static_cast<byte>(max(1, min(0xff, CONFIG_FLAG(MaxFuncInlineDepth))));
  2577. }
  2578. void OnBeginInlineInto()
  2579. {
  2580. ++inlineDepth;
  2581. }
  2582. void OnEndInlineInto()
  2583. {
  2584. --inlineDepth;
  2585. }
  2586. uint8 IncrementBailOnMisingProfileCount() { return ++bailOnMisingProfileCount; }
  2587. void ResetBailOnMisingProfileCount() { bailOnMisingProfileCount = 0; }
  2588. uint8 IncrementBailOnMisingProfileRejitCount() { return ++bailOnMisingProfileRejitCount; }
  2589. uint32 GetFrameHeight(EntryPointInfo* entryPointInfo) const;
  2590. void SetFrameHeight(EntryPointInfo* entryPointInfo, uint32 frameHeight);
  2591. RegSlot GetLocalsCount();
  2592. RegSlot GetConstantCount() const { return this->GetCountField(CounterFields::ConstantCount); }
  2593. void CheckAndSetConstantCount(RegSlot cNewConstants);
  2594. void SetConstantCount(RegSlot cNewConstants);
  2595. RegSlot GetVarCount();
  2596. void SetVarCount(RegSlot cNewVars);
  2597. void CheckAndSetVarCount(RegSlot cNewVars);
  2598. RegSlot MapRegSlot(RegSlot reg)
  2599. {
  2600. if (this->RegIsConst(reg))
  2601. {
  2602. reg = CONSTREG_TO_REGSLOT(reg);
  2603. Assert(reg < this->GetConstantCount());
  2604. }
  2605. else
  2606. {
  2607. reg += this->GetConstantCount();
  2608. }
  2609. return reg;
  2610. }
  2611. bool RegIsConst(RegSlot reg) { return reg > REGSLOT_TO_CONSTREG(this->GetConstantCount()); }
  2612. uint32 GetNonTempLocalVarCount();
  2613. uint32 GetFirstNonTempLocalIndex();
  2614. uint32 GetEndNonTempLocalIndex();
  2615. bool IsNonTempLocalVar(uint32 varIndex);
  2616. bool GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp = false);
  2617. RegSlot GetOutParamMaxDepth();
  2618. void SetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2619. void CheckAndSetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2620. RegSlot GetYieldRegister();
  2621. RegSlot GetFirstTmpRegister() const;
  2622. void SetFirstTmpRegister(RegSlot reg);
  2623. RegSlot GetFirstTmpReg();
  2624. void SetFirstTmpReg(RegSlot firstTmpReg);
  2625. RegSlot GetTempCount();
  2626. Js::ModuleID GetModuleID() const;
  2627. void CreateConstantTable();
  2628. void RecordNullObject(RegSlot location);
  2629. void RecordUndefinedObject(RegSlot location);
  2630. void RecordTrueObject(RegSlot location);
  2631. void RecordFalseObject(RegSlot location);
  2632. void RecordIntConstant(RegSlot location, unsigned int val);
  2633. void RecordStrConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool forcePropertyString);
  2634. void RecordFloatConstant(RegSlot location, double d);
  2635. void RecordNullDisplayConstant(RegSlot location);
  2636. void RecordStrictNullDisplayConstant(RegSlot location);
  2637. void InitConstantSlots(Var *dstSlots);
  2638. Var GetConstantVar(RegSlot location);
  2639. Field(Js::Var)* GetConstTable() const { return this->m_constTable; }
  2640. void SetConstTable(Field(Js::Var)* constTable) { this->m_constTable = constTable; }
  2641. void MarkScript(ByteBlock * pblkByteCode, ByteBlock * pblkAuxiliaryData, ByteBlock* auxContextBlock,
  2642. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount);
  2643. void BeginExecution();
  2644. void EndExecution();
  2645. SourceInfo * GetSourceInfo() { return &this->m_sourceInfo; }
  2646. #ifdef ENABLE_SCRIPT_DEBUGGING
  2647. bool InstallProbe(int offset);
  2648. bool UninstallProbe(int offset);
  2649. bool ProbeAtOffset(int offset, OpCode* pOriginalOpcode);
  2650. #endif
  2651. static bool ShouldShareInlineCaches() { return CONFIG_FLAG(ShareInlineCaches); }
  2652. uint GetInlineCacheCount() const { return GetCountField(CounterFields::InlineCacheCount); }
  2653. void SetInlineCacheCount(uint count) { SetCountField(CounterFields::InlineCacheCount, count); }
  2654. uint GetRootObjectLoadInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadInlineCacheStart); }
  2655. void SetRootObjectLoadInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadInlineCacheStart, count); }
  2656. uint GetRootObjectLoadMethodInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart); }
  2657. void SetRootObjectLoadMethodInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart, count); }
  2658. uint GetRootObjectStoreInlineCacheStart() const { return GetCountField(CounterFields::RootObjectStoreInlineCacheStart); }
  2659. void SetRootObjectStoreInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectStoreInlineCacheStart, count); }
  2660. uint GetIsInstInlineCacheCount() const { return GetCountField(CounterFields::IsInstInlineCacheCount); }
  2661. void SetIsInstInlineCacheCount(uint count) { SetCountField(CounterFields::IsInstInlineCacheCount, count); }
  2662. uint GetReferencedPropertyIdCount() const { return GetCountField(CounterFields::ReferencedPropertyIdCount); }
  2663. void SetReferencedPropertyIdCount(uint count) { SetCountField(CounterFields::ReferencedPropertyIdCount, count); }
  2664. uint GetObjLiteralCount() const { return GetCountField(CounterFields::ObjLiteralCount); }
  2665. void SetObjLiteralCount(uint count) { SetCountField(CounterFields::ObjLiteralCount, count); }
  2666. uint IncObjLiteralCount() { return IncreaseCountField(CounterFields::ObjLiteralCount); }
  2667. uint GetLiteralRegexCount() const { return GetCountField(CounterFields::LiteralRegexCount); }
  2668. void SetLiteralRegexCount(uint count) { SetCountField(CounterFields::LiteralRegexCount, count); }
  2669. uint IncLiteralRegexCount() { return IncreaseCountField(CounterFields::LiteralRegexCount); }
  2670. void AllocateForInCache();
  2671. ForInCache * GetForInCache(uint index);
  2672. ForInCache * GetForInCacheArray();
  2673. void CleanUpForInCache(bool isShutdown);
  2674. void AllocateInlineCache();
  2675. InlineCache * GetInlineCache(uint index);
  2676. bool CanFunctionObjectHaveInlineCaches();
  2677. void** GetInlineCaches();
  2678. #if DBG
  2679. byte* GetInlineCacheTypes();
  2680. #endif
  2681. IsInstInlineCache * GetIsInstInlineCache(uint index);
  2682. PolymorphicInlineCache * GetPolymorphicInlineCache(uint index);
  2683. PolymorphicInlineCache * CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache);
  2684. PolymorphicInlineCache * CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId);
  2685. private:
  2686. void ResetInlineCaches();
  2687. PolymorphicInlineCache * CreatePolymorphicInlineCache(uint index, uint16 size);
  2688. FieldWithBarrier(uint32) m_asmJsTotalLoopCount;
  2689. public:
  2690. void CreateCacheIdToPropertyIdMap();
  2691. void CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart, uint rootObjectStoreInlineCacheStart,
  2692. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount);
  2693. void SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId);
  2694. PropertyId GetPropertyIdFromCacheId(uint cacheId)
  2695. {
  2696. Assert(this->cacheIdToPropertyIdMap);
  2697. Assert(cacheId < this->GetInlineCacheCount());
  2698. return this->cacheIdToPropertyIdMap[cacheId];
  2699. }
  2700. #if DBG
  2701. void VerifyCacheIdToPropertyIdMap();
  2702. #endif
  2703. PropertyId* GetReferencedPropertyIdMap() const { return static_cast<PropertyId*>(this->GetAuxPtr(AuxPointerType::ReferencedPropertyIdMap)); }
  2704. PropertyId* GetReferencedPropertyIdMapWithLock() const { return static_cast<PropertyId*>(this->GetAuxPtrWithLock(AuxPointerType::ReferencedPropertyIdMap)); }
  2705. void SetReferencedPropertyIdMap(PropertyId* propIdMap) { this->SetAuxPtr(AuxPointerType::ReferencedPropertyIdMap, propIdMap); }
  2706. void CreateReferencedPropertyIdMap(uint referencedPropertyIdCount);
  2707. void CreateReferencedPropertyIdMap();
  2708. PropertyId GetReferencedPropertyIdWithMapIndex(uint mapIndex);
  2709. PropertyId GetReferencedPropertyIdWithMapIndexWithLock(uint mapIndex);
  2710. void SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId);
  2711. PropertyId GetReferencedPropertyId(uint index);
  2712. PropertyId GetReferencedPropertyIdWithLock(uint index);
  2713. #if DBG
  2714. void VerifyReferencedPropertyIdMap();
  2715. #endif
  2716. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2717. void DumpFullFunctionName();
  2718. void DumpFunctionId(bool pad);
  2719. uint GetTraceFunctionNumber() const;
  2720. #endif
  2721. public:
  2722. uint NewObjectLiteral();
  2723. void AllocateObjectLiteralTypeArray();
  2724. Field(DynamicType*)* GetObjectLiteralTypeRef(uint index);
  2725. Field(DynamicType*)* GetObjectLiteralTypeRefWithLock(uint index);
  2726. uint NewLiteralRegex();
  2727. void AllocateLiteralRegexArray();
  2728. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexes() const { return static_cast<Field(UnifiedRegex::RegexPattern*)*>(this->GetAuxPtr(AuxPointerType::LiteralRegexes)); }
  2729. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexesWithLock() const { return static_cast<Field(UnifiedRegex::RegexPattern*)*>(this->GetAuxPtrWithLock(AuxPointerType::LiteralRegexes)); }
  2730. void SetLiteralRegexs(UnifiedRegex::RegexPattern ** literalRegexes) { this->SetAuxPtr(AuxPointerType::LiteralRegexes, literalRegexes); }
  2731. UnifiedRegex::RegexPattern *GetLiteralRegex(const uint index);
  2732. UnifiedRegex::RegexPattern *GetLiteralRegexWithLock(const uint index);
  2733. #ifdef ASMJS_PLAT
  2734. AsmJsFunctionInfo* GetAsmJsFunctionInfo()const { return static_cast<AsmJsFunctionInfo*>(this->GetAuxPtr(AuxPointerType::AsmJsFunctionInfo)); }
  2735. AsmJsFunctionInfo* GetAsmJsFunctionInfoWithLock()const { return static_cast<AsmJsFunctionInfo*>(this->GetAuxPtrWithLock(AuxPointerType::AsmJsFunctionInfo)); }
  2736. AsmJsFunctionInfo* AllocateAsmJsFunctionInfo();
  2737. AsmJsModuleInfo* GetAsmJsModuleInfo()const { return static_cast<AsmJsModuleInfo*>(this->GetAuxPtr(AuxPointerType::AsmJsModuleInfo)); }
  2738. AsmJsModuleInfo* GetAsmJsModuleInfoWithLock()const { return static_cast<AsmJsModuleInfo*>(this->GetAuxPtrWithLock(AuxPointerType::AsmJsModuleInfo)); }
  2739. void ResetAsmJsInfo()
  2740. {
  2741. SetAuxPtr(AuxPointerType::AsmJsFunctionInfo, nullptr);
  2742. SetAuxPtr(AuxPointerType::AsmJsModuleInfo, nullptr);
  2743. }
  2744. bool IsAsmJSModule()const{ return this->GetAsmJsFunctionInfo() != nullptr; }
  2745. AsmJsModuleInfo* AllocateAsmJsModuleInfo();
  2746. #endif
  2747. void SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern);
  2748. Field(DynamicType*)* GetObjectLiteralTypes() const { return static_cast<Field(DynamicType*)*>(this->GetAuxPtr(AuxPointerType::ObjLiteralTypes)); }
  2749. Field(DynamicType*)* GetObjectLiteralTypesWithLock() const { return static_cast<Field(DynamicType*)*>(this->GetAuxPtrWithLock(AuxPointerType::ObjLiteralTypes)); }
  2750. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArray() const { return static_cast<Js::AuxArray<uint32> *>(this->GetAuxPtr(AuxPointerType::SlotIdInCachedScopeToNestedIndexArray)); }
  2751. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArrayWithLock() const { return static_cast<Js::AuxArray<uint32> *>(this->GetAuxPtrWithLock(AuxPointerType::SlotIdInCachedScopeToNestedIndexArray)); }
  2752. Js::AuxArray<uint32> * AllocateSlotIdInCachedScopeToNestedIndexArray(uint32 slotCount);
  2753. private:
  2754. void ResetLiteralRegexes();
  2755. void ResetObjectLiteralTypes();
  2756. void SetObjectLiteralTypes(DynamicType** objLiteralTypes) { this->SetAuxPtr(AuxPointerType::ObjLiteralTypes, objLiteralTypes); };
  2757. void SetSlotIdInCachedScopeToNestedIndexArray(Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray) { this->SetAuxPtr(AuxPointerType::SlotIdInCachedScopeToNestedIndexArray, slotIdInCachedScopeToNestedIndexArray); }
  2758. void ResetSlotIdInCachedScopeToNestedIndexArray() { SetSlotIdInCachedScopeToNestedIndexArray(nullptr); }
  2759. public:
  2760. void ResetByteCodeGenState();
  2761. void ResetByteCodeGenVisitState();
  2762. void FindClosestStatements(int32 characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation);
  2763. #if ENABLE_NATIVE_CODEGEN
  2764. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2765. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, FunctionBody *inlineeFuncBody) const;
  2766. FunctionCodeGenRuntimeData *EnsureInlineeCodeGenRuntimeData(
  2767. Recycler *const recycler,
  2768. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2769. FunctionBody *const inlinee);
  2770. const FunctionCodeGenRuntimeData *GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const;
  2771. FunctionCodeGenRuntimeData *EnsureLdFldInlineeCodeGenRuntimeData(
  2772. Recycler *const recycler,
  2773. const InlineCacheIndex inlineCacheIndex,
  2774. FunctionBody *const inlinee);
  2775. void LoadDynamicProfileInfo();
  2776. bool HasExecutionDynamicProfileInfo() const { return hasExecutionDynamicProfileInfo; }
  2777. bool HasDynamicProfileInfo() const { return dynamicProfileInfo != nullptr; }
  2778. bool NeedEnsureDynamicProfileInfo() const;
  2779. DynamicProfileInfo * GetDynamicProfileInfo() const { Assert(HasExecutionDynamicProfileInfo()); return dynamicProfileInfo; }
  2780. DynamicProfileInfo * GetAnyDynamicProfileInfo() const { Assert(HasDynamicProfileInfo()); return dynamicProfileInfo; }
  2781. DynamicProfileInfo * EnsureDynamicProfileInfo();
  2782. DynamicProfileInfo * AllocateDynamicProfile();
  2783. BYTE GetSavedInlinerVersion() const;
  2784. uint32 GetSavedPolymorphicCacheState() const;
  2785. void SetSavedPolymorphicCacheState(uint32 state);
  2786. ImplicitCallFlags GetSavedImplicitCallsFlags() const;
  2787. bool HasNonBuiltInCallee();
  2788. void RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 offset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum);
  2789. void SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint);
  2790. BOOL GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2791. BOOL GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2792. FunctionEntryPointInfo * GetEntryPointFromNativeAddress(DWORD_PTR codeAddress);
  2793. LoopEntryPointInfo * GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const;
  2794. #endif
  2795. void InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount);
  2796. void InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount);
  2797. void SetPropertyIdsOfFormals(PropertyIdArray * formalArgs);
  2798. PropertyIdArray * AllocatePropertyIdArrayForFormals(uint32 size, uint32 count, byte extraSlots);
  2799. bool DontRethunkAfterBailout() const { return dontRethunkAfterBailout; }
  2800. void SetDontRethunkAfterBailout() { dontRethunkAfterBailout = true; }
  2801. void ClearDontRethunkAfterBailout() { dontRethunkAfterBailout = false; }
  2802. void SaveState(ParseNodePtr pnode);
  2803. void RestoreState(ParseNodePtr pnode);
  2804. // Used for the debug purpose, this info will be stored (in the non-debug mode), when a function has all locals marked as non-local-referenced.
  2805. // So when we got to no-refresh debug mode, and try to re-use the same function body we can then enforce all locals to be non-local-referenced.
  2806. bool HasAllNonLocalReferenced() const { return m_hasAllNonLocalReferenced; }
  2807. void SetAllNonLocalReferenced(bool set) { m_hasAllNonLocalReferenced = set; }
  2808. bool HasSetIsObject() const { return m_hasSetIsObject; }
  2809. void SetHasSetIsObject(bool set) { m_hasSetIsObject = set; }
  2810. bool HasFuncExprNameReference() const { return m_hasFunExprNameReference; }
  2811. void SetFuncExprNameReference(bool value) { m_hasFunExprNameReference = value; }
  2812. bool GetChildCallsEval() const { return m_ChildCallsEval; }
  2813. void SetChildCallsEval(bool value) { m_ChildCallsEval = value; }
  2814. bool GetCallsEval() const { return m_CallsEval; }
  2815. void SetCallsEval(bool set) { m_CallsEval = set; }
  2816. bool HasReferenceableBuiltInArguments() const { return m_hasReferenceableBuiltInArguments; }
  2817. void SetHasReferenceableBuiltInArguments(bool value) { m_hasReferenceableBuiltInArguments = value; }
  2818. bool IsParamAndBodyScopeMerged() const { return m_isParamAndBodyScopeMerged; }
  2819. void SetParamAndBodyScopeNotMerged() { m_isParamAndBodyScopeMerged = false; }
  2820. // Used for the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple time for each child function.
  2821. bool HasDoneAllNonLocalReferenced() const { return m_hasDoneAllNonLocalReferenced; }
  2822. void SetHasDoneAllNonLocalReferenced(bool set) { m_hasDoneAllNonLocalReferenced = set; }
  2823. // Once the function compiled is sent m_hasFunctionCompiledSent will be set to 'true'. The below check will be used only to determine during ProfileModeDeferredParse function.
  2824. bool HasFunctionCompiledSent() const { return m_hasFunctionCompiledSent; }
  2825. void SetHasFunctionCompiledSent(bool set) { m_hasFunctionCompiledSent = set; }
  2826. #if DBG_DUMP
  2827. void DumpStatementMaps();
  2828. void Dump();
  2829. void PrintStatementSourceLine(uint statementIndex);
  2830. void PrintStatementSourceLineFromStartOffset(uint cchStartOffset);
  2831. void DumpScopes();
  2832. #endif
  2833. uint GetStatementStartOffset(const uint statementIndex);
  2834. #ifdef IR_VIEWER
  2835. void GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2836. ULONG * line, LONG * col);
  2837. void GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2838. ULONG * line, LONG * col);
  2839. #endif
  2840. #if ENABLE_TTD
  2841. void GetSourceLineFromStartOffset_TTD(const uint startOffset, ULONG* line, LONG* col);
  2842. #endif
  2843. #ifdef ENABLE_SCRIPT_PROFILING
  2844. HRESULT RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent = FALSE);
  2845. HRESULT ReportScriptCompiled();
  2846. HRESULT ReportFunctionCompiled();
  2847. void SetEntryToProfileMode();
  2848. #endif
  2849. #ifdef ENABLE_SCRIPT_DEBUGGING
  2850. void CheckAndRegisterFuncToDiag(ScriptContext *scriptContext);
  2851. void SetEntryToDeferParseForDebugger();
  2852. #endif
  2853. void ClearEntryPoints();
  2854. void ResetEntryPoint();
  2855. void CleanupToReparseHelper();
  2856. void AddDeferParseAttribute();
  2857. void RemoveDeferParseAttribute();
  2858. #if DBG
  2859. void MustBeInDebugMode();
  2860. #endif
  2861. static bool IsDummyGlobalRetStatement(const regex::Interval *sourceSpan)
  2862. {
  2863. Assert(sourceSpan != nullptr);
  2864. return sourceSpan->begin == 0 && sourceSpan->end == 0;
  2865. }
  2866. static void GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer);
  2867. template<class Fn>
  2868. void MapLoopHeaders(Fn fn) const
  2869. {
  2870. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2871. if(loopHeaderArray)
  2872. {
  2873. uint loopCount = this->GetLoopCount();
  2874. for(uint i = 0; i < loopCount; i++)
  2875. {
  2876. fn(i , &loopHeaderArray[i]);
  2877. }
  2878. }
  2879. }
  2880. template<class Fn>
  2881. void MapLoopHeadersWithLock(Fn fn) const
  2882. {
  2883. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArrayWithLock();
  2884. if (loopHeaderArray)
  2885. {
  2886. uint loopCount = this->GetLoopCount();
  2887. for (uint i = 0; i < loopCount; i++)
  2888. {
  2889. fn(i, &loopHeaderArray[i]);
  2890. }
  2891. }
  2892. }
  2893. template<class Fn>
  2894. bool MapLoopHeadersUntil(Fn fn) const
  2895. {
  2896. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2897. if (loopHeaderArray)
  2898. {
  2899. uint loopCount = this->GetLoopCount();
  2900. for (uint i = 0; i < loopCount; i++)
  2901. {
  2902. if (fn(i, &loopHeaderArray[i]))
  2903. {
  2904. return true;
  2905. }
  2906. }
  2907. return false;
  2908. }
  2909. return false;
  2910. }
  2911. template <class Fn>
  2912. void MapEntryPoints(Fn fn) const
  2913. {
  2914. if (this->entryPoints)
  2915. {
  2916. this->entryPoints->Map([&fn] (int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2917. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2918. if (strongRef)
  2919. {
  2920. fn(index, strongRef);
  2921. }
  2922. });
  2923. }
  2924. }
  2925. template <class Fn>
  2926. bool MapEntryPointsUntil(Fn fn) const
  2927. {
  2928. if (this->entryPoints)
  2929. {
  2930. return this->entryPoints->MapUntil([&fn](int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2931. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2932. if (strongRef)
  2933. {
  2934. return fn(index, strongRef);
  2935. }
  2936. return false;
  2937. });
  2938. }
  2939. return false;
  2940. }
  2941. bool DoJITLoopBody() const
  2942. {
  2943. return IsJitLoopBodyPhaseEnabled() && this->GetLoopHeaderArrayWithLock() != nullptr;
  2944. }
  2945. bool ForceJITLoopBody() const
  2946. {
  2947. return IsJitLoopBodyPhaseForced() && !this->GetHasTry();
  2948. }
  2949. bool IsGeneratorAndJitIsDisabled()
  2950. {
  2951. return this->IsCoroutine() && !(CONFIG_ISENABLED(Js::JitES6GeneratorsFlag) && !this->GetHasTry());
  2952. }
  2953. FunctionBodyFlags * GetAddressOfFlags() { return &this->flags; }
  2954. Js::RegSlot GetRestParamRegSlot();
  2955. public:
  2956. void RecordConstant(RegSlot location, Var var);
  2957. private:
  2958. inline void CheckEmpty();
  2959. inline void CheckNotExecuting();
  2960. BOOL GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee);
  2961. #if ENABLE_NATIVE_CODEGEN
  2962. int GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset);
  2963. int GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress);
  2964. #endif
  2965. void EnsureAuxStatementData();
  2966. StatementAdjustmentRecordList* GetStatementAdjustmentRecords();
  2967. };
  2968. class AutoRestoreFunctionInfo {
  2969. public:
  2970. AutoRestoreFunctionInfo(ParseableFunctionInfo *pfi, const JavascriptMethod originalEntryPoint) : pfi(pfi), funcBody(nullptr), originalEntryPoint(originalEntryPoint) {}
  2971. ~AutoRestoreFunctionInfo() {
  2972. if (this->pfi != nullptr && this->pfi->GetFunctionInfo()->GetFunctionProxy() != this->pfi)
  2973. {
  2974. FunctionInfo *functionInfo = this->pfi->GetFunctionInfo();
  2975. FunctionBody *functionBody = functionInfo->GetFunctionProxy()->GetFunctionBody();
  2976. functionBody->RedeferFunctionObjectTypes();
  2977. functionInfo->SetAttributes(
  2978. (FunctionInfo::Attributes)(functionInfo->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  2979. functionInfo->SetFunctionProxy(this->pfi);
  2980. functionInfo->SetOriginalEntryPoint(originalEntryPoint);
  2981. }
  2982. Assert(this->pfi == nullptr || (this->pfi->GetFunctionInfo()->GetFunctionProxy() == this->pfi && !this->pfi->IsFunctionBody()));
  2983. }
  2984. void Clear() { pfi = nullptr; funcBody = nullptr; }
  2985. ParseableFunctionInfo * pfi;
  2986. FunctionBody * funcBody;
  2987. const JavascriptMethod originalEntryPoint;
  2988. };
  2989. // If we throw or fail with the function body in an unfinished state, make sure the function info is still
  2990. // pointing to the old ParseableFunctionInfo and has the right attributes.
  2991. typedef SynchronizableList<FunctionBody*, JsUtil::List<FunctionBody*, ArenaAllocator, false, Js::FreeListedRemovePolicy> > FunctionBodyList;
  2992. struct ScopeSlots
  2993. {
  2994. public:
  2995. static uint const MaxEncodedSlotCount = Constants::UShortMaxValue;
  2996. // The slot index is at the same location as the vtable, so that we can distinguish between scope slot and frame display
  2997. static uint const EncodedSlotCountSlotIndex = 0;
  2998. static uint const ScopeMetadataSlotIndex = 1; // Either a FunctionBody* or DebuggerScope*
  2999. static uint const FirstSlotIndex = 2;
  3000. public:
  3001. ScopeSlots(Var* slotArray) : slotArray((Field(Var)*)slotArray)
  3002. {
  3003. }
  3004. bool IsFunctionScopeSlotArray()
  3005. {
  3006. return FunctionInfo::Is(slotArray[ScopeMetadataSlotIndex]);
  3007. }
  3008. FunctionInfo* GetFunctionInfo()
  3009. {
  3010. Assert(IsFunctionScopeSlotArray());
  3011. return (FunctionInfo*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  3012. }
  3013. DebuggerScope* GetDebuggerScope()
  3014. {
  3015. Assert(!IsFunctionScopeSlotArray());
  3016. return (DebuggerScope*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  3017. }
  3018. Var GetScopeMetadataRaw() const
  3019. {
  3020. return slotArray[ScopeMetadataSlotIndex];
  3021. }
  3022. void SetScopeMetadata(Var scopeMetadataObj)
  3023. {
  3024. slotArray[ScopeMetadataSlotIndex] = scopeMetadataObj;
  3025. }
  3026. size_t GetCount() const
  3027. {
  3028. return ::Math::PointerCastToIntegralTruncate<size_t>(slotArray[EncodedSlotCountSlotIndex]);
  3029. }
  3030. void SetCount(uint count)
  3031. {
  3032. slotArray[EncodedSlotCountSlotIndex] = (Var)min<uint>(count, ScopeSlots::MaxEncodedSlotCount);
  3033. }
  3034. Var Get(uint i) const
  3035. {
  3036. Assert(i < GetCount());
  3037. return slotArray[i + FirstSlotIndex];
  3038. }
  3039. void Set(uint i, Var value)
  3040. {
  3041. Assert(i < GetCount());
  3042. slotArray[i + FirstSlotIndex] = value;
  3043. }
  3044. template<class Fn>
  3045. void Map(Fn fn)
  3046. {
  3047. uint count = GetCount();
  3048. for(uint i = 0; i < count; i++)
  3049. {
  3050. fn(GetSlot[i]);
  3051. }
  3052. }
  3053. // The first pointer sized value in the object for scope slots is the count, while it is a vtable
  3054. // for Activation object or with scope (a recyclable object)
  3055. // VTable values are always > 64K because they are a pointer, hence anything less than that implies
  3056. // a slot array.
  3057. // CONSIDER: Use TaggedInt instead of range of slot count to distinguish slot array with others.
  3058. static bool Is(void* object)
  3059. {
  3060. size_t slotCount = *((size_t*)object);
  3061. if(slotCount <= MaxEncodedSlotCount)
  3062. {
  3063. return true;
  3064. }
  3065. return false;
  3066. }
  3067. private:
  3068. Field(Field(Var)*) slotArray;
  3069. };
  3070. enum ScopeType
  3071. {
  3072. ScopeType_ActivationObject,
  3073. ScopeType_SlotArray,
  3074. ScopeType_WithScope
  3075. };
  3076. // A FrameDisplay encodes a FunctionObject's scope chain. It is an array of scopes, where each scope can be either an inline slot array
  3077. // or a RecyclableObject. A FrameDisplay for a given FunctionObject will consist of the FrameDisplay from it's enclosing scope, with any additional
  3078. // scopes prepended. Due to with statements etc. a function may introduce multiple scopes to the FrameDisplay.
  3079. struct FrameDisplay
  3080. {
  3081. FrameDisplay(uint16 len, bool strictMode = false) :
  3082. tag(true),
  3083. length(len),
  3084. strictMode(strictMode)
  3085. #if _M_X64
  3086. , unused(0)
  3087. #endif
  3088. {
  3089. }
  3090. void SetTag(bool tag) { this->tag = tag; }
  3091. void SetItem(uint index, void* item);
  3092. void *GetItem(uint index);
  3093. uint16 GetLength() const { return length; }
  3094. void SetLength(uint16 len) { this->length = len; }
  3095. bool GetStrictMode() const { return strictMode; }
  3096. void SetStrictMode(bool flag) { this->strictMode = flag; }
  3097. void** GetDataAddress() { return (void**)&this->scopes; }
  3098. static uint32 GetOffsetOfStrictMode() { return offsetof(FrameDisplay, strictMode); }
  3099. static uint32 GetOffsetOfLength() { return offsetof(FrameDisplay, length); }
  3100. static uint32 GetOffsetOfScopes() { return offsetof(FrameDisplay, scopes); }
  3101. static ScopeType GetScopeType(void* scope);
  3102. private:
  3103. Field(bool) tag; // Tag it so that the NativeCodeGenerator::IsValidVar would not think this is var
  3104. Field(bool) strictMode;
  3105. Field(uint16) length;
  3106. #if defined(_M_X64_OR_ARM64)
  3107. Field(uint32) unused;
  3108. #endif
  3109. Field(void*) scopes[];
  3110. };
  3111. #pragma region Function Body helper classes
  3112. #pragma region Debugging related source classes
  3113. // Contains only the beginning part of the statement. This will mainly used in SmallSpanSequence which will further be compressed
  3114. // and stored in the buffer
  3115. struct StatementData
  3116. {
  3117. StatementData()
  3118. : sourceBegin(0),
  3119. bytecodeBegin(0)
  3120. {
  3121. }
  3122. int sourceBegin;
  3123. int bytecodeBegin;
  3124. };
  3125. struct StatementLocation
  3126. {
  3127. Js::FunctionBody* function;
  3128. regex::Interval statement;
  3129. regex::Interval bytecodeSpan;
  3130. };
  3131. // Small span in the Statement buffer of the SmallSpanSequence
  3132. struct SmallSpan
  3133. {
  3134. ushort sourceBegin;
  3135. ushort bytecodeBegin;
  3136. SmallSpan(uint32 val)
  3137. {
  3138. sourceBegin = (ushort)(val >> 16);
  3139. bytecodeBegin = (ushort)(val & 0x0000FFFF);
  3140. }
  3141. operator unsigned int()
  3142. {
  3143. return (uint32)sourceBegin << 16 | bytecodeBegin;
  3144. }
  3145. };
  3146. // Iterator which contains the state at particular index. These values will used when fetching next item from
  3147. // SmallSpanSequence
  3148. class SmallSpanSequenceIter
  3149. {
  3150. friend class SmallSpanSequence;
  3151. public:
  3152. SmallSpanSequenceIter()
  3153. : accumulatedIndex(-1),
  3154. accumulatedSourceBegin(0),
  3155. accumulatedBytecodeBegin(0),
  3156. indexOfActualOffset(0)
  3157. {
  3158. }
  3159. // Below are used for fast access when the last access happened nearby.
  3160. // so the actual index would be accumulatedIndex / 2 + (remainder for which byte).
  3161. int accumulatedIndex;
  3162. int accumulatedSourceBegin;
  3163. int accumulatedBytecodeBegin;
  3164. int indexOfActualOffset;
  3165. };
  3166. struct ThrowMapEntry
  3167. {
  3168. uint32 nativeBufferOffset;
  3169. uint32 statementIndex;
  3170. };
  3171. // This class compacts the range of the statement to BYTEs instead of ints.
  3172. // Instead of having start and end as int32s we will have them stored in bytes, and they will be
  3173. // treated as start offset and end offset.
  3174. // For simplicity, this class should be heap allocated, since it can be allocated from either the background
  3175. // or main thread.
  3176. class SmallSpanSequence
  3177. {
  3178. private:
  3179. BOOL GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data);
  3180. ushort GetDiff(int current, int prev);
  3181. public:
  3182. // Each item in the list contains two set of begins (one for bytecode and for sourcespan).
  3183. // The allowed valued for source and bytecode span is in between SHORT_MAX - 1 to SHORT_MIN (inclusive).
  3184. // otherwise its a miss
  3185. JsUtil::GrowingUint32HeapArray * pStatementBuffer;
  3186. // Contains list of values which are missed in StatementBuffer.
  3187. JsUtil::GrowingUint32HeapArray * pActualOffsetList;
  3188. // The first value of the sequence
  3189. int baseValue;
  3190. SmallSpanSequence();
  3191. ~SmallSpanSequence()
  3192. {
  3193. Cleanup();
  3194. }
  3195. void Cleanup()
  3196. {
  3197. if (pStatementBuffer != nullptr)
  3198. {
  3199. HeapDelete(pStatementBuffer);
  3200. pStatementBuffer = nullptr;
  3201. }
  3202. if (pActualOffsetList != nullptr)
  3203. {
  3204. HeapDelete(pActualOffsetList);
  3205. pActualOffsetList = nullptr;
  3206. }
  3207. }
  3208. // Trys to match passed bytecode in the statement, and returns the statement which includes that.
  3209. BOOL GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data);
  3210. // Record the statement data in the statement buffer in the compressed manner.
  3211. BOOL RecordARange(SmallSpanSequenceIter &iter, StatementData * data);
  3212. // Reset the accumulator's state and value.
  3213. void Reset(SmallSpanSequenceIter &iter);
  3214. uint32 Count() const { return pStatementBuffer ? pStatementBuffer->Count() : 0; }
  3215. BOOL Item(int index, SmallSpanSequenceIter &iter, StatementData &data);
  3216. // Below function will not change any state, so it will not alter accumulated index and value
  3217. BOOL Seek(int index, StatementData & data);
  3218. };
  3219. #pragma endregion
  3220. // This container represent the property ids for the locals which are placed at direct slot
  3221. // and list of formals args if user has not used the arguments object in the script for the current function
  3222. struct PropertyIdOnRegSlotsContainer
  3223. {
  3224. Field(PropertyId *) propertyIdsForRegSlots;
  3225. Field(uint) length;
  3226. // This keeps the upper bound of register slots for the formals. While emitting locals in the body we skip
  3227. // the properties that are below this limit.
  3228. Field(RegSlot) formalsUpperBound;
  3229. Field(PropertyIdArray *) propertyIdsForFormalArgs;
  3230. PropertyIdOnRegSlotsContainer();
  3231. static PropertyIdOnRegSlotsContainer * New(Recycler * recycler);
  3232. void CreateRegSlotsArray(Recycler * recycler, uint _length);
  3233. void SetFormalArgs(PropertyIdArray * formalArgs);
  3234. // Helper methods
  3235. void Insert(RegSlot reg, PropertyId propId);
  3236. void FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot);
  3237. // Whether reg belongs to non-temp locals
  3238. bool IsRegSlotFormal(RegSlot reg);
  3239. };
  3240. // Flags for the DebuggerScopeProperty object.
  3241. typedef int DebuggerScopePropertyFlags;
  3242. const int DebuggerScopePropertyFlags_None = 0x000000000;
  3243. const int DebuggerScopePropertyFlags_Const = 0x000000001;
  3244. const int DebuggerScopePropertyFlags_CatchObject = 0x000000002;
  3245. const int DebuggerScopePropertyFlags_WithObject = 0x000000004;
  3246. const int DebuggerScopePropertyFlags_ForInOrOfCollection = 0x000000008;
  3247. const int DebuggerScopePropertyFlags_HasDuplicateInBody = 0x000000016;
  3248. // Used to store local property info for with/catch objects, lets, or consts
  3249. // that are needed for the debugger.
  3250. class DebuggerScopeProperty
  3251. {
  3252. public:
  3253. Js::PropertyId propId; // The property ID of the scope variable.
  3254. RegSlot location; // Contains the location of the scope variable (regslot, slotarray, direct).
  3255. int byteCodeInitializationOffset; // The byte code offset used when comparing let/const variables for dead zone exclusion debugger side.
  3256. DebuggerScopePropertyFlags flags; // Flags for the property.
  3257. bool IsConst() const { return (flags & DebuggerScopePropertyFlags_Const) != 0; }
  3258. bool IsCatchObject() const { return (flags & DebuggerScopePropertyFlags_CatchObject) != 0; }
  3259. bool IsWithObject() const { return (flags & DebuggerScopePropertyFlags_WithObject) != 0; }
  3260. bool IsForInOrForOfCollectionScope() const { return (flags & DebuggerScopePropertyFlags_ForInOrOfCollection) != 0; }
  3261. public:
  3262. // Determines if the current property is in a dead zone. Note that the property makes
  3263. // no assumptions about what scope it's in, that is determined by DebuggerScope.
  3264. // byteCodeOffset - The current offset in bytecode that the debugger is at.
  3265. bool IsInDeadZone(int byteCodeOffset) const
  3266. {
  3267. if (IsForInOrForOfCollectionScope())
  3268. {
  3269. // These are let/const loop variables of a for-in or for-of loop
  3270. // in the scope for the collection expression. They are always
  3271. // in TDZ in this scope, never initialized by the bytecode.
  3272. return true;
  3273. }
  3274. if (this->byteCodeInitializationOffset == Constants::InvalidByteCodeOffset && !(IsCatchObject() || IsWithObject()))
  3275. {
  3276. AssertMsg(false, "Debug let/const property never had its initialization point updated. This indicates that a Ld or St operation in ByteCodeGenerator was missed that needs to have DebuggerScope::UpdatePropertyInitializationOffset() added to it.");
  3277. return false;
  3278. }
  3279. return byteCodeOffset < this->byteCodeInitializationOffset;
  3280. }
  3281. };
  3282. // Used to track with, catch, and block scopes for the debugger to determine context.
  3283. class DebuggerScope
  3284. {
  3285. public:
  3286. typedef JsUtil::List<DebuggerScopeProperty> DebuggerScopePropertyList;
  3287. DebuggerScope(Recycler* recycler, DiagExtraScopesType scopeType, RegSlot scopeLocation, int rangeBegin)
  3288. : scopeType(scopeType),
  3289. scopeProperties(nullptr),
  3290. parentScope(nullptr),
  3291. siblingScope(nullptr),
  3292. scopeLocation(scopeLocation),
  3293. recycler(recycler)
  3294. {
  3295. this->range.begin = rangeBegin;
  3296. this->range.end = -1;
  3297. }
  3298. DebuggerScope * GetSiblingScope(RegSlot location, FunctionBody *functionBody);
  3299. void AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags);
  3300. bool GetPropertyIndex(Js::PropertyId propertyId, int& i);
  3301. bool HasProperty(Js::PropertyId propertyId);
  3302. bool IsOffsetInScope(int offset) const;
  3303. bool Contains(Js::PropertyId propertyId, RegSlot location) const;
  3304. bool IsBlockScope() const;
  3305. bool IsBlockObjectScope() const
  3306. {
  3307. return this->scopeType == Js::DiagBlockScopeInObject;
  3308. }
  3309. bool IsCatchScope() const;
  3310. bool IsWithScope() const;
  3311. bool IsSlotScope() const;
  3312. bool IsParamScope() const;
  3313. bool HasProperties() const;
  3314. bool IsAncestorOf(const DebuggerScope* potentialChildScope);
  3315. bool AreAllPropertiesInDeadZone(int byteCodeOffset) const;
  3316. RegSlot GetLocation() const { Assert(IsOwnScope()); return scopeLocation; }
  3317. bool IsOwnScope() const { return scopeLocation != Js::Constants::NoRegister; }
  3318. bool TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const;
  3319. bool TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const;
  3320. bool UpdatePropertyInitializationOffset(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3321. void UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  3322. void UpdatePropertiesInForInOrOfCollectionScope();
  3323. void SetParentScope(DebuggerScope* parentScope) { this->parentScope = parentScope; }
  3324. DebuggerScope* GetParentScope() const { return parentScope; }
  3325. DebuggerScope* FindCommonAncestor(DebuggerScope* debuggerScope);
  3326. int GetEnd() const { return range.end; }
  3327. int GetStart() const { return range.begin; }
  3328. void SetScopeLocation(RegSlot scopeLocation) { this->scopeLocation = scopeLocation; }
  3329. void SetBegin(int begin);
  3330. void SetEnd(int end);
  3331. #if DBG
  3332. void Dump();
  3333. PCWSTR GetDebuggerScopeTypeString(DiagExtraScopesType scopeType);
  3334. #endif
  3335. #if ENABLE_TTD
  3336. Js::PropertyId GetPropertyIdForSlotIndex_TTD(uint32 slotIndex) const;
  3337. #endif
  3338. public:
  3339. // The list of scope properties in this scope object.
  3340. // For with scope: Has 1 property that represents the scoped object.
  3341. // For catch scope: Has 1 property that represents the exception object.
  3342. // For block scope: Has 0-n properties that represent let/const variables in that scope.
  3343. Field(DebuggerScopePropertyList*) scopeProperties;
  3344. Field(DiagExtraScopesType) scopeType; // The type of scope being represented (With, Catch, or Block scope).
  3345. Field(DebuggerScope*) siblingScope; // Valid only when current scope is slot/activationobject and symbols are on direct regslot
  3346. static const int InvalidScopeIndex = -1;
  3347. private:
  3348. int GetScopeDepth() const;
  3349. bool UpdatePropertyInitializationOffsetInternal(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3350. void EnsurePropertyListIsAllocated();
  3351. private:
  3352. Field(DebuggerScope*) parentScope;
  3353. Field(regex::Interval) range; // The start and end byte code writer offsets used when comparing where the debugger is currently stopped at (breakpoint location).
  3354. Field(RegSlot) scopeLocation;
  3355. FieldNoBarrier(Recycler*) recycler;
  3356. };
  3357. class ScopeObjectChain
  3358. {
  3359. public:
  3360. typedef JsUtil::List<DebuggerScope*> ScopeObjectChainList;
  3361. ScopeObjectChain(Recycler* recycler)
  3362. : pScopeChain(nullptr)
  3363. {
  3364. pScopeChain = RecyclerNew(recycler, ScopeObjectChainList, recycler);
  3365. }
  3366. // This function will return DebuggerScopeProperty when the property is found and correctly in the range.
  3367. // If the property is found, but the scope is not in the range, it will return false, but the out param (isPropertyInDebuggerScope) will set to true,
  3368. // and isConst will be updated.
  3369. // If the property is not found at all, it will return false, and isPropertyInDebuggerScope will be false.
  3370. bool TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone);
  3371. // List of all Scope Objects in a function. Scopes are added to this list as when they are created in bytecode gen part.
  3372. Field(ScopeObjectChainList*) pScopeChain;
  3373. };
  3374. #pragma endregion
  3375. } // namespace Js