NativeCodeGenerator.cpp 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "Backend.h"
  7. #include "Base/ScriptContextProfiler.h"
  8. #include "NativeEntryPointData.h"
  9. #include "JitTransferData.h"
  10. #if DBG
  11. Js::JavascriptMethod checkCodeGenThunk;
  12. #endif
  13. #ifdef ENABLE_PREJIT
  14. #define IS_PREJIT_ON() (Js::Configuration::Global.flags.Prejit)
  15. #else
  16. #define IS_PREJIT_ON() (DEFAULT_CONFIG_Prejit)
  17. #endif
  18. #define ASSERT_THREAD() AssertMsg(mainThreadId == GetCurrentThreadContextId(), \
  19. "Cannot use this member of native code generator from thread other than the creating context's current thread")
  20. NativeCodeGenerator::NativeCodeGenerator(Js::ScriptContext * scriptContext)
  21. : JsUtil::WaitableJobManager(scriptContext->GetThreadContext()->GetJobProcessor()),
  22. scriptContext(scriptContext),
  23. pendingCodeGenWorkItems(0),
  24. queuedFullJitWorkItemCount(0),
  25. foregroundAllocators(nullptr),
  26. backgroundAllocators(nullptr),
  27. byteCodeSizeGenerated(0),
  28. isClosed(false),
  29. isOptimizedForManyInstances(scriptContext->GetThreadContext()->IsOptimizedForManyInstances()),
  30. SetNativeEntryPoint(Js::FunctionBody::DefaultSetNativeEntryPoint),
  31. freeLoopBodyManager(scriptContext->GetThreadContext()->GetJobProcessor()),
  32. hasUpdatedQForDebugMode(false)
  33. #ifdef PROFILE_EXEC
  34. , foregroundCodeGenProfiler(nullptr)
  35. , backgroundCodeGenProfiler(nullptr)
  36. #endif
  37. {
  38. freeLoopBodyManager.SetNativeCodeGen(this);
  39. #if DBG_DUMP
  40. if (Js::Configuration::Global.flags.IsEnabled(Js::AsmDumpModeFlag)
  41. && (Js::Configuration::Global.flags.AsmDumpMode != nullptr))
  42. {
  43. bool fileOpened = false;
  44. fileOpened = (0 == _wfopen_s(&this->asmFile, Js::Configuration::Global.flags.AsmDumpMode, _u("wt")));
  45. if (!fileOpened)
  46. {
  47. size_t len = wcslen(Js::Configuration::Global.flags.AsmDumpMode);
  48. if (len < _MAX_PATH - 5)
  49. {
  50. char16 filename[_MAX_PATH];
  51. wcscpy_s(filename, _MAX_PATH, Js::Configuration::Global.flags.AsmDumpMode);
  52. char16 * number = filename + len;
  53. for (int i = 0; i < 1000; i++)
  54. {
  55. _itow_s(i, number, 5, 10);
  56. fileOpened = (0 == _wfopen_s(&this->asmFile, filename, _u("wt")));
  57. if (fileOpened)
  58. {
  59. break;
  60. }
  61. }
  62. }
  63. if (!fileOpened)
  64. {
  65. this->asmFile = nullptr;
  66. AssertMsg(0, "Could not open file for AsmDump. The output will goto standard console");
  67. }
  68. }
  69. }
  70. else
  71. {
  72. this->asmFile = nullptr;
  73. }
  74. #endif
  75. #if DBG
  76. this->mainThreadId = GetCurrentThreadContextId();
  77. #endif
  78. Processor()->AddManager(this);
  79. this->freeLoopBodyManager.SetAutoClose(false);
  80. }
  81. NativeCodeGenerator::~NativeCodeGenerator()
  82. {
  83. Assert(this->IsClosed());
  84. #if PDATA_ENABLED && defined(_WIN32)
  85. DelayDeletingFunctionTable::Clear();
  86. #endif
  87. #ifdef PROFILE_EXEC
  88. if (this->foregroundCodeGenProfiler != nullptr)
  89. {
  90. this->foregroundCodeGenProfiler->Release();
  91. }
  92. #endif
  93. if (scriptContext->GetJitFuncRangeCache() != nullptr)
  94. {
  95. scriptContext->GetJitFuncRangeCache()->ClearCache();
  96. }
  97. if(this->foregroundAllocators != nullptr)
  98. {
  99. HeapDelete(this->foregroundAllocators);
  100. }
  101. if (this->backgroundAllocators)
  102. {
  103. #if DBG
  104. // PageAllocator is thread agile. This destructor can be called from background GC thread.
  105. // We have already removed this manager from the job queue and hence its fine to set the threadId to -1.
  106. // We can't DissociatePageAllocator here as its allocated ui thread.
  107. //this->Processor()->DissociatePageAllocator(allocator->GetPageAllocator());
  108. this->backgroundAllocators->ClearConcurrentThreadId();
  109. #endif
  110. // The native code generator may be deleted after Close was called on the job processor. In that case, the
  111. // background thread is no longer running, so clean things up in the foreground.
  112. HeapDelete(this->backgroundAllocators);
  113. }
  114. #ifdef PROFILE_EXEC
  115. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  116. {
  117. while (this->backgroundCodeGenProfiler)
  118. {
  119. Js::ScriptContextProfiler *codegenProfiler = this->backgroundCodeGenProfiler;
  120. this->backgroundCodeGenProfiler = this->backgroundCodeGenProfiler->next;
  121. // background codegen profiler is allocated in background thread,
  122. // clear the thead Id before release
  123. #ifdef DBG
  124. if (codegenProfiler->pageAllocator != nullptr)
  125. {
  126. codegenProfiler->pageAllocator->SetDisableThreadAccessCheck();
  127. }
  128. #endif
  129. codegenProfiler->Release();
  130. }
  131. }
  132. else
  133. {
  134. Assert(this->backgroundCodeGenProfiler == nullptr);
  135. }
  136. #endif
  137. }
  138. void NativeCodeGenerator::Close()
  139. {
  140. Assert(!this->IsClosed());
  141. // Close FreeLoopBodyJobManager first, as it depends on NativeCodeGenerator to be open before it's removed
  142. this->freeLoopBodyManager.Close();
  143. Processor()->RemoveManager(this);
  144. this->isClosed = true;
  145. Assert(!queuedFullJitWorkItems.Head());
  146. Assert(queuedFullJitWorkItemCount == 0);
  147. for(JsUtil::Job *job = workItems.Head(); job;)
  148. {
  149. JsUtil::Job *const next = job->Next();
  150. JobProcessed(job, /*succeeded*/ false);
  151. job = next;
  152. }
  153. workItems.Clear();
  154. // Only decommit here instead of releasing the memory, so we retain control over these addresses
  155. // Mitigate against the case the entry point is called after the script site is closed
  156. if (this->backgroundAllocators)
  157. {
  158. this->backgroundAllocators->emitBufferManager.Decommit();
  159. }
  160. if (this->foregroundAllocators)
  161. {
  162. this->foregroundAllocators->emitBufferManager.Decommit();
  163. }
  164. #if DBG_DUMP
  165. if (this->asmFile != nullptr)
  166. {
  167. if(0 != fclose(this->asmFile))
  168. {
  169. AssertMsg(0, "Could not close file for AsmDump. You may ignore this warning.");
  170. }
  171. }
  172. #endif
  173. }
  174. #if DBG_DUMP
  175. extern Func *CurrentFunc;
  176. #endif
  177. JsFunctionCodeGen *
  178. NativeCodeGenerator::NewFunctionCodeGen(Js::FunctionBody *functionBody, Js::EntryPointInfo* info)
  179. {
  180. return HeapNewNoThrow(JsFunctionCodeGen, this, functionBody, info, functionBody->IsInDebugMode());
  181. }
  182. JsLoopBodyCodeGen *
  183. NativeCodeGenerator::NewLoopBodyCodeGen(Js::FunctionBody *functionBody, Js::EntryPointInfo* info, Js::LoopHeader * loopHeader)
  184. {
  185. return HeapNewNoThrow(JsLoopBodyCodeGen, this, functionBody, info, functionBody->IsInDebugMode(), loopHeader);
  186. }
  187. #ifdef ENABLE_PREJIT
  188. bool
  189. NativeCodeGenerator::DoBackEnd(Js::FunctionBody *fn)
  190. {
  191. return (
  192. !PHASE_OFF(Js::BackEndPhase, fn)
  193. && !fn->IsGeneratorAndJitIsDisabled()
  194. #ifdef ASMJS_PLAT
  195. && !fn->IsAsmJSModule()
  196. #endif
  197. );
  198. }
  199. void
  200. NativeCodeGenerator::GenerateAllFunctions(Js::FunctionBody * fn)
  201. {
  202. Assert(IS_PREJIT_ON());
  203. Assert(fn->GetDefaultFunctionEntryPointInfo()->entryPointIndex == 0);
  204. // Make sure this isn't a deferred function
  205. Assert(fn->GetFunctionBody() == fn);
  206. Assert(!fn->IsDeferred());
  207. if (DoBackEnd(fn))
  208. {
  209. if (fn->GetLoopCount() != 0 && fn->ForceJITLoopBody() && !fn->IsInDebugMode())
  210. {
  211. // Only jit the loop body with /force:JITLoopBody
  212. for (uint i = 0; i < fn->GetLoopCount(); i++)
  213. {
  214. Js::LoopHeader * loopHeader = fn->GetLoopHeader(i);
  215. if (loopHeader->hasYield == false)
  216. {
  217. Js::EntryPointInfo * entryPointInfo = loopHeader->GetCurrentEntryPointInfo();
  218. this->GenerateLoopBody(fn, loopHeader, entryPointInfo);
  219. }
  220. }
  221. }
  222. else
  223. {
  224. // A JIT attempt should have already been made through GenerateFunction
  225. Assert(!fn->GetDefaultFunctionEntryPointInfo()->IsNotScheduled());
  226. }
  227. }
  228. for (uint i = 0; i < fn->GetNestedCount(); i++)
  229. {
  230. Js::FunctionBody* functionToJIT = fn->GetNestedFunctionForExecution(i)->GetFunctionBody();
  231. GenerateAllFunctions(functionToJIT);
  232. }
  233. }
  234. #endif
  235. #if _M_ARM
  236. USHORT ArmExtractThumbImmediate16(PUSHORT address)
  237. {
  238. return ((address[0] << 12) & 0xf000) | // bits[15:12] in OP0[3:0]
  239. ((address[0] << 1) & 0x0800) | // bits[11] in OP0[10]
  240. ((address[1] >> 4) & 0x0700) | // bits[10:8] in OP1[14:12]
  241. ((address[1] >> 0) & 0x00ff); // bits[7:0] in OP1[7:0]
  242. }
  243. void ArmInsertThumbImmediate16(PUSHORT address, USHORT immediate)
  244. {
  245. USHORT opcode0;
  246. USHORT opcode1;
  247. opcode0 = address[0];
  248. opcode1 = address[1];
  249. opcode0 &= ~((0xf000 >> 12) | (0x0800 >> 1));
  250. opcode1 &= ~((0x0700 << 4) | (0x00ff << 0));
  251. opcode0 |= (immediate & 0xf000) >> 12; // bits[15:12] in OP0[3:0]
  252. opcode0 |= (immediate & 0x0800) >> 1; // bits[11] in OP0[10]
  253. opcode1 |= (immediate & 0x0700) << 4; // bits[10:8] in OP1[14:12]
  254. opcode1 |= (immediate & 0x00ff) << 0; // bits[7:0] in OP1[7:0]
  255. address[0] = opcode0;
  256. address[1] = opcode1;
  257. }
  258. #endif
  259. void DoFunctionRelocations(BYTE *function, DWORD functionOffset, DWORD functionSize, BYTE *module, size_t imageBase, IMAGE_SECTION_HEADER *textHeader, IMAGE_SECTION_HEADER *relocHeader)
  260. {
  261. PIMAGE_BASE_RELOCATION relocationBlock = (PIMAGE_BASE_RELOCATION)(module + relocHeader->PointerToRawData);
  262. for (; relocationBlock->VirtualAddress > 0 && ((BYTE *)relocationBlock < (module + relocHeader->PointerToRawData + relocHeader->SizeOfRawData)); )
  263. {
  264. DWORD blockOffset = relocationBlock->VirtualAddress - textHeader->VirtualAddress;
  265. // Skip relocation blocks that are before the function
  266. if ((blockOffset + 0x1000) > functionOffset)
  267. {
  268. unsigned short *relocation = (unsigned short *)((unsigned char *)relocationBlock + sizeof(IMAGE_BASE_RELOCATION));
  269. for (uint index = 0; index < ((relocationBlock->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2); index++, relocation++)
  270. {
  271. int type = *relocation >> 12;
  272. int offset = *relocation & 0xfff;
  273. // If we are past the end of the function, we can stop.
  274. if ((blockOffset + offset) >= (functionOffset + functionSize))
  275. {
  276. break;
  277. }
  278. if ((blockOffset + offset) < functionOffset)
  279. {
  280. continue;
  281. }
  282. switch (type)
  283. {
  284. case IMAGE_REL_BASED_ABSOLUTE:
  285. break;
  286. #if _M_IX86
  287. case IMAGE_REL_BASED_HIGHLOW:
  288. {
  289. DWORD *patchAddrHL = (DWORD *) (function + blockOffset + offset - functionOffset);
  290. DWORD patchAddrHLOffset = *patchAddrHL - imageBase - textHeader->VirtualAddress;
  291. Assert((patchAddrHLOffset > functionOffset) && (patchAddrHLOffset < (functionOffset + functionSize)));
  292. *patchAddrHL = patchAddrHLOffset - functionOffset + (DWORD)function;
  293. }
  294. break;
  295. #elif defined(TARGET_64)
  296. case IMAGE_REL_BASED_DIR64:
  297. {
  298. ULONGLONG *patchAddr64 = (ULONGLONG *) (function + blockOffset + offset - functionOffset);
  299. ULONGLONG patchAddr64Offset = *patchAddr64 - imageBase - textHeader->VirtualAddress;
  300. Assert((patchAddr64Offset > functionOffset) && (patchAddr64Offset < (functionOffset + functionSize)));
  301. *patchAddr64 = patchAddr64Offset - functionOffset + (ULONGLONG)function;
  302. }
  303. break;
  304. #else
  305. case IMAGE_REL_BASED_THUMB_MOV32:
  306. {
  307. USHORT *patchAddr = (USHORT *) (function + blockOffset + offset - functionOffset);
  308. DWORD address = ArmExtractThumbImmediate16(patchAddr) | (ArmExtractThumbImmediate16(patchAddr + 2) << 16);
  309. address = address - imageBase - textHeader->VirtualAddress - functionOffset + (DWORD)function;
  310. ArmInsertThumbImmediate16(patchAddr, (USHORT)(address & 0xFFFF));
  311. ArmInsertThumbImmediate16(patchAddr + 2, (USHORT)(address >> 16));
  312. }
  313. break;
  314. #endif
  315. default:
  316. Assert(false);
  317. break;
  318. }
  319. }
  320. }
  321. relocationBlock = (PIMAGE_BASE_RELOCATION) (((BYTE *) relocationBlock) + relocationBlock->SizeOfBlock);
  322. }
  323. }
  324. class AutoRestoreDefaultEntryPoint
  325. {
  326. public:
  327. AutoRestoreDefaultEntryPoint(Js::FunctionBody* functionBody):
  328. functionBody(functionBody)
  329. {
  330. this->oldDefaultEntryPoint = functionBody->GetDefaultFunctionEntryPointInfo();
  331. this->oldOriginalEntryPoint = functionBody->GetOriginalEntryPoint();
  332. this->newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  333. }
  334. ~AutoRestoreDefaultEntryPoint()
  335. {
  336. if (newEntryPoint && !newEntryPoint->IsCodeGenDone())
  337. {
  338. functionBody->RestoreOldDefaultEntryPoint(oldDefaultEntryPoint, oldOriginalEntryPoint, newEntryPoint);
  339. }
  340. }
  341. private:
  342. Js::FunctionBody* functionBody;
  343. Js::FunctionEntryPointInfo* oldDefaultEntryPoint;
  344. Js::JavascriptMethod oldOriginalEntryPoint;
  345. Js::FunctionEntryPointInfo* newEntryPoint;
  346. };
  347. //static
  348. void NativeCodeGenerator::Jit_TransitionFromSimpleJit(void *const framePointer)
  349. {
  350. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(TransitionFromSimpleJit);
  351. TransitionFromSimpleJit(
  352. Js::VarTo<Js::ScriptFunction>(Js::JavascriptCallStackLayout::FromFramePointer(framePointer)->functionObject));
  353. JIT_HELPER_END(TransitionFromSimpleJit);
  354. }
  355. //static
  356. void NativeCodeGenerator::TransitionFromSimpleJit(Js::ScriptFunction *const function)
  357. {
  358. Assert(function);
  359. Js::FunctionBody *const functionBody = function->GetFunctionBody();
  360. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  361. if(defaultEntryPointInfo == functionBody->GetSimpleJitEntryPointInfo())
  362. {
  363. Assert(functionBody->GetExecutionMode() == ExecutionMode::SimpleJit);
  364. Assert(function->GetFunctionEntryPointInfo() == defaultEntryPointInfo);
  365. // The latest entry point is the simple JIT, transition to the next execution mode and schedule a full JIT
  366. bool functionEntryPointUpdated = functionBody->GetScriptContext()->GetNativeCodeGenerator()->GenerateFunction(functionBody, function);
  367. if (functionEntryPointUpdated)
  368. {
  369. // Transition to the next execution mode after scheduling a full JIT, in case of OOM before the entry point is changed
  370. const bool transitioned = functionBody->TryTransitionToNextExecutionMode();
  371. Assert(transitioned);
  372. if (PHASE_TRACE(Js::SimpleJitPhase, functionBody))
  373. {
  374. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  375. Output::Print(
  376. _u("SimpleJit (TransitionFromSimpleJit): function: %s (%s)"),
  377. functionBody->GetDisplayName(),
  378. functionBody->GetDebugNumberSet(debugStringBuffer));
  379. Output::Flush();
  380. }
  381. }
  382. return;
  383. }
  384. if(function->GetFunctionEntryPointInfo() != defaultEntryPointInfo)
  385. {
  386. // A full JIT may have already been scheduled, or some entry point info got expired before the simple JIT entry point
  387. // was ready. In any case, the function's entry point info is not the latest, so update it.
  388. function->UpdateThunkEntryPoint(defaultEntryPointInfo, functionBody->GetDirectEntryPoint(defaultEntryPointInfo));
  389. }
  390. }
  391. #ifdef IR_VIEWER
  392. Js::Var
  393. NativeCodeGenerator::RejitIRViewerFunction(Js::FunctionBody *fn, Js::ScriptContext *requestContext)
  394. {
  395. /* Note: adapted from NativeCodeGenerator::GenerateFunction (NativeCodeGenerator.cpp) */
  396. Js::ScriptContext *scriptContext = fn->GetScriptContext();
  397. PageAllocator *pageAllocator = scriptContext->GetThreadContext()->GetPageAllocator();
  398. NativeCodeGenerator *nativeCodeGenerator = scriptContext->GetNativeCodeGenerator();
  399. AutoRestoreDefaultEntryPoint autoRestore(fn);
  400. Js::FunctionEntryPointInfo * entryPoint = fn->GetDefaultFunctionEntryPointInfo();
  401. JsFunctionCodeGen workitem(this, fn, entryPoint, fn->IsInDebugMode());
  402. workitem.isRejitIRViewerFunction = true;
  403. workitem.irViewerRequestContext = scriptContext;
  404. workitem.SetJitMode(ExecutionMode::FullJit);
  405. entryPoint->SetCodeGenPendingWithStackAllocatedWorkItem();
  406. entryPoint->SetCodeGenQueued();
  407. const auto recyclableData = GatherCodeGenData(fn, fn, entryPoint, &workitem);
  408. workitem.SetRecyclableData(recyclableData);
  409. nativeCodeGenerator->CodeGen(pageAllocator, &workitem, true);
  410. return Js::CrossSite::MarshalVar(requestContext, workitem.GetIRViewerOutput(scriptContext));
  411. }
  412. #endif /* IR_VIEWER */
  413. #ifdef ALLOW_JIT_REPRO
  414. HRESULT NativeCodeGenerator::JitFromEncodedWorkItem(_In_reads_(bufferSize) const byte* buffer, _In_ uint bufferSize)
  415. {
  416. CodeGenWorkItemIDL* workItemData = nullptr;
  417. HRESULT hr = JITManager::DeserializeRPCData(buffer, bufferSize, &workItemData);
  418. if (FAILED(hr))
  419. {
  420. return hr;
  421. }
  422. AssertOrFailFast(workItemData);
  423. JITOutputIDL jitOutput = { 0 };
  424. CodeGen(scriptContext->GetThreadContext()->GetPageAllocator(), workItemData, jitOutput, true);
  425. return S_OK;
  426. }
  427. #endif
  428. ///----------------------------------------------------------------------------
  429. ///
  430. /// NativeCodeGenerator::GenerateFunction
  431. ///
  432. /// This is the main entry point for the runtime to call the native code
  433. /// generator.
  434. ///
  435. ///----------------------------------------------------------------------------
  436. bool
  437. NativeCodeGenerator::GenerateFunction(Js::FunctionBody *fn, Js::ScriptFunction * function)
  438. {
  439. ASSERT_THREAD();
  440. Assert(!fn->GetIsFromNativeCodeModule());
  441. Assert(fn->GetScriptContext()->GetNativeCodeGenerator() == this);
  442. Assert(fn->GetFunctionBody() == fn);
  443. Assert(!fn->IsDeferred());
  444. if (fn->IsGeneratorAndJitIsDisabled())
  445. {
  446. // JITing generator functions is not complete nor stable yet so it is off by default.
  447. // Also try/catch JIT support in generator functions is not a goal for threshold
  448. // release so JITing generators containing try blocks is disabled for now.
  449. return false;
  450. }
  451. if (fn->IsInDebugMode() && fn->GetHasTry())
  452. {
  453. // Under debug mode disable JIT for functions that:
  454. // - have try
  455. return false;
  456. }
  457. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  458. if (Js::Configuration::Global.flags.Interpret &&
  459. fn->GetDisplayName() &&
  460. ::wcsstr(Js::Configuration::Global.flags.Interpret, fn->GetDisplayName()))
  461. {
  462. return false;
  463. }
  464. #endif
  465. if (fn->GetLoopCount() != 0 && fn->ForceJITLoopBody() && !fn->IsInDebugMode())
  466. {
  467. // Don't code gen the function if the function has loop, ForceJITLoopBody is on,
  468. // unless we are in debug mode in which case JIT loop body is disabled, even if it's forced.
  469. return false;
  470. }
  471. // Create a work item with null entry point- we'll set it once its allocated
  472. AutoPtr<JsFunctionCodeGen> workItemAutoPtr(this->NewFunctionCodeGen(fn, nullptr));
  473. if ((JsFunctionCodeGen*) workItemAutoPtr == nullptr)
  474. {
  475. // OOM, just skip this work item and return.
  476. return false;
  477. }
  478. Js::FunctionEntryPointInfo* entryPointInfo = nullptr;
  479. if (function != nullptr)
  480. {
  481. entryPointInfo = fn->CreateNewDefaultEntryPoint();
  482. }
  483. else
  484. {
  485. entryPointInfo = fn->GetDefaultFunctionEntryPointInfo();
  486. Assert(fn->IsInterpreterThunk() || fn->IsSimpleJitOriginalEntryPoint());
  487. }
  488. bool doPreJit = IS_PREJIT_ON();
  489. #ifdef ASMJS_PLAT
  490. if (fn->GetIsAsmjsMode())
  491. {
  492. AnalysisAssert(function != nullptr);
  493. Js::FunctionEntryPointInfo* oldFuncObjEntryPointInfo = (Js::FunctionEntryPointInfo*)function->GetEntryPointInfo();
  494. Assert(oldFuncObjEntryPointInfo->GetIsAsmJSFunction()); // should be asmjs entrypoint info
  495. // Set asmjs to be true in entrypoint
  496. entryPointInfo->SetIsAsmJSFunction(true);
  497. Assert(PHASE_ON1(Js::AsmJsJITTemplatePhase) || (!oldFuncObjEntryPointInfo->GetIsTJMode() && !entryPointInfo->GetIsTJMode()));
  498. // this changes the address in the entrypointinfo to be the AsmJsCodgenThunk
  499. function->UpdateThunkEntryPoint(entryPointInfo, NativeCodeGenerator::CheckAsmJsCodeGenThunk);
  500. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  501. Output::Print(_u("New Entrypoint is CheckAsmJsCodeGenThunk for function: %s\n"), fn->GetDisplayName());
  502. doPreJit |= CONFIG_FLAG(MaxAsmJsInterpreterRunCount) == 0 || CONFIG_ISENABLED(Js::ForceNativeFlag);
  503. }
  504. else
  505. #endif
  506. {
  507. fn->SetCheckCodeGenEntryPoint(entryPointInfo, NativeCodeGenerator::CheckCodeGenThunk);
  508. if (function != nullptr)
  509. {
  510. function->UpdateThunkEntryPoint(entryPointInfo, NativeCodeGenerator::CheckCodeGenThunk);
  511. }
  512. }
  513. JsFunctionCodeGen * workitem = workItemAutoPtr.Detach();
  514. workitem->SetEntryPointInfo(entryPointInfo);
  515. entryPointInfo->SetCodeGenPending(workitem);
  516. InterlockedIncrement(&pendingCodeGenWorkItems);
  517. if(!doPreJit)
  518. {
  519. workItems.LinkToEnd(workitem);
  520. return true;
  521. }
  522. const ExecutionMode prejitJitMode = PrejitJitMode(fn);
  523. workitem->SetJitMode(prejitJitMode);
  524. try
  525. {
  526. AddToJitQueue(workitem, /*prioritize*/ true, /*lock*/ true, function);
  527. }
  528. catch (...)
  529. {
  530. // Add the item back to the list if AddToJitQueue throws. The position in the list is not important.
  531. workitem->ResetJitMode();
  532. workItems.LinkToEnd(workitem);
  533. throw;
  534. }
  535. fn->TraceExecutionMode("Prejit (before)");
  536. if(prejitJitMode == ExecutionMode::SimpleJit)
  537. {
  538. fn->TransitionToSimpleJitExecutionMode();
  539. }
  540. else
  541. {
  542. Assert(prejitJitMode == ExecutionMode::FullJit);
  543. fn->TransitionToFullJitExecutionMode();
  544. }
  545. fn->TraceExecutionMode("Prejit");
  546. Processor()->PrioritizeJobAndWait(this, entryPointInfo, function);
  547. CheckCodeGenDone(fn, entryPointInfo, function);
  548. return true;
  549. }
  550. void NativeCodeGenerator::GenerateLoopBody(Js::FunctionBody * fn, Js::LoopHeader * loopHeader, Js::EntryPointInfo* entryPoint, uint localCount, Js::Var localSlots[])
  551. {
  552. ASSERT_THREAD();
  553. Assert(fn->GetScriptContext()->GetNativeCodeGenerator() == this);
  554. Assert(entryPoint->jsMethod == nullptr);
  555. Assert(!loopHeader->hasYield);
  556. #if DBG_DUMP
  557. if (PHASE_TRACE1(Js::JITLoopBodyPhase))
  558. {
  559. fn->DumpFunctionId(true);
  560. Output::Print(_u(": %-20s LoopBody Start Loop: %2d ByteCode: %4d (%4d,%4d)\n"), fn->GetDisplayName(), fn->GetLoopNumber(loopHeader),
  561. loopHeader->endOffset - loopHeader->startOffset, loopHeader->startOffset, loopHeader->endOffset);
  562. Output::Flush();
  563. }
  564. #endif
  565. // If the parent function is JITted, no need to JIT this loop
  566. // CanReleaseLoopHeaders is a quick and dirty way of checking if the
  567. // function is currently being interpreted. If it is being interpreted,
  568. // We'd still like to jit the loop body.
  569. // We reset the interpretCount to 0 in case we switch back to the interpreter
  570. if (fn->GetNativeEntryPointUsed() && fn->GetCanReleaseLoopHeaders()
  571. #ifdef ASMJS_PLAT
  572. && (!fn->GetIsAsmJsFunction() || !(loopHeader->GetCurrentEntryPointInfo()->GetIsTJMode()))
  573. #endif
  574. )
  575. {
  576. loopHeader->ResetInterpreterCount();
  577. return;
  578. }
  579. #ifdef ASMJS_PLAT
  580. if (fn->GetIsAsmJsFunction())
  581. {
  582. Js::LoopEntryPointInfo* loopEntryPointInfo = (Js::LoopEntryPointInfo*)entryPoint;
  583. loopEntryPointInfo->SetIsAsmJSFunction(true);
  584. }
  585. #endif
  586. JsLoopBodyCodeGen * workitem = this->NewLoopBodyCodeGen(fn, entryPoint, loopHeader);
  587. if (!workitem)
  588. {
  589. // OOM, just skip this work item and return.
  590. return;
  591. }
  592. entryPoint->SetCodeGenPending(workitem);
  593. try
  594. {
  595. if (!fn->GetIsAsmJsFunction()) // not needed for asmjs as we don't profile in asm mode
  596. {
  597. const uint profiledRegBegin = fn->GetConstantCount();
  598. const uint profiledRegEnd = localCount;
  599. if (profiledRegBegin < profiledRegEnd)
  600. {
  601. workitem->GetJITData()->symIdToValueTypeMapCount = profiledRegEnd - profiledRegBegin;
  602. workitem->GetJITData()->symIdToValueTypeMap = (uint16*)HeapNewArrayZ(ValueType, workitem->GetJITData()->symIdToValueTypeMapCount);
  603. Recycler *recycler = fn->GetScriptContext()->GetRecycler();
  604. for (uint i = profiledRegBegin; i < profiledRegEnd; i++)
  605. {
  606. if (localSlots[i] && IsValidVar(localSlots[i], recycler))
  607. {
  608. workitem->GetJITData()->symIdToValueTypeMap[i - profiledRegBegin] = ValueType::Uninitialized.Merge(localSlots[i]).GetRawData();
  609. }
  610. }
  611. }
  612. }
  613. workitem->SetJitMode(ExecutionMode::FullJit);
  614. AddToJitQueue(workitem, /*prioritize*/ true, /*lock*/ true);
  615. }
  616. catch (...)
  617. {
  618. // If adding to the JIT queue fails we need to revert the state of the entry point
  619. // and delete the work item
  620. entryPoint->RevertToNotScheduled();
  621. workitem->Delete();
  622. throw;
  623. }
  624. if (!Processor()->ProcessesInBackground() || fn->ForceJITLoopBody())
  625. {
  626. Processor()->PrioritizeJobAndWait(this, entryPoint);
  627. }
  628. }
  629. bool
  630. NativeCodeGenerator::IsValidVar(const Js::Var var, Recycler *const recycler)
  631. {
  632. using namespace Js;
  633. Assert(var);
  634. Assert(recycler);
  635. // We may be handling uninitialized memory here, need to ensure that each recycler-allocated object is valid before it is
  636. // read. Virtual functions shouldn't be called because the type ID may match by coincidence but the vtable can still be
  637. // invalid, even if it is deemed to be a "valid" object, since that only validates that the memory is still owned by the
  638. // recycler. This function validates the memory that ValueType::Merge(Var) reads.
  639. if(TaggedInt::Is(var))
  640. {
  641. return true;
  642. }
  643. #if FLOATVAR
  644. if(JavascriptNumber::Is_NoTaggedIntCheck(var))
  645. {
  646. return true;
  647. }
  648. #endif
  649. RecyclableObject *const recyclableObject = UnsafeVarTo<RecyclableObject>(var);
  650. if(!recycler->IsValidObject(recyclableObject, sizeof(*recyclableObject)))
  651. {
  652. return false;
  653. }
  654. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  655. if (vtable <= USHRT_MAX || (vtable & 1))
  656. {
  657. // Don't have a vtable, is it not a var, may be a frame display?
  658. return false;
  659. }
  660. Type *const type = recyclableObject->GetType();
  661. if(!recycler->IsValidObject(type, sizeof(*type)))
  662. {
  663. return false;
  664. }
  665. #if !FLOATVAR
  666. if(JavascriptNumber::Is_NoTaggedIntCheck(var))
  667. {
  668. return true;
  669. }
  670. #endif
  671. const TypeId typeId = type->GetTypeId();
  672. if(typeId < static_cast<TypeId>(0))
  673. {
  674. return false;
  675. }
  676. if(!DynamicType::Is(typeId))
  677. {
  678. return true;
  679. }
  680. DynamicType *const dynamicType = static_cast<DynamicType *>(type);
  681. if(!recycler->IsValidObject(dynamicType, sizeof(*dynamicType)))
  682. {
  683. return false;
  684. }
  685. DynamicTypeHandler *const typeHandler = dynamicType->GetTypeHandler();
  686. if(!recycler->IsValidObject(typeHandler, sizeof(*typeHandler)))
  687. {
  688. return false;
  689. }
  690. // Not using VarTo<DynamicObject> since there's a virtual call in there
  691. DynamicObject *const object = static_cast<DynamicObject *>(recyclableObject);
  692. if(!recycler->IsValidObject(object, sizeof(*object)))
  693. {
  694. return false;
  695. }
  696. if(typeId != TypeIds_Array)
  697. {
  698. ArrayObject* const objectArray = object->GetObjectArrayUnchecked();
  699. return objectArray == nullptr || recycler->IsValidObject(objectArray, sizeof(*objectArray));
  700. }
  701. // Not using JavascriptArray::FromVar since there's a virtual call in there
  702. JavascriptArray *const array = static_cast<JavascriptArray *>(object);
  703. if(!recycler->IsValidObject(array, sizeof(*array)))
  704. {
  705. return false;
  706. }
  707. return true;
  708. }
  709. #if ENABLE_DEBUG_CONFIG_OPTIONS
  710. volatile UINT_PTR NativeCodeGenerator::CodegenFailureSeed = 0;
  711. #endif
  712. void NativeCodeGenerator::CodeGen(PageAllocator* pageAllocator, CodeGenWorkItemIDL* workItemData, _Out_ JITOutputIDL& jitWriteData, const bool foreground, Js::EntryPointInfo* epInfo /*= nullptr*/)
  713. {
  714. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  715. {
  716. PSCRIPTCONTEXT_HANDLE remoteScriptContext = this->scriptContext->GetRemoteScriptAddr();
  717. if (!JITManager::GetJITManager()->IsConnected())
  718. {
  719. throw Js::OperationAbortedException();
  720. }
  721. HRESULT hr = JITManager::GetJITManager()->RemoteCodeGenCall(
  722. workItemData,
  723. remoteScriptContext,
  724. &jitWriteData);
  725. if (hr == E_ACCESSDENIED && scriptContext->IsClosed())
  726. {
  727. // script context may close after codegen call starts, consider this as aborted codegen
  728. hr = E_ABORT;
  729. }
  730. JITManager::HandleServerCallResult(hr, RemoteCallType::CodeGen);
  731. if (!PreReservedVirtualAllocWrapper::IsInRange((void*)this->scriptContext->GetThreadContext()->GetPreReservedRegionAddr(), (void*)jitWriteData.codeAddress))
  732. {
  733. this->scriptContext->GetJitFuncRangeCache()->AddFuncRange((void*)jitWriteData.codeAddress, jitWriteData.codeSize);
  734. }
  735. Assert(jitWriteData.codeAddress);
  736. Assert(jitWriteData.codeSize);
  737. }
  738. else
  739. {
  740. #if DBG
  741. size_t serializedRpcDataSize = 0;
  742. const unsigned char* serializedRpcData = nullptr;
  743. JITManager::SerializeRPCData(workItemData, &serializedRpcDataSize, &serializedRpcData);
  744. struct AutoFreeArray
  745. {
  746. const byte* arr = nullptr;
  747. size_t bufferSize = 0;
  748. ~AutoFreeArray() { HeapDeleteArray(bufferSize, arr); }
  749. } autoFreeArray;
  750. if (CONFIG_FLAG(EntryPointInfoRpcData) && epInfo != nullptr)
  751. {
  752. epInfo->SetSerializedRpcData(serializedRpcData, serializedRpcDataSize);
  753. }
  754. else
  755. {
  756. autoFreeArray.arr = serializedRpcData;
  757. autoFreeArray.bufferSize = serializedRpcDataSize;
  758. }
  759. #endif
  760. InProcCodeGenAllocators *const allocators =
  761. foreground ? EnsureForegroundAllocators(pageAllocator) : GetBackgroundAllocator(pageAllocator); // okay to do outside lock since the respective function is called only from one thread
  762. NoRecoverMemoryJitArenaAllocator jitArena(_u("JITArena"), pageAllocator, Js::Throw::OutOfMemory);
  763. #if DBG
  764. jitArena.SetNeedsDelayFreeList();
  765. #endif
  766. JITTimeWorkItem * jitWorkItem = Anew(&jitArena, JITTimeWorkItem, workItemData);
  767. #if !FLOATVAR
  768. CodeGenNumberAllocator* pNumberAllocator = nullptr;
  769. // the number allocator needs to be on the stack so that if we are doing foreground JIT
  770. // the chunk allocated from the recycler will be stacked pinned
  771. CodeGenNumberAllocator numberAllocator(
  772. foreground ? nullptr : scriptContext->GetThreadContext()->GetCodeGenNumberThreadAllocator(),
  773. scriptContext->GetRecycler());
  774. pNumberAllocator = &numberAllocator;
  775. #endif
  776. Js::ScriptContextProfiler *const codeGenProfiler =
  777. #ifdef PROFILE_EXEC
  778. foreground ? EnsureForegroundCodeGenProfiler() : GetBackgroundCodeGenProfiler(pageAllocator); // okay to do outside lock since the respective function is called only from one thread
  779. #else
  780. nullptr;
  781. #endif
  782. Func::Codegen(&jitArena, jitWorkItem, scriptContext->GetThreadContext(),
  783. scriptContext, &jitWriteData, epInfo, nullptr, jitWorkItem->GetPolymorphicInlineCacheInfo(), allocators,
  784. #if !FLOATVAR
  785. pNumberAllocator,
  786. #endif
  787. codeGenProfiler, !foreground);
  788. if (!this->scriptContext->GetThreadContext()->GetPreReservedVirtualAllocator()->IsInRange((void*)jitWriteData.codeAddress))
  789. {
  790. this->scriptContext->GetJitFuncRangeCache()->AddFuncRange((void*)jitWriteData.codeAddress, jitWriteData.codeSize);
  791. }
  792. }
  793. }
  794. void
  795. NativeCodeGenerator::CodeGen(PageAllocator * pageAllocator, CodeGenWorkItem* workItem, const bool foreground)
  796. {
  797. if(foreground)
  798. {
  799. // Func::Codegen has a lot of things on the stack, so probe the stack here instead
  800. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackJITCompile);
  801. }
  802. #if ENABLE_DEBUG_CONFIG_OPTIONS
  803. if (!foreground && Js::Configuration::Global.flags.IsEnabled(Js::InduceCodeGenFailureFlag))
  804. {
  805. if (NativeCodeGenerator::CodegenFailureSeed == 0)
  806. {
  807. // Initialize the seed
  808. NativeCodeGenerator::CodegenFailureSeed = Js::Configuration::Global.flags.InduceCodeGenFailureSeed;
  809. if (NativeCodeGenerator::CodegenFailureSeed == 0)
  810. {
  811. LARGE_INTEGER ctr;
  812. ::QueryPerformanceCounter(&ctr);
  813. NativeCodeGenerator::CodegenFailureSeed = ctr.HighPart ^ ctr.LowPart;
  814. srand((uint)NativeCodeGenerator::CodegenFailureSeed);
  815. }
  816. }
  817. int v = Math::Rand() % 100;
  818. if (v < Js::Configuration::Global.flags.InduceCodeGenFailure)
  819. {
  820. switch (v % 3)
  821. {
  822. case 0: Js::Throw::OutOfMemory(); break;
  823. case 1: throw Js::StackOverflowException(); break;
  824. case 2: throw Js::OperationAbortedException(); break;
  825. default:
  826. Assert(false);
  827. }
  828. }
  829. }
  830. #endif
  831. bool irviewerInstance = false;
  832. #ifdef IR_VIEWER
  833. irviewerInstance = true;
  834. #endif
  835. Assert(
  836. workItem->Type() != JsFunctionType ||
  837. irviewerInstance ||
  838. IsThunk(workItem->GetFunctionBody()->GetDirectEntryPoint(workItem->GetEntryPoint())) ||
  839. IsAsmJsCodeGenThunk(workItem->GetFunctionBody()->GetDirectEntryPoint(workItem->GetEntryPoint())));
  840. InterlockedExchangeAdd(&this->byteCodeSizeGenerated, workItem->GetByteCodeCount()); // must be interlocked because this data may be modified in the foreground and background thread concurrently
  841. Js::FunctionBody* body = workItem->GetFunctionBody();
  842. int nRegs = body->GetLocalsCount();
  843. AssertMsg((nRegs + 1) == (int)(SymID)(nRegs + 1), "SymID too small...");
  844. if (body->GetScriptContext()->IsClosed())
  845. {
  846. // Should not be jitting something in the foreground when the script context is actually closed
  847. Assert(IsBackgroundJIT() || !body->GetScriptContext()->IsActuallyClosed());
  848. throw Js::OperationAbortedException();
  849. }
  850. #if ENABLE_OOP_NATIVE_CODEGEN
  851. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  852. {
  853. workItem->GetJITData()->nativeDataAddr = (__int3264)workItem->GetEntryPoint()->GetOOPNativeEntryPointData()->GetNativeDataBufferRef();
  854. }
  855. #endif
  856. // TODO: oop jit can we be more efficient here?
  857. ArenaAllocator alloc(_u("JitData"), pageAllocator, Js::Throw::OutOfMemory);
  858. auto& jitData = workItem->GetJITData()->jitData;
  859. jitData = AnewStructZ(&alloc, FunctionJITTimeDataIDL);
  860. auto codeGenData = workItem->RecyclableData()->JitTimeData();
  861. FunctionJITTimeInfo::BuildJITTimeData(&alloc, codeGenData, nullptr, workItem->GetJITData()->jitData, false, foreground);
  862. workItem->GetJITData()->profiledIterations = codeGenData->GetProfiledIterations();
  863. Js::EntryPointInfo * epInfo = workItem->GetEntryPoint();
  864. if (workItem->Type() == JsFunctionType)
  865. {
  866. auto funcEPInfo = (Js::FunctionEntryPointInfo*)epInfo;
  867. jitData->callsCountAddress = (uintptr_t)&funcEPInfo->callsCount;
  868. }
  869. else
  870. {
  871. workItem->GetJITData()->jittedLoopIterationsSinceLastBailoutAddr = (intptr_t)Js::FunctionBody::GetJittedLoopIterationsSinceLastBailoutAddress(epInfo);
  872. }
  873. jitData->sharedPropertyGuards = codeGenData->sharedPropertyGuards;
  874. jitData->sharedPropGuardCount = codeGenData->sharedPropertyGuardCount;
  875. JITOutputIDL jitWriteData = {0};
  876. #if !FLOATVAR
  877. workItem->GetJITData()->xProcNumberPageSegment = scriptContext->GetThreadContext()->GetXProcNumberPageSegmentManager()->GetFreeSegment(&alloc);
  878. #endif
  879. workItem->GetJITData()->globalThisAddr = (intptr_t)workItem->RecyclableData()->JitTimeData()->GetGlobalThisObject();
  880. LARGE_INTEGER start_time = { 0 };
  881. NativeCodeGenerator::LogCodeGenStart(workItem, &start_time);
  882. workItem->GetJITData()->startTime = (int64)start_time.QuadPart;
  883. CodeGen(pageAllocator, workItem->GetJITData(), jitWriteData, foreground, epInfo);
  884. if (JITManager::GetJITManager()->IsOOPJITEnabled() && PHASE_VERBOSE_TRACE(Js::BackEndPhase, workItem->GetFunctionBody()))
  885. {
  886. LARGE_INTEGER freq;
  887. LARGE_INTEGER end_time;
  888. QueryPerformanceCounter(&end_time);
  889. QueryPerformanceFrequency(&freq);
  890. Output::Print(
  891. _u("BackendMarshalOut - function: %s time:%8.6f mSec\r\n"),
  892. workItem->GetFunctionBody()->GetDisplayName(),
  893. (((double)((end_time.QuadPart - jitWriteData.startTime)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  894. Output::Flush();
  895. }
  896. epInfo->GetNativeEntryPointData()->SetFrameHeight(jitWriteData.frameHeight);
  897. if (workItem->Type() == JsFunctionType)
  898. {
  899. Js::FunctionEntryPointInfo * funcEP = (Js::FunctionEntryPointInfo*)workItem->GetEntryPoint();
  900. funcEP->localVarSlotsOffset = jitWriteData.localVarSlotsOffset;
  901. funcEP->localVarChangedOffset = jitWriteData.localVarChangedOffset;
  902. }
  903. if (jitWriteData.hasJittedStackClosure != FALSE)
  904. {
  905. workItem->GetEntryPoint()->SetHasJittedStackClosure();
  906. }
  907. #if ENABLE_OOP_NATIVE_CODEGEN
  908. #if !FLOATVAR
  909. if (jitWriteData.numberPageSegments)
  910. {
  911. if (jitWriteData.numberPageSegments->pageAddress == 0)
  912. {
  913. midl_user_free(jitWriteData.numberPageSegments);
  914. jitWriteData.numberPageSegments = nullptr;
  915. }
  916. else
  917. {
  918. // TODO: when codegen fail, need to return the segment as well
  919. epInfo->GetOOPNativeEntryPointData()->SetNumberPageSegment(jitWriteData.numberPageSegments);
  920. }
  921. }
  922. #endif
  923. #endif
  924. #if ENABLE_OOP_NATIVE_CODEGEN
  925. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  926. {
  927. if (jitWriteData.nativeDataFixupTable)
  928. {
  929. for (unsigned int i = 0; i < jitWriteData.nativeDataFixupTable->count; i++)
  930. {
  931. auto& record = jitWriteData.nativeDataFixupTable->fixupRecords[i];
  932. auto updateList = record.updateList;
  933. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  934. {
  935. Output::Print(_u("NativeCodeData Fixup: allocIndex:%d, len:%x, totalOffset:%x, startAddress:%p\n"),
  936. record.index, record.length, record.startOffset, jitWriteData.buffer->data + record.startOffset);
  937. }
  938. while (updateList)
  939. {
  940. void* addrToFixup = jitWriteData.buffer->data + record.startOffset + updateList->addrOffset;
  941. void* targetAddr = jitWriteData.buffer->data + updateList->targetTotalOffset;
  942. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  943. {
  944. Output::Print(_u("\tEntry: +%x %p(%p) ==> %p\n"), updateList->addrOffset, addrToFixup, *(void**)(addrToFixup), targetAddr);
  945. }
  946. *(void**)(addrToFixup) = targetAddr;
  947. auto current = updateList;
  948. updateList = updateList->next;
  949. midl_user_free(current);
  950. }
  951. }
  952. midl_user_free(jitWriteData.nativeDataFixupTable);
  953. jitWriteData.nativeDataFixupTable = nullptr;
  954. // change the address with the fixup information
  955. epInfo->GetOOPNativeEntryPointData()->SetNativeDataBuffer((char*)jitWriteData.buffer->data);
  956. #if DBG
  957. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  958. {
  959. Output::Print(_u("NativeCodeData Client Buffer: %p, len: %x\n"), jitWriteData.buffer->data, jitWriteData.buffer->len);
  960. }
  961. #endif
  962. }
  963. if (jitWriteData.throwMapCount > 0)
  964. {
  965. Js::ThrowMapEntry * throwMap = (Js::ThrowMapEntry *)(jitWriteData.buffer->data + jitWriteData.throwMapOffset);
  966. Js::SmallSpanSequenceIter iter;
  967. for (uint i = 0; i < jitWriteData.throwMapCount; ++i)
  968. {
  969. workItem->RecordNativeThrowMap(iter, throwMap[i].nativeBufferOffset, throwMap[i].statementIndex);
  970. }
  971. }
  972. epInfo->GetOOPNativeEntryPointData()->RecordInlineeFrameOffsetsInfo(jitWriteData.inlineeFrameOffsetArrayOffset, jitWriteData.inlineeFrameOffsetArrayCount);
  973. }
  974. #endif
  975. if (workItem->GetJitMode() != ExecutionMode::SimpleJit)
  976. {
  977. epInfo->GetJitTransferData()->SetRuntimeTypeRefs(jitWriteData.pinnedTypeRefs);
  978. epInfo->GetJitTransferData()->SetEquivalentTypeGuardOffsets(jitWriteData.equivalentTypeGuardOffsets);
  979. epInfo->GetJitTransferData()->SetTypeGuardTransferData(&jitWriteData);
  980. Assert(jitWriteData.ctorCacheEntries == nullptr || epInfo->GetNativeEntryPointData()->GetConstructorCacheCount() > 0);
  981. epInfo->GetJitTransferData()->SetCtorCacheTransferData(&jitWriteData);
  982. workItem->GetEntryPoint()->GetJitTransferData()->SetIsReady();
  983. }
  984. else
  985. {
  986. Assert(jitWriteData.pinnedTypeRefs == nullptr);
  987. }
  988. #if defined(TARGET_64)
  989. XDataAllocation * xdataInfo = HeapNewZ(XDataAllocation);
  990. xdataInfo->address = (byte*)jitWriteData.xdataAddr;
  991. XDataAllocator::Register(xdataInfo, jitWriteData.codeAddress, jitWriteData.codeSize);
  992. epInfo->GetNativeEntryPointData()->SetXDataInfo(xdataInfo);
  993. #endif
  994. #if defined(_M_ARM)
  995. // for in-proc jit we do registration in encoder
  996. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  997. {
  998. XDataAllocation * xdataInfo = HeapNewZ(XDataAllocation);
  999. xdataInfo->pdataCount = jitWriteData.pdataCount;
  1000. xdataInfo->xdataSize = jitWriteData.xdataSize;
  1001. if (jitWriteData.buffer)
  1002. {
  1003. xdataInfo->address = jitWriteData.buffer->data + jitWriteData.xdataOffset;
  1004. for (ushort i = 0; i < xdataInfo->pdataCount; ++i)
  1005. {
  1006. RUNTIME_FUNCTION *function = xdataInfo->GetPdataArray() + i;
  1007. // if flag is 0, then we have separate .xdata, for which we need to fixup the address
  1008. if (function->Flag == 0)
  1009. {
  1010. // UnwindData was set on server as the offset from the beginning of xdata buffer
  1011. function->UnwindData = (DWORD)(xdataInfo->address + function->UnwindData);
  1012. Assert(((DWORD)function->UnwindData & 0x3) == 0); // 4 byte aligned
  1013. }
  1014. }
  1015. }
  1016. else
  1017. {
  1018. xdataInfo->address = nullptr;
  1019. }
  1020. // unmask thumb mode from code address
  1021. XDataAllocator::Register(xdataInfo, jitWriteData.codeAddress & ~0x1, jitWriteData.codeSize);
  1022. epInfo->GetNativeEntryPointData()->SetXDataInfo(xdataInfo);
  1023. }
  1024. #endif
  1025. if (!CONFIG_FLAG(OOPCFGRegistration))
  1026. {
  1027. if (jitWriteData.thunkAddress)
  1028. {
  1029. scriptContext->GetThreadContext()->SetValidCallTargetForCFG((PVOID)jitWriteData.thunkAddress);
  1030. }
  1031. else
  1032. {
  1033. scriptContext->GetThreadContext()->SetValidCallTargetForCFG((PVOID)jitWriteData.codeAddress);
  1034. }
  1035. }
  1036. if (workItem->Type() == JsLoopBodyWorkItemType)
  1037. {
  1038. Assert(jitWriteData.thunkAddress == NULL);
  1039. ((JsLoopBodyCodeGen*)workItem)->SetCodeAddress(jitWriteData.codeAddress);
  1040. }
  1041. workItem->GetEntryPoint()->SetCodeGenRecorded((Js::JavascriptMethod)jitWriteData.thunkAddress, (Js::JavascriptMethod)jitWriteData.codeAddress, jitWriteData.codeSize, (void *)this);
  1042. #if DBG_DUMP
  1043. if (PHASE_DUMP(Js::EncoderPhase, workItem->GetFunctionBody()) && Js::Configuration::Global.flags.Verbose && !JITManager::GetJITManager()->IsOOPJITEnabled())
  1044. {
  1045. workItem->GetEntryPoint()->DumpNativeOffsetMaps();
  1046. workItem->GetEntryPoint()->DumpNativeThrowSpanSequence();
  1047. Output::Flush();
  1048. }
  1049. #endif
  1050. if (jitWriteData.hasBailoutInstr != FALSE)
  1051. {
  1052. body->SetHasBailoutInstrInJittedCode(true);
  1053. }
  1054. if (!jitWriteData.isInPrereservedRegion)
  1055. {
  1056. scriptContext->GetThreadContext()->ResetIsAllJITCodeInPreReservedRegion();
  1057. }
  1058. body->m_argUsedForBranch |= jitWriteData.argUsedForBranch;
  1059. if (body->HasDynamicProfileInfo())
  1060. {
  1061. if (jitWriteData.disableArrayCheckHoist)
  1062. {
  1063. body->GetAnyDynamicProfileInfo()->DisableArrayCheckHoist(workItem->Type() == JsLoopBodyWorkItemType);
  1064. }
  1065. if (jitWriteData.disableAggressiveIntTypeSpec)
  1066. {
  1067. body->GetAnyDynamicProfileInfo()->DisableAggressiveIntTypeSpec(workItem->Type() == JsLoopBodyWorkItemType);
  1068. }
  1069. if (jitWriteData.disableStackArgOpt)
  1070. {
  1071. body->GetAnyDynamicProfileInfo()->DisableStackArgOpt();
  1072. }
  1073. if (jitWriteData.disableSwitchOpt)
  1074. {
  1075. body->GetAnyDynamicProfileInfo()->DisableSwitchOpt();
  1076. }
  1077. if (jitWriteData.disableTrackCompoundedIntOverflow)
  1078. {
  1079. body->GetAnyDynamicProfileInfo()->DisableTrackCompoundedIntOverflow();
  1080. }
  1081. if (jitWriteData.disableMemOp)
  1082. {
  1083. body->GetAnyDynamicProfileInfo()->DisableMemOp();
  1084. }
  1085. }
  1086. if (jitWriteData.disableInlineApply)
  1087. {
  1088. body->SetDisableInlineApply(true);
  1089. }
  1090. if (jitWriteData.disableInlineSpread)
  1091. {
  1092. body->SetDisableInlineSpread(true);
  1093. }
  1094. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  1095. if (Js::Configuration::Global.flags.ProfileBailOutRecordMemory)
  1096. {
  1097. scriptContext->codeSize += workItem->GetEntryPoint()->GetCodeSize();
  1098. }
  1099. #endif
  1100. NativeCodeGenerator::LogCodeGenDone(workItem, &start_time);
  1101. #ifdef BGJIT_STATS
  1102. // Must be interlocked because the following data may be modified from the background and foreground threads concurrently
  1103. Js::ScriptContext *scriptContext = workItem->GetScriptContext();
  1104. if (workItem->Type() == JsFunctionType)
  1105. {
  1106. InterlockedExchangeAdd(&scriptContext->bytecodeJITCount, workItem->GetByteCodeCount());
  1107. InterlockedIncrement(&scriptContext->funcJITCount);
  1108. }
  1109. else if(workItem->Type() == JsLoopBodyWorkItemType)
  1110. {
  1111. InterlockedIncrement(&scriptContext->loopJITCount);
  1112. }
  1113. #endif
  1114. }
  1115. /* static */
  1116. void NativeCodeGenerator::LogCodeGenStart(CodeGenWorkItem * workItem, LARGE_INTEGER * start_time)
  1117. {
  1118. Js::FunctionBody * body = workItem->GetFunctionBody();
  1119. {
  1120. if (IS_JS_ETW(EventEnabledJSCRIPT_FUNCTION_JIT_START()))
  1121. {
  1122. WCHAR displayNameBuffer[256];
  1123. WCHAR* displayName = displayNameBuffer;
  1124. size_t sizeInChars = workItem->GetDisplayName(displayName, 256);
  1125. if (sizeInChars > 256)
  1126. {
  1127. displayName = HeapNewArray(WCHAR, sizeInChars);
  1128. workItem->GetDisplayName(displayName, 256);
  1129. }
  1130. JS_ETW(EventWriteJSCRIPT_FUNCTION_JIT_START(
  1131. body->GetFunctionNumber(),
  1132. displayName,
  1133. body->GetScriptContext(),
  1134. workItem->GetInterpretedCount(),
  1135. (const unsigned int)body->LengthInBytes(),
  1136. body->GetByteCodeCount(),
  1137. body->GetByteCodeInLoopCount(),
  1138. (int)workItem->GetJitMode()));
  1139. if (displayName != displayNameBuffer)
  1140. {
  1141. HeapDeleteArray(sizeInChars, displayName);
  1142. }
  1143. }
  1144. }
  1145. #if DBG_DUMP
  1146. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BackEndPhase))
  1147. {
  1148. if (workItem->GetEntryPoint()->IsLoopBody())
  1149. {
  1150. Output::Print(_u("---BeginBackEnd: function: %s, loop:%d---\r\n"), body->GetDisplayName(), ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber());
  1151. }
  1152. else
  1153. {
  1154. Output::Print(_u("---BeginBackEnd: function: %s---\r\n"), body->GetDisplayName());
  1155. }
  1156. Output::Flush();
  1157. }
  1158. #endif
  1159. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1160. if (PHASE_TRACE(Js::BackEndPhase, body))
  1161. {
  1162. QueryPerformanceCounter(start_time);
  1163. if (workItem->GetEntryPoint()->IsLoopBody())
  1164. {
  1165. Output::Print(
  1166. _u("BeginBackEnd - function: %s (%s, line %u), loop: %u, mode: %S"),
  1167. body->GetDisplayName(),
  1168. body->GetDebugNumberSet(debugStringBuffer),
  1169. body->GetLineNumber(),
  1170. ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber(),
  1171. ExecutionModeName(workItem->GetJitMode()));
  1172. if (body->GetIsAsmjsMode())
  1173. {
  1174. Output::Print(_u(" (Asmjs)\n"));
  1175. }
  1176. else
  1177. {
  1178. Output::Print(_u("\n"));
  1179. }
  1180. }
  1181. else
  1182. {
  1183. Output::Print(
  1184. _u("BeginBackEnd - function: %s (%s, line %u), mode: %S"),
  1185. body->GetDisplayName(),
  1186. body->GetDebugNumberSet(debugStringBuffer),
  1187. body->GetLineNumber(),
  1188. ExecutionModeName(workItem->GetJitMode()));
  1189. if (body->GetIsAsmjsMode())
  1190. {
  1191. Output::Print(_u(" (Asmjs)\n"));
  1192. }
  1193. else
  1194. {
  1195. Output::Print(_u("\n"));
  1196. }
  1197. }
  1198. Output::Flush();
  1199. }
  1200. #ifdef FIELD_ACCESS_STATS
  1201. if (PHASE_TRACE(Js::ObjTypeSpecPhase, body) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, body))
  1202. {
  1203. if (workItem->RecyclableData()->JitTimeData()->inlineCacheStats)
  1204. {
  1205. auto stats = workItem->RecyclableData()->JitTimeData()->inlineCacheStats;
  1206. Output::Print(_u("ObjTypeSpec: jitting function %s (#%s): inline cache stats:\n"), body->GetDisplayName(), body->GetDebugNumberSet(debugStringBuffer));
  1207. Output::Print(_u(" overall: total %u, no profile info %u\n"), stats->totalInlineCacheCount, stats->noInfoInlineCacheCount);
  1208. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  1209. stats->monoInlineCacheCount, stats->emptyMonoInlineCacheCount, stats->clonedMonoInlineCacheCount);
  1210. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  1211. stats->polyInlineCacheCount, stats->highUtilPolyInlineCacheCount, stats->lowUtilPolyInlineCacheCount,
  1212. stats->nullPolyInlineCacheCount, stats->emptyPolyInlineCacheCount, stats->ignoredPolyInlineCacheCount, stats->disabledPolyInlineCacheCount,
  1213. stats->equivPolyInlineCacheCount, stats->nonEquivPolyInlineCacheCount, stats->clonedPolyInlineCacheCount);
  1214. }
  1215. else
  1216. {
  1217. Output::Print(_u("EquivObjTypeSpec: function %s (%s): inline cache stats unavailable\n"), body->GetDisplayName(), body->GetDebugNumberSet(debugStringBuffer));
  1218. }
  1219. Output::Flush();
  1220. }
  1221. #endif
  1222. }
  1223. /* static */
  1224. void NativeCodeGenerator::LogCodeGenDone(CodeGenWorkItem * workItem, LARGE_INTEGER * start_time)
  1225. {
  1226. Js::FunctionBody * body = workItem->GetFunctionBody();
  1227. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1228. {
  1229. if (IS_JS_ETW(EventEnabledJSCRIPT_FUNCTION_JIT_STOP()))
  1230. {
  1231. WCHAR displayNameBuffer[256];
  1232. WCHAR* displayName = displayNameBuffer;
  1233. size_t sizeInChars = workItem->GetDisplayName(displayName, 256);
  1234. if (sizeInChars > 256)
  1235. {
  1236. displayName = HeapNewArray(WCHAR, sizeInChars);
  1237. workItem->GetDisplayName(displayName, 256);
  1238. }
  1239. void* entryPoint;
  1240. ptrdiff_t codeSize;
  1241. workItem->GetEntryPointAddress(&entryPoint, &codeSize);
  1242. JS_ETW(EventWriteJSCRIPT_FUNCTION_JIT_STOP(
  1243. body->GetFunctionNumber(),
  1244. displayName,
  1245. body->GetScriptContext(),
  1246. workItem->GetInterpretedCount(),
  1247. entryPoint,
  1248. codeSize));
  1249. if (displayName != displayNameBuffer)
  1250. {
  1251. HeapDeleteArray(sizeInChars, displayName);
  1252. }
  1253. }
  1254. }
  1255. #if DBG_DUMP
  1256. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BackEndPhase))
  1257. {
  1258. Output::Print(_u("---EndBackEnd---\r\n"));
  1259. Output::Flush();
  1260. }
  1261. #endif
  1262. if (PHASE_TRACE(Js::BackEndPhase, body))
  1263. {
  1264. LARGE_INTEGER freq;
  1265. LARGE_INTEGER end_time;
  1266. QueryPerformanceCounter(&end_time);
  1267. QueryPerformanceFrequency(&freq);
  1268. if (workItem->GetEntryPoint()->IsLoopBody())
  1269. {
  1270. Output::Print(
  1271. _u("EndBackEnd - function: %s (%s, line %u), loop: %u, mode: %S, time:%8.6f mSec"),
  1272. body->GetDisplayName(),
  1273. body->GetDebugNumberSet(debugStringBuffer),
  1274. body->GetLineNumber(),
  1275. ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber(),
  1276. ExecutionModeName(workItem->GetJitMode()),
  1277. (((double)((end_time.QuadPart - start_time->QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  1278. if (body->GetIsAsmjsMode())
  1279. {
  1280. Output::Print(_u(" (Asmjs)\n"));
  1281. }
  1282. else
  1283. {
  1284. Output::Print(_u("\n"));
  1285. }
  1286. }
  1287. else
  1288. {
  1289. Output::Print(
  1290. _u("EndBackEnd - function: %s (%s, line %u), mode: %S time:%8.6f mSec"),
  1291. body->GetDisplayName(),
  1292. body->GetDebugNumberSet(debugStringBuffer),
  1293. body->GetLineNumber(),
  1294. ExecutionModeName(workItem->GetJitMode()),
  1295. (((double)((end_time.QuadPart - start_time->QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  1296. if (body->GetIsAsmjsMode())
  1297. {
  1298. Output::Print(_u(" (Asmjs)\n"));
  1299. }
  1300. else
  1301. {
  1302. Output::Print(_u("\n"));
  1303. }
  1304. }
  1305. Output::Flush();
  1306. }
  1307. }
  1308. void NativeCodeGenerator::SetProfileMode(BOOL fSet)
  1309. {
  1310. this->SetNativeEntryPoint = fSet? Js::FunctionBody::ProfileSetNativeEntryPoint : Js::FunctionBody::DefaultSetNativeEntryPoint;
  1311. }
  1312. #if _M_IX86
  1313. __declspec(naked)
  1314. Js::Var
  1315. NativeCodeGenerator::CheckAsmJsCodeGenThunk(Js::RecyclableObject* function, Js::CallInfo callInfo, ...)
  1316. {
  1317. __asm
  1318. {
  1319. push ebp
  1320. mov ebp, esp
  1321. push function
  1322. call NativeCodeGenerator::CheckAsmJsCodeGen
  1323. #ifdef _CONTROL_FLOW_GUARD
  1324. // verify that the call target is valid
  1325. mov ecx, eax
  1326. call[__guard_check_icall_fptr]
  1327. mov eax, ecx
  1328. #endif
  1329. pop ebp
  1330. jmp eax
  1331. }
  1332. }
  1333. #elif _M_X64 || _M_ARM || _M_ARM64
  1334. // Do nothing: the implementation of NativeCodeGenerator::CheckCodeGenThunk is declared (appropriately decorated) in
  1335. // Backend\amd64\Thunks.asm and Backend\arm\Thunks.asm and Backend\arm64\Thunks.asm respectively.
  1336. #else
  1337. #error Not implemented.
  1338. #endif
  1339. #if _M_IX86
  1340. __declspec(naked)
  1341. Js::Var
  1342. NativeCodeGenerator::CheckCodeGenThunk(Js::RecyclableObject* function, Js::CallInfo callInfo, ...)
  1343. {
  1344. __asm
  1345. {
  1346. push ebp
  1347. mov ebp, esp
  1348. push [esp+8]
  1349. call NativeCodeGenerator::CheckCodeGen
  1350. #ifdef _CONTROL_FLOW_GUARD
  1351. // verify that the call target is valid
  1352. mov ecx, eax
  1353. call[__guard_check_icall_fptr]
  1354. mov eax, ecx
  1355. #endif
  1356. pop ebp
  1357. jmp eax
  1358. }
  1359. }
  1360. #elif _M_X64 || _M_ARM || _M_ARM64
  1361. // Do nothing: the implementation of NativeCodeGenerator::CheckCodeGenThunk is declared (appropriately decorated) in
  1362. // Backend\amd64\Thunks.asm and Backend\arm\Thunks.asm and Backend\arm64\Thunks.asm respectively.
  1363. #else
  1364. #error Not implemented.
  1365. #endif
  1366. bool
  1367. NativeCodeGenerator::IsThunk(Js::JavascriptMethod codeAddress)
  1368. {
  1369. return codeAddress == NativeCodeGenerator::CheckCodeGenThunk;
  1370. }
  1371. bool
  1372. NativeCodeGenerator::IsAsmJsCodeGenThunk(Js::JavascriptMethod codeAddress)
  1373. {
  1374. #ifdef ASMJS_PLAT
  1375. return codeAddress == NativeCodeGenerator::CheckAsmJsCodeGenThunk;
  1376. #else
  1377. return false;
  1378. #endif
  1379. }
  1380. CheckCodeGenFunction
  1381. NativeCodeGenerator::GetCheckCodeGenFunction(Js::JavascriptMethod codeAddress)
  1382. {
  1383. if (codeAddress == NativeCodeGenerator::CheckCodeGenThunk)
  1384. {
  1385. return NativeCodeGenerator::CheckCodeGen;
  1386. }
  1387. return nullptr;
  1388. }
  1389. Js::JavascriptMethod
  1390. NativeCodeGenerator::CheckAsmJsCodeGen(Js::ScriptFunction * function)
  1391. {
  1392. Assert(function);
  1393. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1394. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1395. NativeCodeGenerator *nativeCodeGen = scriptContext->GetNativeCodeGenerator();
  1396. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  1397. Assert(scriptContext->GetThreadContext()->IsInScript());
  1398. AssertOrFailFastMsg(!functionBody->IsWasmFunction() || functionBody->GetByteCodeCount() > 0, "Wasm function should be parsed by now");
  1399. // Load the entry point here to validate it got changed afterwards
  1400. Js::FunctionEntryPointInfo* entryPoint = function->GetFunctionEntryPointInfo();
  1401. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1402. if ((PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxTemplatizedJitRunCount) >= 0) || (!PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxAsmJsInterpreterRunCount) >= 0))
  1403. {
  1404. nativeCodeGen->Processor()->PrioritizeJobAndWait(nativeCodeGen, entryPoint, function);
  1405. } else
  1406. #endif
  1407. if (!nativeCodeGen->Processor()->PrioritizeJob(nativeCodeGen, entryPoint, function))
  1408. {
  1409. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  1410. {
  1411. Output::Print(_u("Codegen not done yet for function: %s, Entrypoint is CheckAsmJsCodeGenThunk\n"), function->GetFunctionBody()->GetDisplayName());
  1412. }
  1413. return functionBody->GetOriginalEntryPoint();
  1414. }
  1415. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  1416. {
  1417. Output::Print(_u("CodeGen Done for function: %s, Changing Entrypoint to Full JIT\n"), function->GetFunctionBody()->GetDisplayName());
  1418. }
  1419. // we will need to set the functionbody external and asmjs entrypoint to the fulljit entrypoint
  1420. return CheckCodeGenDone(functionBody, entryPoint, function);
  1421. }
  1422. Js::JavascriptMethod
  1423. NativeCodeGenerator::CheckCodeGen(Js::ScriptFunction * function)
  1424. {
  1425. Assert(function);
  1426. Assert(function->GetEntryPoint() == NativeCodeGenerator::CheckCodeGenThunk
  1427. || Js::CrossSite::IsThunk(function->GetEntryPoint()));
  1428. // We are not expecting non-deserialized functions here; Error if it hasn't been deserialized by this point
  1429. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1430. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1431. NativeCodeGenerator *nativeCodeGen = scriptContext->GetNativeCodeGenerator();
  1432. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  1433. Assert(scriptContext->GetThreadContext()->IsInScript());
  1434. // Load the entry point here to validate it got changed afterwards
  1435. Js::JavascriptMethod originalEntryPoint = functionBody->GetOriginalEntryPoint();
  1436. Js::FunctionEntryPointInfo* entryPoint = function->GetFunctionEntryPointInfo();
  1437. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  1438. if(entryPoint != defaultEntryPointInfo)
  1439. {
  1440. // Switch to the latest entry point info
  1441. function->UpdateThunkEntryPoint(defaultEntryPointInfo, functionBody->GetDirectEntryPoint(defaultEntryPointInfo));
  1442. const Js::JavascriptMethod defaultDirectEntryPoint = functionBody->GetDirectEntryPoint(defaultEntryPointInfo);
  1443. if(!IsThunk(defaultDirectEntryPoint))
  1444. {
  1445. return defaultDirectEntryPoint;
  1446. }
  1447. entryPoint = defaultEntryPointInfo;
  1448. }
  1449. // If a transition to JIT needs to be forced, JIT right away
  1450. if(Js::Configuration::Global.flags.EnforceExecutionModeLimits &&
  1451. functionBody->GetExecutionMode() != ExecutionMode::SimpleJit &&
  1452. functionBody->TryTransitionToJitExecutionMode())
  1453. {
  1454. nativeCodeGen->Processor()->PrioritizeJobAndWait(nativeCodeGen, entryPoint, function);
  1455. return CheckCodeGenDone(functionBody, entryPoint, function);
  1456. }
  1457. if(!nativeCodeGen->Processor()->PrioritizeJob(nativeCodeGen, entryPoint, function))
  1458. {
  1459. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1460. #define originalEntryPoint_IS_ProfileDeferredParsingThunk \
  1461. (originalEntryPoint == ProfileDeferredParsingThunk)
  1462. #else
  1463. #define originalEntryPoint_IS_ProfileDeferredParsingThunk \
  1464. false
  1465. #endif
  1466. // Job was not yet processed
  1467. // originalEntryPoint is the last known good entry point for the function body. Here we verify that
  1468. // it either corresponds with this codegen episode (identified by function->entryPointIndex) of the function body
  1469. // or one that was scheduled after. In the latter case originalEntryPoint will get updated if and when
  1470. // that last episode completes successfully.
  1471. Assert(functionBody->GetDefaultEntryPointInfo() == function->GetEntryPointInfo() &&
  1472. (
  1473. originalEntryPoint == DefaultEntryThunk
  1474. || originalEntryPoint == Js::InterpreterStackFrame::StaticInterpreterThunk
  1475. || scriptContext->IsDynamicInterpreterThunk(originalEntryPoint)
  1476. || originalEntryPoint_IS_ProfileDeferredParsingThunk
  1477. || originalEntryPoint == DefaultDeferredParsingThunk
  1478. || (
  1479. functionBody->GetSimpleJitEntryPointInfo() &&
  1480. originalEntryPoint == functionBody->GetSimpleJitEntryPointInfo()->GetNativeEntrypoint()
  1481. )
  1482. ) ||
  1483. functionBody->GetDefaultFunctionEntryPointInfo()->entryPointIndex > function->GetFunctionEntryPointInfo()->entryPointIndex);
  1484. return (scriptContext->CurrentThunk == ProfileEntryThunk) ? ProfileEntryThunk : originalEntryPoint;
  1485. }
  1486. return CheckCodeGenDone(functionBody, entryPoint, function);
  1487. }
  1488. Js::JavascriptMethod
  1489. NativeCodeGenerator::CheckCodeGenDone(
  1490. Js::FunctionBody *const functionBody,
  1491. Js::FunctionEntryPointInfo *const entryPointInfo,
  1492. Js::ScriptFunction * function)
  1493. {
  1494. Assert(!function || function->GetFunctionBody() == functionBody);
  1495. Assert(!function || function->GetFunctionEntryPointInfo() == entryPointInfo);
  1496. // Job was processed or failed and cleaned up
  1497. // We won't call CheckCodeGenDone if the job is still pending since
  1498. // PrioritizeJob will return false
  1499. Assert(entryPointInfo->IsCodeGenDone() || entryPointInfo->IsCleanedUp() || entryPointInfo->IsPendingCleanup());
  1500. if (!functionBody->GetHasBailoutInstrInJittedCode() && functionBody->GetHasAllocatedLoopHeaders()
  1501. #ifdef ASMJS_PLAT
  1502. && (!functionBody->GetIsAsmJsFunction() || !(((Js::FunctionEntryPointInfo*)functionBody->GetDefaultEntryPointInfo())->GetIsTJMode()))
  1503. #endif
  1504. )
  1505. {
  1506. if (functionBody->GetCanReleaseLoopHeaders())
  1507. {
  1508. functionBody->ReleaseLoopHeaders();
  1509. }
  1510. else
  1511. {
  1512. functionBody->SetPendingLoopHeaderRelease(true);
  1513. }
  1514. }
  1515. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1516. if (!functionBody->GetNativeEntryPointUsed())
  1517. {
  1518. #ifdef BGJIT_STATS
  1519. scriptContext->jitCodeUsed += functionBody->GetByteCodeCount();
  1520. scriptContext->funcJitCodeUsed++;
  1521. #endif
  1522. functionBody->SetNativeEntryPointUsed(true);
  1523. }
  1524. // Replace the entry point
  1525. Js::JavascriptMethod jsMethod;
  1526. if (!entryPointInfo->IsCodeGenDone())
  1527. {
  1528. if (entryPointInfo->IsPendingCleanup())
  1529. {
  1530. entryPointInfo->Cleanup(false /* isShutdown */, true /* capture cleanup stack */);
  1531. }
  1532. // Do not profile WebAssembly functions
  1533. jsMethod = (functionBody->GetScriptContext()->CurrentThunk == ProfileEntryThunk
  1534. && !functionBody->IsWasmFunction()) ? ProfileEntryThunk : functionBody->GetOriginalEntryPoint();
  1535. entryPointInfo->jsMethod = jsMethod;
  1536. }
  1537. else
  1538. {
  1539. scriptContext->GetNativeCodeGenerator()->SetNativeEntryPoint(
  1540. entryPointInfo,
  1541. functionBody,
  1542. entryPointInfo->GetNativeEntrypoint());
  1543. jsMethod = entryPointInfo->jsMethod;
  1544. Assert(!functionBody->NeedEnsureDynamicProfileInfo() || jsMethod == Js::DynamicProfileInfo::EnsureDynamicProfileInfoThunk || functionBody->GetIsAsmjsMode());
  1545. if (functionBody->GetIsAsmjsMode() && functionBody->NeedEnsureDynamicProfileInfo())
  1546. {
  1547. functionBody->EnsureDynamicProfileInfo();
  1548. }
  1549. }
  1550. Assert(!IsThunk(jsMethod));
  1551. if(function)
  1552. {
  1553. function->UpdateThunkEntryPoint(entryPointInfo, jsMethod);
  1554. }
  1555. // call the direct entry point, which will ensure dynamic profile info if necessary
  1556. return jsMethod;
  1557. }
  1558. CodeGenWorkItem *
  1559. NativeCodeGenerator::GetJob(Js::EntryPointInfo * const entryPoint) const
  1560. {
  1561. ASSERT_THREAD();
  1562. Assert(entryPoint);
  1563. return entryPoint->GetWorkItem();
  1564. }
  1565. bool
  1566. NativeCodeGenerator::WasAddedToJobProcessor(JsUtil::Job *const job) const
  1567. {
  1568. // This function is called from inside the lock
  1569. ASSERT_THREAD();
  1570. Assert(job);
  1571. return static_cast<CodeGenWorkItem *>(job)->IsInJitQueue();
  1572. }
  1573. bool
  1574. NativeCodeGenerator::ShouldProcessInForeground(const bool willWaitForJob, const unsigned int numJobsInQueue) const
  1575. {
  1576. // This function is called from inside the lock
  1577. ASSERT_THREAD();
  1578. // Process the job synchronously in the foreground thread if we're waiting for the job to be processed, or if the background
  1579. // job queue is long enough and this native code generator is optimized for many instances (web workers)
  1580. return
  1581. willWaitForJob ||
  1582. (numJobsInQueue > (uint)CONFIG_FLAG(HybridFgJitBgQueueLengthThreshold) &&
  1583. (CONFIG_FLAG(HybridFgJit) || isOptimizedForManyInstances));
  1584. }
  1585. void
  1586. NativeCodeGenerator::PrioritizedButNotYetProcessed(JsUtil::Job *const job)
  1587. {
  1588. // This function is called from inside the lock
  1589. ASSERT_THREAD();
  1590. Assert(job);
  1591. CodeGenWorkItem *const codeGenWorkItem = static_cast<CodeGenWorkItem *>(job);
  1592. if(codeGenWorkItem->Type() == JsFunctionType && codeGenWorkItem->IsInJitQueue())
  1593. {
  1594. #ifdef BGJIT_STATS
  1595. codeGenWorkItem->GetScriptContext()->interpretedCallsHighPri++;
  1596. #endif
  1597. if(codeGenWorkItem->GetJitMode() == ExecutionMode::FullJit)
  1598. {
  1599. QueuedFullJitWorkItem *const queuedFullJitWorkItem = codeGenWorkItem->GetQueuedFullJitWorkItem();
  1600. if(queuedFullJitWorkItem)
  1601. {
  1602. queuedFullJitWorkItems.MoveToBeginning(queuedFullJitWorkItem);
  1603. }
  1604. }
  1605. }
  1606. }
  1607. void
  1608. NativeCodeGenerator::BeforeWaitForJob(Js::EntryPointInfo *const entryPoint) const
  1609. {
  1610. ASSERT_THREAD();
  1611. Assert(entryPoint);
  1612. #ifdef PROFILE_EXEC
  1613. ProfileBegin(this->foregroundCodeGenProfiler, Js::DelayPhase);
  1614. #endif
  1615. }
  1616. void
  1617. NativeCodeGenerator::AfterWaitForJob(Js::EntryPointInfo *const entryPoint) const
  1618. {
  1619. ASSERT_THREAD();
  1620. Assert(entryPoint);
  1621. #ifdef PROFILE_EXEC
  1622. ProfileEnd(this->foregroundCodeGenProfiler, Js::DelayPhase);
  1623. #endif
  1624. }
  1625. /*
  1626. * A workitem exceeds JIT limits if we've already generated MaxThreadJITCodeHeapSize
  1627. * (currently 7 MB) of code on this thread or MaxProcessJITCodeHeapSize (currently 55 MB)
  1628. * in the process. In real world websites we rarely (if at all) hit this limit.
  1629. * Also, if this workitem's byte code size is in excess of MaxJITFunctionBytecodeSize instructions,
  1630. * it exceeds the JIT limits
  1631. */
  1632. bool
  1633. NativeCodeGenerator::WorkItemExceedsJITLimits(CodeGenWorkItem *const codeGenWork)
  1634. {
  1635. return
  1636. (codeGenWork->GetScriptContext()->GetThreadContext()->GetCodeSize() >= Js::Constants::MaxThreadJITCodeHeapSize) ||
  1637. (ThreadContext::GetProcessCodeSize() >= Js::Constants::MaxProcessJITCodeHeapSize) ||
  1638. (codeGenWork->GetByteCodeLength() >= (uint)CONFIG_FLAG(MaxJITFunctionBytecodeByteLength)) ||
  1639. (codeGenWork->GetByteCodeCount() >= (uint)CONFIG_FLAG(MaxJITFunctionBytecodeCount));
  1640. }
  1641. bool
  1642. NativeCodeGenerator::Process(JsUtil::Job *const job, JsUtil::ParallelThreadData *threadData)
  1643. {
  1644. const bool foreground = !threadData;
  1645. PageAllocator *pageAllocator;
  1646. if (foreground)
  1647. {
  1648. pageAllocator = scriptContext->GetThreadContext()->GetPageAllocator();
  1649. }
  1650. else
  1651. {
  1652. pageAllocator = threadData->GetPageAllocator();
  1653. }
  1654. CodeGenWorkItem *const codeGenWork = static_cast<CodeGenWorkItem *>(job);
  1655. switch (codeGenWork->Type())
  1656. {
  1657. case JsLoopBodyWorkItemType:
  1658. {
  1659. JsLoopBodyCodeGen* loopBodyCodeGenWorkItem = (JsLoopBodyCodeGen*)codeGenWork;
  1660. Js::FunctionBody* fn = loopBodyCodeGenWorkItem->GetFunctionBody();
  1661. if (fn->GetNativeEntryPointUsed() && fn->GetCanReleaseLoopHeaders()
  1662. #ifdef ASMJS_PLAT
  1663. && (!fn->GetIsAsmJsFunction() || !(loopBodyCodeGenWorkItem->loopHeader->GetCurrentEntryPointInfo()->GetIsTJMode()))
  1664. #endif
  1665. )
  1666. {
  1667. loopBodyCodeGenWorkItem->loopHeader->ResetInterpreterCount();
  1668. return false;
  1669. }
  1670. // Unless we're in a ForceNative configuration, ignore this workitem if it exceeds JIT limits
  1671. if (fn->ForceJITLoopBody() || !WorkItemExceedsJITLimits(codeGenWork))
  1672. {
  1673. CodeGen(pageAllocator, codeGenWork, foreground);
  1674. return true;
  1675. }
  1676. Js::EntryPointInfo * entryPoint = loopBodyCodeGenWorkItem->GetEntryPoint();
  1677. entryPoint->SetJITCapReached();
  1678. return false;
  1679. }
  1680. case JsFunctionType:
  1681. {
  1682. // Unless we're in a ForceNative configuration, ignore this workitem if it exceeds JIT limits
  1683. if (IS_PREJIT_ON() || Js::Configuration::Global.flags.ForceNative || !WorkItemExceedsJITLimits(codeGenWork))
  1684. {
  1685. CodeGen(pageAllocator, codeGenWork, foreground);
  1686. return true;
  1687. }
  1688. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1689. job->failureReason = Job::FailureReason::ExceedJITLimit;
  1690. #endif
  1691. return false;
  1692. }
  1693. default:
  1694. Assume(UNREACHED);
  1695. }
  1696. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1697. job->failureReason = Job::FailureReason::Unknown;
  1698. #endif
  1699. return false;
  1700. }
  1701. void
  1702. NativeCodeGenerator::Prioritize(JsUtil::Job *const job, const bool forceAddJobToProcessor, void* function)
  1703. {
  1704. // This function is called from inside the lock
  1705. ASSERT_THREAD();
  1706. Assert(job);
  1707. Assert(static_cast<const CodeGenWorkItem *>(job)->Type() == CodeGenWorkItemType::JsFunctionType);
  1708. Assert(!WasAddedToJobProcessor(job));
  1709. JsFunctionCodeGen *const workItem = static_cast<JsFunctionCodeGen *>(job);
  1710. Js::FunctionBody *const functionBody = workItem->GetFunctionBody();
  1711. Assert(workItem->GetEntryPoint() == functionBody->GetDefaultFunctionEntryPointInfo());
  1712. ExecutionMode jitMode;
  1713. if (functionBody->GetIsAsmjsMode())
  1714. {
  1715. jitMode = ExecutionMode::FullJit;
  1716. functionBody->SetAsmJsExecutionMode();
  1717. }
  1718. else
  1719. {
  1720. if (!forceAddJobToProcessor)
  1721. {
  1722. if (!functionBody->TryTransitionToJitExecutionMode())
  1723. {
  1724. return;
  1725. }
  1726. #if ENABLE_OOP_NATIVE_CODEGEN
  1727. // If for some reason OOP JIT isn't connected (e.g. it crashed), don't attempt to JIT
  1728. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !JITManager::GetJITManager()->IsConnected())
  1729. {
  1730. return;
  1731. }
  1732. #endif
  1733. }
  1734. jitMode = functionBody->GetExecutionMode();
  1735. Assert(jitMode == ExecutionMode::SimpleJit || jitMode == ExecutionMode::FullJit);
  1736. }
  1737. workItems.Unlink(workItem);
  1738. workItem->SetJitMode(jitMode);
  1739. try
  1740. {
  1741. // Prioritize full JIT work items over simple JIT work items. This simple solution seems sufficient for now, but it
  1742. // might be better to use a priority queue if it becomes necessary to prioritize recent simple JIT work items relative
  1743. // to the older simple JIT work items.
  1744. AddToJitQueue(
  1745. workItem,
  1746. jitMode == ExecutionMode::FullJit || queuedFullJitWorkItemCount == 0 /* prioritize */,
  1747. false /* lock */,
  1748. function);
  1749. }
  1750. catch (...)
  1751. {
  1752. // Add the item back to the list if AddToJitQueue throws. The position in the list is not important.
  1753. workItem->ResetJitMode();
  1754. workItems.LinkToEnd(workItem);
  1755. throw;
  1756. }
  1757. }
  1758. ExecutionMode NativeCodeGenerator::PrejitJitMode(Js::FunctionBody *const functionBody)
  1759. {
  1760. Assert(IS_PREJIT_ON() || functionBody->GetIsAsmjsMode());
  1761. Assert(functionBody->DoSimpleJit() || !PHASE_OFF(Js::FullJitPhase, functionBody));
  1762. // Prefer full JIT for prejitting unless it's off or simple JIT is forced
  1763. return
  1764. !PHASE_OFF(Js::FullJitPhase, functionBody) && !(PHASE_FORCE(Js::Phase::SimpleJitPhase, functionBody) && functionBody->DoSimpleJit())
  1765. ? ExecutionMode::FullJit
  1766. : ExecutionMode::SimpleJit;
  1767. }
  1768. void
  1769. NativeCodeGenerator::UpdateQueueForDebugMode()
  1770. {
  1771. Assert(!this->hasUpdatedQForDebugMode);
  1772. // If we're going to debug mode, drain the job processors queue of
  1773. // all jobs belonging this native code generator
  1774. // JobProcessed will be called for existing jobs, and in debug mode
  1775. // that method will simply add them back to the NativeCodeGen's queue
  1776. Processor()->RemoveManager(this);
  1777. this->hasUpdatedQForDebugMode = true;
  1778. Processor()->AddManager(this);
  1779. }
  1780. void
  1781. NativeCodeGenerator::JobProcessed(JsUtil::Job *const job, const bool succeeded)
  1782. {
  1783. // This function is called from inside the lock
  1784. Assert(job);
  1785. CodeGenWorkItem *workItem = static_cast<CodeGenWorkItem *>(job);
  1786. class AutoCleanup
  1787. {
  1788. private:
  1789. Js::ScriptContext *const scriptContext;
  1790. Js::CodeGenRecyclableData *const recyclableData;
  1791. public:
  1792. AutoCleanup(Js::ScriptContext *const scriptContext, Js::CodeGenRecyclableData *const recyclableData)
  1793. : scriptContext(scriptContext), recyclableData(recyclableData)
  1794. {
  1795. Assert(scriptContext);
  1796. }
  1797. ~AutoCleanup()
  1798. {
  1799. if(recyclableData)
  1800. {
  1801. scriptContext->GetThreadContext()->UnregisterCodeGenRecyclableData(recyclableData);
  1802. }
  1803. }
  1804. } autoCleanup(scriptContext, workItem->RecyclableData());
  1805. const ExecutionMode jitMode = workItem->GetJitMode();
  1806. if(jitMode == ExecutionMode::FullJit && workItem->IsInJitQueue())
  1807. {
  1808. QueuedFullJitWorkItem *const queuedFullJitWorkItem = workItem->GetQueuedFullJitWorkItem();
  1809. if(queuedFullJitWorkItem)
  1810. {
  1811. queuedFullJitWorkItems.Unlink(queuedFullJitWorkItem);
  1812. --queuedFullJitWorkItemCount;
  1813. }
  1814. }
  1815. Js::FunctionBody* functionBody = nullptr;
  1816. CodeGenWorkItemType workitemType = workItem->Type();
  1817. if (workitemType == JsFunctionType)
  1818. {
  1819. JsFunctionCodeGen * functionCodeGen = (JsFunctionCodeGen *)workItem;
  1820. functionBody = functionCodeGen->GetFunctionBody();
  1821. if (succeeded)
  1822. {
  1823. Js::FunctionEntryPointInfo* entryPointInfo = static_cast<Js::FunctionEntryPointInfo*>(functionCodeGen->GetEntryPoint());
  1824. entryPointInfo->SetJitMode(jitMode);
  1825. entryPointInfo->SetCodeGenDone();
  1826. }
  1827. else
  1828. {
  1829. #if DBG
  1830. functionBody->m_nativeEntryPointIsInterpreterThunk = true;
  1831. #endif
  1832. // It's okay if the entry point has been reclaimed at this point
  1833. // since the job failed anyway so the entry point should never get used
  1834. // If it's still around, clean it up. If not, its finalizer would clean
  1835. // it up anyway.
  1836. Js::EntryPointInfo* entryPointInfo = functionCodeGen->GetEntryPoint();
  1837. if (entryPointInfo)
  1838. {
  1839. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  1840. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1841. switch (job->failureReason)
  1842. {
  1843. case Job::FailureReason::OOM: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedOOM); break;
  1844. case Job::FailureReason::StackOverflow: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedStackOverflow); break;
  1845. case Job::FailureReason::Aborted: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedAborted); break;
  1846. case Job::FailureReason::ExceedJITLimit: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedExceedJITLimit); break;
  1847. case Job::FailureReason::Unknown: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedUnknown); break;
  1848. default: Assert(job->failureReason == Job::FailureReason::NotFailed);
  1849. }
  1850. #endif
  1851. #endif
  1852. entryPointInfo->SetPendingCleanup();
  1853. }
  1854. functionCodeGen->OnWorkItemProcessFail(this);
  1855. }
  1856. InterlockedDecrement(&pendingCodeGenWorkItems);
  1857. HeapDelete(functionCodeGen);
  1858. }
  1859. else if (workitemType == JsLoopBodyWorkItemType)
  1860. {
  1861. JsLoopBodyCodeGen * loopBodyCodeGen = (JsLoopBodyCodeGen*)workItem;
  1862. functionBody = loopBodyCodeGen->GetFunctionBody();
  1863. Js::EntryPointInfo * entryPoint = loopBodyCodeGen->GetEntryPoint();
  1864. if (succeeded)
  1865. {
  1866. Assert(loopBodyCodeGen->GetCodeAddress() != NULL);
  1867. uint loopNum = loopBodyCodeGen->GetJITData()->loopNumber;
  1868. functionBody->SetLoopBodyEntryPoint(loopBodyCodeGen->loopHeader, entryPoint, (Js::JavascriptMethod)loopBodyCodeGen->GetCodeAddress(), loopNum);
  1869. entryPoint->SetCodeGenDone();
  1870. }
  1871. else
  1872. {
  1873. // We re-use failed loop body entry points.
  1874. // The loop body entry point could have been cleaned up if the parent function JITed,
  1875. // in which case we don't want to reset it.
  1876. if (entryPoint && !entryPoint->IsCleanedUp())
  1877. {
  1878. entryPoint->Reset(!entryPoint->IsJITCapReached()); // reset state to NotScheduled if JIT cap hasn't been reached
  1879. }
  1880. loopBodyCodeGen->OnWorkItemProcessFail(this);
  1881. }
  1882. HeapDelete(loopBodyCodeGen);
  1883. }
  1884. else
  1885. {
  1886. AssertMsg(false, "Unknown work item type");
  1887. }
  1888. }
  1889. void
  1890. NativeCodeGenerator::UpdateJITState()
  1891. {
  1892. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  1893. {
  1894. // TODO: OOP JIT, move server calls to background thread to reduce foreground thread delay
  1895. if (!this->scriptContext->GetRemoteScriptAddr() || !JITManager::GetJITManager()->IsConnected())
  1896. {
  1897. return;
  1898. }
  1899. if (scriptContext->GetThreadContext()->JITNeedsPropUpdate())
  1900. {
  1901. typedef BVSparseNode<JitArenaAllocator> BVSparseNode;
  1902. CompileAssert(sizeof(BVSparseNode) == sizeof(BVSparseNodeIDL));
  1903. BVSparseNodeIDL * bvHead = (BVSparseNodeIDL*)scriptContext->GetThreadContext()->GetJITNumericProperties()->head;
  1904. HRESULT hr = JITManager::GetJITManager()->UpdatePropertyRecordMap(scriptContext->GetThreadContext()->GetRemoteThreadContextAddr(), bvHead);
  1905. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1906. scriptContext->GetThreadContext()->ResetJITNeedsPropUpdate();
  1907. }
  1908. }
  1909. }
  1910. JsUtil::Job *
  1911. NativeCodeGenerator::GetJobToProcessProactively()
  1912. {
  1913. ASSERT_THREAD();
  1914. // Look for work, starting with high priority items first, and above LowPri
  1915. CodeGenWorkItem* workItem = workItems.Head();
  1916. while(workItem != nullptr)
  1917. {
  1918. if(workItem->ShouldSpeculativelyJit(this->byteCodeSizeGenerated))
  1919. {
  1920. workItem->SetJitMode(ExecutionMode::FullJit);
  1921. // Note: This gives a perf regression in fre build, but it is useful for debugging and won't be there for the final build
  1922. // anyway, so I left it in.
  1923. if (PHASE_TRACE(Js::DelayPhase, workItem->GetFunctionBody())) {
  1924. OUTPUT_TRACE(Js::DelayPhase, _u("ScriptContext: 0x%p, Speculative JIT: %-25s, Byte code generated: %d \n"),
  1925. this->scriptContext, workItem->GetFunctionBody()->GetExternalDisplayName(), this->byteCodeSizeGenerated);
  1926. }
  1927. Js::FunctionBody *fn = workItem->GetFunctionBody();
  1928. Js::EntryPointInfo *entryPoint = workItem->GetEntryPoint();
  1929. const auto recyclableData = GatherCodeGenData(fn, fn, entryPoint, workItem);
  1930. workItems.Unlink(workItem);
  1931. workItem->SetRecyclableData(recyclableData);
  1932. {
  1933. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  1934. scriptContext->GetThreadContext()->RegisterCodeGenRecyclableData(recyclableData);
  1935. }
  1936. #ifdef BGJIT_STATS
  1937. scriptContext->speculativeJitCount++;
  1938. #endif
  1939. QueuedFullJitWorkItem *const queuedFullJitWorkItem = workItem->EnsureQueuedFullJitWorkItem();
  1940. if(queuedFullJitWorkItem) // ignore OOM, this work item just won't be removed from the job processor's queue
  1941. {
  1942. queuedFullJitWorkItems.LinkToBeginning(queuedFullJitWorkItem);
  1943. ++queuedFullJitWorkItemCount;
  1944. }
  1945. workItem->OnAddToJitQueue();
  1946. workItem->GetFunctionBody()->TraceExecutionMode("SpeculativeJit (before)");
  1947. workItem->GetFunctionBody()->TransitionToFullJitExecutionMode();
  1948. workItem->GetFunctionBody()->TraceExecutionMode("SpeculativeJit");
  1949. break;
  1950. }
  1951. workItem = static_cast<CodeGenWorkItem*>(workItem->Next());
  1952. }
  1953. return workItem;
  1954. }
  1955. // Removes all of the proactive jobs from the generator. Used when switching between attached/detached
  1956. // debug modes in order to drain the queue of jobs (since we switch from interpreted to native and back).
  1957. void
  1958. NativeCodeGenerator::RemoveProactiveJobs()
  1959. {
  1960. CodeGenWorkItem* workItem = workItems.Head();
  1961. while (workItem)
  1962. {
  1963. CodeGenWorkItem* temp = static_cast<CodeGenWorkItem*>(workItem->Next());
  1964. workItem->Delete();
  1965. workItem = temp;
  1966. }
  1967. workItems.Clear();
  1968. //for(JsUtil::Job *job = workItems.Head(); job;)
  1969. //{
  1970. // JsUtil::Job *const next = job->Next();
  1971. // JobProcessed(job, /*succeeded*/ false);
  1972. // job = next;
  1973. //}
  1974. }
  1975. template<bool IsInlinee>
  1976. void
  1977. NativeCodeGenerator::GatherCodeGenData(
  1978. Recycler *const recycler,
  1979. Js::FunctionBody *const topFunctionBody,
  1980. Js::FunctionBody *const functionBody,
  1981. Js::EntryPointInfo *const entryPoint,
  1982. InliningDecider &inliningDecider,
  1983. ObjTypeSpecFldInfoList *objTypeSpecFldInfoList,
  1984. Js::FunctionCodeGenJitTimeData *const jitTimeData,
  1985. Js::FunctionCodeGenRuntimeData *const runtimeData,
  1986. Js::JavascriptFunction* function,
  1987. bool isJitTimeDataComputed,
  1988. uint32 recursiveInlineDepth)
  1989. {
  1990. ASSERT_THREAD();
  1991. Assert(recycler);
  1992. Assert(functionBody);
  1993. Assert(jitTimeData);
  1994. Assert(IsInlinee == !!runtimeData);
  1995. Assert(!IsInlinee || (!inliningDecider.GetIsLoopBody() || !PHASE_OFF(Js::InlineInJitLoopBodyPhase, topFunctionBody)));
  1996. Assert(topFunctionBody != nullptr && (!entryPoint->GetWorkItem() || entryPoint->GetWorkItem()->GetFunctionBody() == topFunctionBody));
  1997. Assert(objTypeSpecFldInfoList != nullptr);
  1998. #ifdef FIELD_ACCESS_STATS
  1999. jitTimeData->EnsureInlineCacheStats(recycler);
  2000. #define SetInlineCacheCount(counter, value) jitTimeData->inlineCacheStats->counter = value;
  2001. #define IncInlineCacheCount(counter) if(!isJitTimeDataComputed) {jitTimeData->inlineCacheStats->counter++;}
  2002. #define AddInlineCacheStats(callerData, inlineeData) callerData->AddInlineeInlineCacheStats(inlineeData);
  2003. #define InlineCacheStatsArg(jitTimeData) !isJitTimeDataComputed ? jitTimeData->inlineCacheStats : nullptr
  2004. #else
  2005. #define SetInlineCacheCount(counter, value)
  2006. #define IncInlineCacheCount(counter)
  2007. #define AddInlineCacheStats(callerData, inlineeData)
  2008. #define InlineCacheStatsArg(jitTimeData) nullptr
  2009. #endif
  2010. #if DBG
  2011. Assert(
  2012. PHASE_ON(Js::Phase::SimulatePolyCacheWithOneTypeForFunctionPhase, functionBody) ==
  2013. CONFIG_ISENABLED(Js::Flag::SimulatePolyCacheWithOneTypeForInlineCacheIndexFlag));
  2014. if (PHASE_ON(Js::Phase::SimulatePolyCacheWithOneTypeForFunctionPhase, functionBody))
  2015. {
  2016. const Js::InlineCacheIndex inlineCacheIndex = CONFIG_FLAG(SimulatePolyCacheWithOneTypeForInlineCacheIndex);
  2017. functionBody->CreateNewPolymorphicInlineCache(
  2018. inlineCacheIndex,
  2019. functionBody->GetPropertyIdFromCacheId(inlineCacheIndex),
  2020. functionBody->GetInlineCache(inlineCacheIndex));
  2021. if (functionBody->HasDynamicProfileInfo())
  2022. {
  2023. functionBody->GetAnyDynamicProfileInfo()->RecordPolymorphicFieldAccess(functionBody, inlineCacheIndex);
  2024. }
  2025. }
  2026. #endif
  2027. NativeEntryPointData * nativeEntryPointData;
  2028. if (IsInlinee)
  2029. {
  2030. // This function is recursive
  2031. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackDefault);
  2032. nativeEntryPointData = entryPoint->GetNativeEntryPointData();;
  2033. }
  2034. else
  2035. {
  2036. // TODO: For now, we create the native entry point data and the jit transfer data when we queue up
  2037. // the entry point for code gen, but not clear/free then then the work item got knocked off the queue
  2038. // without code gen happening.
  2039. nativeEntryPointData = entryPoint->EnsureNativeEntryPointData();
  2040. nativeEntryPointData->EnsureJitTransferData(recycler);
  2041. //TryAggressiveInlining adjusts inlining heuristics and walks the call tree. If it can inlining everything it will set the InliningThreshold to be aggressive.
  2042. if (!inliningDecider.GetIsLoopBody())
  2043. {
  2044. uint32 inlineeCount = 0;
  2045. if (!PHASE_OFF(Js::TryAggressiveInliningPhase, topFunctionBody))
  2046. {
  2047. Assert(topFunctionBody == functionBody);
  2048. inliningDecider.SetAggressiveHeuristics();
  2049. if (!TryAggressiveInlining(topFunctionBody, functionBody, inliningDecider, inlineeCount, 0))
  2050. {
  2051. uint countOfInlineesWithLoops = inliningDecider.GetNumberOfInlineesWithLoop();
  2052. //TryAggressiveInlining failed, set back to default heuristics.
  2053. inliningDecider.ResetInlineHeuristics();
  2054. inliningDecider.SetLimitOnInlineesWithLoop(countOfInlineesWithLoops);
  2055. }
  2056. else
  2057. {
  2058. jitTimeData->SetIsAggressiveInliningEnabled();
  2059. }
  2060. inliningDecider.ResetState();
  2061. }
  2062. }
  2063. nativeEntryPointData->EnsurePolymorphicInlineCacheInfo(recycler, functionBody);
  2064. }
  2065. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2066. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2067. #endif
  2068. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2069. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2070. {
  2071. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s): GatherCodeGenData(): \n"),
  2072. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer));
  2073. Output::Flush();
  2074. }
  2075. #endif
  2076. const auto profileData =
  2077. functionBody->HasDynamicProfileInfo()
  2078. ? functionBody->GetAnyDynamicProfileInfo()
  2079. : functionBody->EnsureDynamicProfileInfo();
  2080. bool inlineGetterSetter = false;
  2081. bool inlineApplyTarget = false; //to indicate whether we can inline apply target or not.
  2082. bool inlineCallTarget = false;
  2083. if (profileData)
  2084. {
  2085. if (!IsInlinee)
  2086. {
  2087. PHASE_PRINT_TRACE(
  2088. Js::ObjTypeSpecPhase, functionBody,
  2089. _u("Objtypespec (%s): Pending cache state on add %x to JIT queue: %d\n"),
  2090. functionBody->GetDebugNumberSet(debugStringBuffer), entryPoint, profileData->GetPolymorphicCacheState());
  2091. nativeEntryPointData->SetPendingPolymorphicCacheState(profileData->GetPolymorphicCacheState());
  2092. nativeEntryPointData->SetPendingInlinerVersion(profileData->GetInlinerVersion());
  2093. nativeEntryPointData->SetPendingImplicitCallFlags(profileData->GetImplicitCallFlags());
  2094. }
  2095. if (functionBody->GetProfiledArrayCallSiteCount() != 0)
  2096. {
  2097. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = recycler->CreateWeakReferenceHandle(functionBody);
  2098. if (!isJitTimeDataComputed)
  2099. {
  2100. jitTimeData->SetWeakFuncRef(weakFuncRef);
  2101. }
  2102. entryPoint->GetNativeEntryPointData()->AddWeakFuncRef(weakFuncRef, recycler);
  2103. }
  2104. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2105. if (PHASE_VERBOSE_TESTTRACE(Js::ObjTypeSpecPhase, functionBody) ||
  2106. PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  2107. {
  2108. if (functionBody->GetInlineCacheCount() > 0)
  2109. {
  2110. if (!IsInlinee)
  2111. {
  2112. Output::Print(_u("-----------------------------------------------------------------------------\n"));
  2113. }
  2114. else
  2115. {
  2116. Output::Print(_u("\tInlinee:\t"));
  2117. }
  2118. functionBody->DumpFullFunctionName();
  2119. Output::Print(_u("\n"));
  2120. }
  2121. }
  2122. #endif
  2123. SetInlineCacheCount(totalInlineCacheCount, functionBody->GetInlineCacheCount());
  2124. Assert(functionBody->GetProfiledFldCount() == functionBody->GetInlineCacheCount()); // otherwise, isInst inline caches need to be cloned
  2125. for(uint i = 0; i < functionBody->GetInlineCacheCount(); ++i)
  2126. {
  2127. const auto cacheType = profileData->GetFldInfo(functionBody, i)->flags;
  2128. PHASE_PRINT_VERBOSE_TESTTRACE(
  2129. Js::ObjTypeSpecPhase, functionBody,
  2130. _u("Cache #%3d, Layout: %s, Profile info: %s\n"),
  2131. i,
  2132. functionBody->GetInlineCache(i)->LayoutString(),
  2133. cacheType == Js::FldInfo_NoInfo ? _u("none") :
  2134. (cacheType & Js::FldInfo_Polymorphic) ? _u("polymorphic") : _u("monomorphic"));
  2135. if (cacheType == Js::FldInfo_NoInfo)
  2136. {
  2137. IncInlineCacheCount(noInfoInlineCacheCount);
  2138. continue;
  2139. }
  2140. Js::PolymorphicInlineCache * polymorphicCacheOnFunctionBody = functionBody->GetPolymorphicInlineCache(i);
  2141. bool isPolymorphic = (cacheType & Js::FldInfo_Polymorphic) != 0;
  2142. if (!isPolymorphic)
  2143. {
  2144. Js::InlineCache *inlineCache = nullptr;
  2145. if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function))
  2146. {
  2147. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2148. {
  2149. inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i);
  2150. }
  2151. }
  2152. else
  2153. {
  2154. inlineCache = functionBody->GetInlineCache(i);
  2155. }
  2156. if (inlineCache != nullptr)
  2157. {
  2158. ObjTypeSpecFldInfo* objTypeSpecFldInfo = nullptr;
  2159. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2160. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2161. {
  2162. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2163. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2164. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2165. Output::Print(_u("ObTypeSpec: top function %s (%s), function %s (%s): cloning mono cache for %s (#%d) cache %d \n"),
  2166. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer),
  2167. functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2), propertyRecord->GetBuffer(), propertyId, i);
  2168. Output::Flush();
  2169. }
  2170. #endif
  2171. IncInlineCacheCount(monoInlineCacheCount);
  2172. if (inlineCache->IsEmpty())
  2173. {
  2174. IncInlineCacheCount(emptyMonoInlineCacheCount);
  2175. }
  2176. if(!PHASE_OFF(Js::ObjTypeSpecPhase, functionBody) || !PHASE_OFF(Js::FixedMethodsPhase, functionBody) || !PHASE_OFF(Js::UseFixedDataPropsPhase, functionBody))
  2177. {
  2178. if(cacheType & (Js::FldInfo_FromLocal | Js::FldInfo_FromLocalWithoutProperty | Js::FldInfo_FromProto))
  2179. {
  2180. // WinBlue 170722: Disable ObjTypeSpec optimization for activation object in debug mode,
  2181. // as it can result in BailOutFailedTypeCheck before locals are set to undefined,
  2182. // which can result in using garbage object during bailout/restore values.
  2183. if (!(functionBody->IsInDebugMode() && inlineCache->GetType() &&
  2184. inlineCache->GetType()->GetTypeId() == Js::TypeIds_ActivationObject))
  2185. {
  2186. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2187. if (objTypeSpecFldInfo)
  2188. {
  2189. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2190. if (!PHASE_OFF(Js::InlineApplyTargetPhase, functionBody) && (cacheType & Js::FldInfo_InlineCandidate))
  2191. {
  2192. if (IsInlinee || objTypeSpecFldInfo->IsBuiltin())
  2193. {
  2194. inlineApplyTarget = true;
  2195. }
  2196. }
  2197. if (!PHASE_OFF(Js::InlineCallTargetPhase, functionBody) && (cacheType & Js::FldInfo_InlineCandidate))
  2198. {
  2199. inlineCallTarget = true;
  2200. }
  2201. if (!isJitTimeDataComputed)
  2202. {
  2203. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2204. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2205. }
  2206. }
  2207. }
  2208. }
  2209. }
  2210. if(!PHASE_OFF(Js::FixAccessorPropsPhase, functionBody))
  2211. {
  2212. if (!objTypeSpecFldInfo && (cacheType & Js::FldInfo_FromAccessor) && (cacheType & Js::FldInfo_InlineCandidate))
  2213. {
  2214. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2215. if (objTypeSpecFldInfo)
  2216. {
  2217. inlineGetterSetter = true;
  2218. if (!isJitTimeDataComputed)
  2219. {
  2220. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2221. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2222. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2223. }
  2224. }
  2225. }
  2226. }
  2227. if (!PHASE_OFF(Js::RootObjectFldFastPathPhase, functionBody))
  2228. {
  2229. if (i >= functionBody->GetRootObjectLoadInlineCacheStart() && inlineCache->IsLocal())
  2230. {
  2231. void * rawType = inlineCache->u.local.type;
  2232. Js::Type * type = TypeWithoutAuxSlotTag(rawType);
  2233. Js::RootObjectBase * rootObject = functionBody->GetRootObject();
  2234. if (rootObject->GetType() == type)
  2235. {
  2236. Js::BigPropertyIndex propertyIndex = inlineCache->u.local.slotIndex;
  2237. if (rawType == type)
  2238. {
  2239. // type is not tagged, inline slot
  2240. propertyIndex = rootObject->GetPropertyIndexFromInlineSlotIndex(inlineCache->u.local.slotIndex);
  2241. }
  2242. else
  2243. {
  2244. propertyIndex = rootObject->GetPropertyIndexFromAuxSlotIndex(inlineCache->u.local.slotIndex);
  2245. }
  2246. Js::PropertyAttributes attributes;
  2247. if (rootObject->GetAttributesWithPropertyIndex(functionBody->GetPropertyIdFromCacheId(i), propertyIndex, &attributes)
  2248. && (attributes & PropertyConfigurable) == 0
  2249. && !isJitTimeDataComputed)
  2250. {
  2251. // non configurable
  2252. if (objTypeSpecFldInfo == nullptr)
  2253. {
  2254. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2255. if (objTypeSpecFldInfo)
  2256. {
  2257. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2258. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2259. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2260. }
  2261. }
  2262. if (objTypeSpecFldInfo != nullptr)
  2263. {
  2264. objTypeSpecFldInfo->SetRootObjectNonConfigurableField(i < functionBody->GetRootObjectStoreInlineCacheStart());
  2265. }
  2266. }
  2267. }
  2268. }
  2269. }
  2270. }
  2271. }
  2272. // Even if the FldInfo says that the field access may be polymorphic, be optimistic that if the function object has inline caches, they'll be monomorphic
  2273. else if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function) && (cacheType & Js::FldInfo_InlineCandidate || !polymorphicCacheOnFunctionBody))
  2274. {
  2275. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2276. {
  2277. Js::InlineCache *inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i);
  2278. ObjTypeSpecFldInfo* objTypeSpecFldInfo = nullptr;
  2279. if(!PHASE_OFF(Js::ObjTypeSpecPhase, functionBody) || !PHASE_OFF(Js::FixedMethodsPhase, functionBody))
  2280. {
  2281. if(cacheType & (Js::FldInfo_FromLocal | Js::FldInfo_FromProto)) // Remove FldInfo_FromLocal?
  2282. {
  2283. // WinBlue 170722: Disable ObjTypeSpec optimization for activation object in debug mode,
  2284. // as it can result in BailOutFailedTypeCheck before locals are set to undefined,
  2285. // which can result in using garbage object during bailout/restore values.
  2286. if (!(functionBody->IsInDebugMode() && inlineCache->GetType() &&
  2287. inlineCache->GetType()->GetTypeId() == Js::TypeIds_ActivationObject))
  2288. {
  2289. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2290. if (objTypeSpecFldInfo)
  2291. {
  2292. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2293. if (!PHASE_OFF(Js::InlineApplyTargetPhase, functionBody) && IsInlinee && (cacheType & Js::FldInfo_InlineCandidate))
  2294. {
  2295. inlineApplyTarget = true;
  2296. }
  2297. if (!isJitTimeDataComputed)
  2298. {
  2299. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2300. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2301. }
  2302. }
  2303. }
  2304. }
  2305. }
  2306. }
  2307. }
  2308. else
  2309. {
  2310. const auto polymorphicInlineCache = functionBody->GetPolymorphicInlineCache(i);
  2311. if (polymorphicInlineCache != nullptr)
  2312. {
  2313. IncInlineCacheCount(polyInlineCacheCount);
  2314. if (profileData->GetFldInfo(functionBody, i)->ShouldUsePolymorphicInlineCache())
  2315. {
  2316. IncInlineCacheCount(highUtilPolyInlineCacheCount);
  2317. }
  2318. else
  2319. {
  2320. IncInlineCacheCount(lowUtilPolyInlineCacheCount);
  2321. }
  2322. if (!PHASE_OFF(Js::EquivObjTypeSpecPhase, topFunctionBody) && !topFunctionBody->GetAnyDynamicProfileInfo()->IsEquivalentObjTypeSpecDisabled())
  2323. {
  2324. if (!polymorphicInlineCache->GetIgnoreForEquivalentObjTypeSpec() || (polymorphicInlineCache->GetCloneForJitTimeUse() && !PHASE_OFF(Js::PolymorphicInlinePhase, functionBody) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, functionBody)))
  2325. {
  2326. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2327. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2328. {
  2329. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2330. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2331. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2332. Output::Print(_u("ObTypeSpec: top function %s (%s), function %s (%s): cloning poly cache for %s (#%d) cache %d \n"),
  2333. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer),
  2334. functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2), propertyRecord->GetBuffer(), propertyId, i);
  2335. Output::Flush();
  2336. }
  2337. #endif
  2338. ObjTypeSpecFldInfo* objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), polymorphicInlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2339. if (objTypeSpecFldInfo != nullptr)
  2340. {
  2341. if (!isJitTimeDataComputed)
  2342. {
  2343. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2344. IncInlineCacheCount(clonedPolyInlineCacheCount);
  2345. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2346. }
  2347. if (!PHASE_OFF(Js::InlineAccessorsPhase, functionBody) && (cacheType & Js::FldInfo_FromAccessor) && (cacheType & Js::FldInfo_InlineCandidate))
  2348. {
  2349. inlineGetterSetter = true;
  2350. }
  2351. }
  2352. }
  2353. else
  2354. {
  2355. IncInlineCacheCount(ignoredPolyInlineCacheCount);
  2356. }
  2357. }
  2358. else
  2359. {
  2360. IncInlineCacheCount(disabledPolyInlineCacheCount);
  2361. }
  2362. }
  2363. else
  2364. {
  2365. IncInlineCacheCount(nullPolyInlineCacheCount);
  2366. }
  2367. if (polymorphicInlineCache != nullptr)
  2368. {
  2369. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2370. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  2371. {
  2372. if (IsInlinee) Output::Print(_u("\t"));
  2373. Output::Print(_u("\t%d: PIC size = %d\n"), i, polymorphicInlineCache->GetSize());
  2374. #if DBG_DUMP
  2375. polymorphicInlineCache->Dump();
  2376. #endif
  2377. }
  2378. else if (PHASE_TRACE1(Js::PolymorphicInlineCachePhase))
  2379. {
  2380. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2381. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2382. Output::Print(_u("Trace PIC JIT function %s (%s) field: %s (index: %d) \n"), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer),
  2383. propertyRecord->GetBuffer(), i);
  2384. }
  2385. #endif
  2386. byte polyCacheUtil = profileData->GetFldInfo(functionBody, i)->polymorphicInlineCacheUtilization;
  2387. nativeEntryPointData->GetPolymorphicInlineCacheInfo()->SetPolymorphicInlineCache(functionBody, i, polymorphicInlineCache, IsInlinee, polyCacheUtil);
  2388. if (IsInlinee)
  2389. {
  2390. Assert(nativeEntryPointData->GetPolymorphicInlineCacheInfo()->GetInlineeInfo(functionBody)->GetPolymorphicInlineCaches()->GetInlineCache(functionBody, i) == polymorphicInlineCache);
  2391. }
  2392. else
  2393. {
  2394. Assert(nativeEntryPointData->GetPolymorphicInlineCacheInfo()->GetSelfInfo()->GetPolymorphicInlineCaches()->GetInlineCache(functionBody, i) == polymorphicInlineCache);
  2395. }
  2396. }
  2397. else if(IsInlinee && CONFIG_FLAG(CloneInlinedPolymorphicCaches))
  2398. {
  2399. // Clone polymorphic inline caches for runtime usage in this inlinee. The JIT should only use the pointers to
  2400. // the inline caches, as their cached data is not guaranteed to be stable while jitting.
  2401. Js::InlineCache *const inlineCache =
  2402. function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function)
  2403. ? (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr ? Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i) : nullptr)
  2404. : functionBody->GetInlineCache(i);
  2405. if (inlineCache != nullptr)
  2406. {
  2407. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2408. const auto clone = runtimeData->ClonedInlineCaches()->GetInlineCache(functionBody, i);
  2409. if (clone)
  2410. {
  2411. inlineCache->CopyTo(propertyId, functionBody->GetScriptContext(), clone);
  2412. }
  2413. else
  2414. {
  2415. runtimeData->ClonedInlineCaches()->SetInlineCache(
  2416. recycler,
  2417. functionBody,
  2418. i,
  2419. inlineCache->Clone(propertyId, functionBody->GetScriptContext()));
  2420. }
  2421. }
  2422. }
  2423. }
  2424. }
  2425. }
  2426. // Gather code gen data for inlinees
  2427. if(IsInlinee ? !inliningDecider.InlineIntoInliner(functionBody) : !inliningDecider.InlineIntoTopFunc())
  2428. {
  2429. return;
  2430. }
  2431. class AutoCleanup
  2432. {
  2433. private:
  2434. Js::FunctionBody *const functionBody;
  2435. public:
  2436. AutoCleanup(Js::FunctionBody *const functionBody) : functionBody(functionBody)
  2437. {
  2438. functionBody->OnBeginInlineInto();
  2439. }
  2440. ~AutoCleanup()
  2441. {
  2442. functionBody->OnEndInlineInto();
  2443. }
  2444. } autoCleanup(functionBody);
  2445. const auto profiledCallSiteCount = functionBody->GetProfiledCallSiteCount();
  2446. Assert(profiledCallSiteCount != 0 || functionBody->GetAnyDynamicProfileInfo()->HasLdFldCallSiteInfo());
  2447. if (profiledCallSiteCount && !isJitTimeDataComputed)
  2448. {
  2449. jitTimeData->inlineesBv = BVFixed::New<Recycler>(profiledCallSiteCount, recycler);
  2450. }
  2451. // Iterate through profiled call sites recursively and determine what should be inlined
  2452. for(Js::ProfileId profiledCallSiteId = 0; profiledCallSiteId < profiledCallSiteCount; ++profiledCallSiteId)
  2453. {
  2454. Js::FunctionInfo *const inlinee = inliningDecider.InlineCallSite(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2455. if(!inlinee)
  2456. {
  2457. if (profileData->CallSiteHasProfileData(profiledCallSiteId))
  2458. {
  2459. jitTimeData->inlineesBv->Set(profiledCallSiteId);
  2460. }
  2461. //Try and see if this polymorphic call
  2462. Js::FunctionBody* inlineeFunctionBodyArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = {0};
  2463. bool canInlineArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  2464. uint polyInlineeCount = inliningDecider.InlinePolymorphicCallSite(functionBody, profiledCallSiteId, inlineeFunctionBodyArray,
  2465. Js::DynamicProfileInfo::maxPolymorphicInliningSize, canInlineArray);
  2466. //We should be able to inline at least two functions here.
  2467. if (polyInlineeCount >= 2)
  2468. {
  2469. for (uint id = 0; id < polyInlineeCount; id++)
  2470. {
  2471. bool isInlined = canInlineArray[id];
  2472. Js::FunctionCodeGenRuntimeData *inlineeRunTimeData = IsInlinee ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]) : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]);
  2473. if (!isJitTimeDataComputed)
  2474. {
  2475. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]->GetFunctionInfo(), isInlined);
  2476. if (isInlined)
  2477. {
  2478. GatherCodeGenData<true>(
  2479. recycler,
  2480. topFunctionBody,
  2481. inlineeFunctionBodyArray[id],
  2482. entryPoint,
  2483. inliningDecider,
  2484. objTypeSpecFldInfoList,
  2485. inlineeJitTimeData,
  2486. inlineeRunTimeData
  2487. );
  2488. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2489. }
  2490. }
  2491. }
  2492. }
  2493. }
  2494. else
  2495. {
  2496. jitTimeData->inlineesBv->Set(profiledCallSiteId);
  2497. Js::FunctionBody *const inlineeFunctionBody = inlinee->GetFunctionBody();
  2498. if(!inlineeFunctionBody )
  2499. {
  2500. if (!isJitTimeDataComputed)
  2501. {
  2502. jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2503. if (inlinee->IsBuiltInApplyFunction() || inlinee->IsBuiltInCallFunction())
  2504. {
  2505. // .call/.apply targets
  2506. Js::FunctionInfo *const targetFunctionInfo = inliningDecider.InlineCallApplyTarget(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2507. if (targetFunctionInfo != nullptr)
  2508. {
  2509. Js::FunctionBody *const targetFunctionBody = targetFunctionInfo->GetFunctionBody();
  2510. Js::ProfileId callApplyCallSiteId = functionBody->GetCallSiteToCallApplyCallSiteArray()[profiledCallSiteId];
  2511. if (!targetFunctionBody)
  2512. {
  2513. jitTimeData->AddCallApplyTargetInlinee(recycler, profiledCallSiteId, callApplyCallSiteId, targetFunctionInfo);
  2514. }
  2515. else if (targetFunctionBody != functionBody)
  2516. {
  2517. Js::FunctionCodeGenJitTimeData * targetJittimeData = jitTimeData->AddCallApplyTargetInlinee(recycler, profiledCallSiteId, callApplyCallSiteId, targetFunctionInfo);
  2518. Js::FunctionCodeGenRuntimeData * targetRuntimeData = IsInlinee ? runtimeData->EnsureCallApplyTargetInlinee(recycler, callApplyCallSiteId, targetFunctionBody) : functionBody->EnsureCallApplyTargetInlineeCodeGenRuntimeData(recycler, callApplyCallSiteId, targetFunctionBody);
  2519. GatherCodeGenData<true>(
  2520. recycler,
  2521. topFunctionBody,
  2522. targetFunctionBody,
  2523. entryPoint,
  2524. inliningDecider,
  2525. objTypeSpecFldInfoList,
  2526. targetJittimeData,
  2527. targetRuntimeData);
  2528. AddInlineCacheStats(jitTimeData, targetJittimeData);
  2529. }
  2530. }
  2531. }
  2532. }
  2533. continue;
  2534. }
  2535. // We are at a callsite that can be inlined. Let the callsite be foo().
  2536. // If foo has inline caches on it, we need to be able to get those for cloning.
  2537. // To do this,
  2538. // 1. Retrieve the inline cache associated with the load of "foo",
  2539. // 2. Try to get the fixed function object corresponding to "foo",
  2540. // 3. Pass the fixed function object to GatherCodeGenData which can clone its inline caches.
  2541. uint ldFldInlineCacheIndex = profileData->GetLdFldCacheIndexFromCallSiteInfo(functionBody, profiledCallSiteId);
  2542. Js::InlineCache * inlineCache = nullptr;
  2543. if ((ldFldInlineCacheIndex != Js::Constants::NoInlineCacheIndex) && (ldFldInlineCacheIndex < functionBody->GetInlineCacheCount()))
  2544. {
  2545. if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function))
  2546. {
  2547. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2548. {
  2549. inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(ldFldInlineCacheIndex);
  2550. }
  2551. }
  2552. else
  2553. {
  2554. inlineCache = functionBody->GetInlineCache(ldFldInlineCacheIndex);
  2555. }
  2556. }
  2557. Js::JavascriptFunction* fixedFunctionObject = nullptr;
  2558. #if ENABLE_FIXED_FIELDS
  2559. if (inlineCache && (inlineCache->IsLocal() || inlineCache->IsProto()))
  2560. {
  2561. inlineCache->TryGetFixedMethodFromCache(functionBody, ldFldInlineCacheIndex, &fixedFunctionObject);
  2562. }
  2563. if (fixedFunctionObject && fixedFunctionObject->GetFunctionInfo() != inlineeFunctionBody->GetFunctionInfo())
  2564. {
  2565. fixedFunctionObject = nullptr;
  2566. }
  2567. #endif
  2568. if (!PHASE_OFF(Js::InlineRecursivePhase, functionBody))
  2569. {
  2570. if (!isJitTimeDataComputed)
  2571. {
  2572. Js::FunctionCodeGenRuntimeData *inlineeRuntimeData = IsInlinee ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBody) : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBody);
  2573. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = nullptr;
  2574. bool doShareJitTimeData = false;
  2575. // Share the jitTime data if i) it is a recursive call, ii) jitTimeData is not from a polymorphic chain, and iii) all the call sites are recursive
  2576. if (functionBody == inlineeFunctionBody // recursive call
  2577. && jitTimeData->GetNext() == nullptr // not from a polymorphic call site
  2578. && profiledCallSiteCount == functionBody->GetNumberOfRecursiveCallSites() && !inlineGetterSetter) // all the callsites are recursive
  2579. {
  2580. jitTimeData->SetupRecursiveInlineeChain(recycler, profiledCallSiteId);
  2581. inlineeJitTimeData = jitTimeData;
  2582. doShareJitTimeData = true;
  2583. // If a recursive inliner has multiple recursive inlinees and if they hit the InlineCountMax
  2584. // threshold, then runtimeData for the inlinees may not be available (bug 2269097) for the inlinees
  2585. // as InlineCountMax threshold heuristics has higher priority than recursive inline heuristics. Since
  2586. // we share runtime data between recursive inliner and recursive inlinees, and all the call sites
  2587. // are recursive (we only do recursive inlining for functions where all the callsites are recursive),
  2588. // we can iterate over all the callsites of the inliner and setup the runtime data recursive inlinee chain
  2589. for (Js::ProfileId id = 0; id < profiledCallSiteCount; id++)
  2590. {
  2591. inlineeRuntimeData->SetupRecursiveInlineeChain(recycler, id, inlineeFunctionBody);
  2592. }
  2593. }
  2594. else
  2595. {
  2596. inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2597. }
  2598. GatherCodeGenData<true>(
  2599. recycler,
  2600. topFunctionBody,
  2601. inlineeFunctionBody,
  2602. entryPoint,
  2603. inliningDecider,
  2604. objTypeSpecFldInfoList,
  2605. inlineeJitTimeData,
  2606. inlineeRuntimeData,
  2607. fixedFunctionObject,
  2608. doShareJitTimeData,
  2609. functionBody == inlineeFunctionBody ? recursiveInlineDepth + 1 : 0);
  2610. if (jitTimeData != inlineeJitTimeData)
  2611. {
  2612. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2613. }
  2614. }
  2615. }
  2616. else
  2617. {
  2618. Js::FunctionCodeGenJitTimeData *const inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2619. GatherCodeGenData<true>(
  2620. recycler,
  2621. topFunctionBody,
  2622. inlineeFunctionBody,
  2623. entryPoint,
  2624. inliningDecider,
  2625. objTypeSpecFldInfoList,
  2626. inlineeJitTimeData,
  2627. IsInlinee
  2628. ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBody)
  2629. : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBody),
  2630. fixedFunctionObject);
  2631. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2632. }
  2633. if (PHASE_ENABLED(InlineCallbacksPhase, functionBody))
  2634. {
  2635. if (!isJitTimeDataComputed)
  2636. {
  2637. Js::FunctionInfo *const callbackInfo = inliningDecider.InlineCallback(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2638. if (callbackInfo != nullptr)
  2639. {
  2640. Js::FunctionBody *const callbackBody = callbackInfo->GetFunctionBody();
  2641. if (callbackBody != nullptr && callbackBody != functionBody)
  2642. {
  2643. Js::FunctionCodeGenJitTimeData * callbackJitTimeData = jitTimeData->AddCallbackInlinee(recycler, profiledCallSiteId, callbackInfo);
  2644. Js::FunctionCodeGenRuntimeData * callbackRuntimeData = IsInlinee ? runtimeData->EnsureCallbackInlinee(recycler, profiledCallSiteId, callbackBody) : functionBody->EnsureCallbackInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, callbackBody);
  2645. GatherCodeGenData<true>(
  2646. recycler,
  2647. topFunctionBody,
  2648. callbackBody,
  2649. entryPoint,
  2650. inliningDecider,
  2651. objTypeSpecFldInfoList,
  2652. callbackJitTimeData,
  2653. callbackRuntimeData);
  2654. AddInlineCacheStats(jitTimeData, callbackJitTimeData);
  2655. }
  2656. }
  2657. }
  2658. }
  2659. }
  2660. }
  2661. // Iterate through inlineCache getter setter and apply call sites recursively and determine what should be inlined
  2662. if (inlineGetterSetter || inlineApplyTarget || inlineCallTarget)
  2663. {
  2664. for(uint inlineCacheIndex = 0; inlineCacheIndex < functionBody->GetInlineCacheCount(); ++inlineCacheIndex)
  2665. {
  2666. const auto cacheType = profileData->GetFldInfo(functionBody, inlineCacheIndex)->flags;
  2667. if(cacheType == Js::FldInfo_NoInfo)
  2668. {
  2669. continue;
  2670. }
  2671. bool getSetInlineCandidate = inlineGetterSetter && ((cacheType & Js::FldInfo_InlineCandidate) != 0) && ((cacheType & Js::FldInfo_FromAccessor) != 0);
  2672. bool callApplyInlineCandidate = (inlineCallTarget || inlineApplyTarget) && ((cacheType & Js::FldInfo_InlineCandidate) != 0) && ((cacheType & Js::FldInfo_FromAccessor) == 0);
  2673. // 1. Do not inline if the x in a.x is both a getter/setter and is followed by a .apply
  2674. // 2. If we were optimistic earlier in assuming that the inline caches on the function object would be monomorphic and asserted that we may possibly inline apply target,
  2675. // then even if the field info flags say that the field access may be polymorphic, carry that optimism forward and try to inline apply target.
  2676. if (getSetInlineCandidate ^ callApplyInlineCandidate)
  2677. {
  2678. ObjTypeSpecFldInfo* info = jitTimeData->GetObjTypeSpecFldInfoArray()->GetInfo(functionBody, inlineCacheIndex);
  2679. if (info == nullptr)
  2680. {
  2681. continue;
  2682. }
  2683. if (!(getSetInlineCandidate && info->UsesAccessor()) && !(callApplyInlineCandidate && !info->IsPoly()))
  2684. {
  2685. continue;
  2686. }
  2687. Js::JavascriptFunction* inlineeFunction = info->GetFieldValueAsFunctionIfAvailable();
  2688. if (inlineeFunction == nullptr)
  2689. {
  2690. continue;
  2691. }
  2692. Js::FunctionInfo* inlineeFunctionInfo = inlineeFunction->GetFunctionInfo();
  2693. Js::FunctionProxy* inlineeFunctionProxy = inlineeFunctionInfo->GetFunctionProxy();
  2694. if (inlineeFunctionProxy != nullptr && !functionBody->CheckCalleeContextForInlining(inlineeFunctionProxy))
  2695. {
  2696. continue;
  2697. }
  2698. const auto inlinee = inliningDecider.Inline(functionBody, inlineeFunctionInfo, false /*isConstructorCall*/, false /*isPolymorphicCall*/, false /*isCallback*/, 0, (uint16)inlineCacheIndex, 0, false);
  2699. if(!inlinee)
  2700. {
  2701. continue;
  2702. }
  2703. const auto inlineeFunctionBody = inlinee->GetFunctionBody();
  2704. if(!inlineeFunctionBody)
  2705. {
  2706. if (((inlineeFunctionInfo->GetAttributes() & Js::FunctionInfo::Attributes::BuiltInInlinableAsLdFldInlinee) != 0) && !isJitTimeDataComputed)
  2707. {
  2708. jitTimeData->AddLdFldInlinee(recycler, inlineCacheIndex, inlinee);
  2709. }
  2710. continue;
  2711. }
  2712. Js::FunctionCodeGenRuntimeData *const inlineeRuntimeData = IsInlinee ? runtimeData->EnsureLdFldInlinee(recycler, inlineCacheIndex, inlineeFunctionBody) :
  2713. functionBody->EnsureLdFldInlineeCodeGenRuntimeData(recycler, inlineCacheIndex, inlineeFunctionBody);
  2714. if (inlineeRuntimeData->GetFunctionBody() != inlineeFunctionBody)
  2715. {
  2716. //There are obscure cases where profileData has not yet seen the polymorphic LdFld but the inlineCache has the newer object from which getter is invoked.
  2717. //In this case we don't want to inline that getter. Polymorphic bit will be set later correctly.
  2718. //See WinBlue 54540
  2719. continue;
  2720. }
  2721. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = jitTimeData->AddLdFldInlinee(recycler, inlineCacheIndex, inlinee);
  2722. GatherCodeGenData<true>(
  2723. recycler,
  2724. topFunctionBody,
  2725. inlineeFunctionBody,
  2726. entryPoint,
  2727. inliningDecider,
  2728. objTypeSpecFldInfoList,
  2729. inlineeJitTimeData,
  2730. inlineeRuntimeData,
  2731. nullptr);
  2732. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2733. }
  2734. }
  2735. }
  2736. #ifdef FIELD_ACCESS_STATS
  2737. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2738. {
  2739. if (jitTimeData->inlineCacheStats)
  2740. {
  2741. Output::Print(_u("ObTypeSpec: gathered code gen data for function %s (#%u) inlined %s (#%u): inline cache stats:\n"),
  2742. topFunctionBody->GetDisplayName(), topFunctionBody->GetFunctionNumber(), functionBody->GetDisplayName(), functionBody->GetFunctionNumber());
  2743. Output::Print(_u(" overall: total %u, no profile info %u\n"),
  2744. jitTimeData->inlineCacheStats->totalInlineCacheCount, jitTimeData->inlineCacheStats->noInfoInlineCacheCount);
  2745. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  2746. jitTimeData->inlineCacheStats->monoInlineCacheCount, jitTimeData->inlineCacheStats->emptyMonoInlineCacheCount,
  2747. jitTimeData->inlineCacheStats->clonedMonoInlineCacheCount);
  2748. Output::Print(_u(" poly: total %u (high %u, low %u), empty %u, equivalent %u, cloned %u\n"),
  2749. jitTimeData->inlineCacheStats->polyInlineCacheCount, jitTimeData->inlineCacheStats->highUtilPolyInlineCacheCount,
  2750. jitTimeData->inlineCacheStats->lowUtilPolyInlineCacheCount, jitTimeData->inlineCacheStats->emptyPolyInlineCacheCount,
  2751. jitTimeData->inlineCacheStats->equivPolyInlineCacheCount, jitTimeData->inlineCacheStats->clonedPolyInlineCacheCount);
  2752. }
  2753. else
  2754. {
  2755. Output::Print(_u("ObTypeSpec: function %s (%s): inline cache stats unavailable\n"), topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer));
  2756. }
  2757. Output::Flush();
  2758. }
  2759. #endif
  2760. #undef SetInlineCacheCount
  2761. #undef IncInlineCacheCount
  2762. #undef AddInlineCacheStats
  2763. }
  2764. Js::CodeGenRecyclableData *
  2765. NativeCodeGenerator::GatherCodeGenData(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const functionBody, Js::EntryPointInfo *const entryPoint, CodeGenWorkItem* workItem, void* function)
  2766. {
  2767. ASSERT_THREAD();
  2768. Assert(functionBody);
  2769. #ifdef PROFILE_EXEC
  2770. class AutoProfile
  2771. {
  2772. private:
  2773. Js::ScriptContextProfiler *const codeGenProfiler;
  2774. public:
  2775. AutoProfile(Js::ScriptContextProfiler *const codeGenProfiler) : codeGenProfiler(codeGenProfiler)
  2776. {
  2777. ProfileBegin(codeGenProfiler, Js::DelayPhase);
  2778. ProfileBegin(codeGenProfiler, Js::GatherCodeGenDataPhase);
  2779. }
  2780. ~AutoProfile()
  2781. {
  2782. ProfileEnd(codeGenProfiler, Js::GatherCodeGenDataPhase);
  2783. ProfileEnd(codeGenProfiler, Js::DelayPhase);
  2784. }
  2785. } autoProfile(foregroundCodeGenProfiler);
  2786. #endif
  2787. UpdateJITState();
  2788. const auto recycler = scriptContext->GetRecycler();
  2789. {
  2790. const auto jitTimeData = Js::FunctionCodeGenJitTimeData::New(recycler, functionBody->GetFunctionInfo(), entryPoint);
  2791. InliningDecider inliningDecider(functionBody, workItem->Type() == JsLoopBodyWorkItemType, functionBody->IsInDebugMode(), workItem->GetJitMode());
  2792. BEGIN_TEMP_ALLOCATOR(gatherCodeGenDataAllocator, scriptContext, _u("GatherCodeGenData"));
  2793. ObjTypeSpecFldInfoList* objTypeSpecFldInfoList = JitAnew(gatherCodeGenDataAllocator, ObjTypeSpecFldInfoList, gatherCodeGenDataAllocator);
  2794. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2795. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2796. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2797. if (PHASE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2798. {
  2799. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s): GatherCodeGenData(): \n"),
  2800. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2));
  2801. }
  2802. #endif
  2803. GatherCodeGenData<false>(recycler, topFunctionBody, functionBody, entryPoint, inliningDecider, objTypeSpecFldInfoList, jitTimeData, nullptr, function ? Js::VarTo<Js::JavascriptFunction>(function) : nullptr, 0);
  2804. jitTimeData->sharedPropertyGuards = entryPoint->GetNativeEntryPointData()->GetSharedPropertyGuards(recycler, jitTimeData->sharedPropertyGuardCount);
  2805. #ifdef FIELD_ACCESS_STATS
  2806. Js::FieldAccessStats* fieldAccessStats = entryPoint->EnsureFieldAccessStats(recycler);
  2807. fieldAccessStats->Add(jitTimeData->inlineCacheStats);
  2808. entryPoint->GetScriptContext()->RecordFieldAccessStats(topFunctionBody, fieldAccessStats);
  2809. #endif
  2810. #ifdef FIELD_ACCESS_STATS
  2811. if (PHASE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2812. {
  2813. auto stats = jitTimeData->inlineCacheStats;
  2814. Output::Print(_u("ObjTypeSpec: gathered code gen data for function %s (%s): inline cache stats:\n"), topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer));
  2815. Output::Print(_u(" overall: total %u, no profile info %u\n"), stats->totalInlineCacheCount, stats->noInfoInlineCacheCount);
  2816. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  2817. stats->monoInlineCacheCount, stats->emptyMonoInlineCacheCount, stats->clonedMonoInlineCacheCount);
  2818. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  2819. stats->polyInlineCacheCount, stats->highUtilPolyInlineCacheCount, stats->lowUtilPolyInlineCacheCount,
  2820. stats->nullPolyInlineCacheCount, stats->emptyPolyInlineCacheCount, stats->ignoredPolyInlineCacheCount, stats->disabledPolyInlineCacheCount,
  2821. stats->equivPolyInlineCacheCount, stats->nonEquivPolyInlineCacheCount, stats->clonedPolyInlineCacheCount);
  2822. }
  2823. #endif
  2824. uint objTypeSpecFldInfoCount = objTypeSpecFldInfoList->Count();
  2825. jitTimeData->SetGlobalObjTypeSpecFldInfoArray(RecyclerNewArray(recycler, Field(ObjTypeSpecFldInfo*), objTypeSpecFldInfoCount), objTypeSpecFldInfoCount);
  2826. uint propertyInfoId = objTypeSpecFldInfoCount - 1;
  2827. FOREACH_SLISTCOUNTED_ENTRY(ObjTypeSpecFldInfo*, info, objTypeSpecFldInfoList)
  2828. {
  2829. // Clear field values we don't need so we don't unnecessarily pin them while JIT-ing.
  2830. if (!info->GetKeepFieldValue() && !(info->IsPoly() && info->DoesntHaveEquivalence()))
  2831. {
  2832. info->SetFieldValue(nullptr);
  2833. }
  2834. jitTimeData->SetGlobalObjTypeSpecFldInfo(propertyInfoId--, info);
  2835. }
  2836. NEXT_SLISTCOUNTED_ENTRY;
  2837. END_TEMP_ALLOCATOR(gatherCodeGenDataAllocator, scriptContext);
  2838. auto jitData = workItem->GetJITData();
  2839. JITTimePolymorphicInlineCacheInfo::InitializeEntryPointPolymorphicInlineCacheInfo(
  2840. recycler,
  2841. entryPoint->GetNativeEntryPointData()->EnsurePolymorphicInlineCacheInfo(recycler, workItem->GetFunctionBody()),
  2842. jitData);
  2843. jitTimeData->SetPolymorphicInlineInfo(jitData->inlineeInfo, jitData->selfInfo, jitData->selfInfo->polymorphicInlineCaches);
  2844. return RecyclerNew(recycler, Js::CodeGenRecyclableData, jitTimeData);
  2845. }
  2846. }
  2847. bool
  2848. NativeCodeGenerator::IsBackgroundJIT() const
  2849. {
  2850. return Processor()->ProcessesInBackground();
  2851. }
  2852. void
  2853. NativeCodeGenerator::EnterScriptStart()
  2854. {
  2855. // We should be in execution
  2856. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  2857. Assert(scriptContext->GetThreadContext()->IsInScript());
  2858. if(CONFIG_FLAG(BgJitDelay) == 0 ||
  2859. Js::Configuration::Global.flags.EnforceExecutionModeLimits ||
  2860. scriptContext->GetThreadContext()->GetCallRootLevel() > 2)
  2861. {
  2862. return;
  2863. }
  2864. if (pendingCodeGenWorkItems == 0 || pendingCodeGenWorkItems > (uint)CONFIG_FLAG(BgJitPendingFuncCap))
  2865. {
  2866. // We have already finish code gen for this script context
  2867. // Only wait if the script is small and we can easily pre-JIT all of it.
  2868. return;
  2869. }
  2870. if (this->IsClosed())
  2871. {
  2872. return;
  2873. }
  2874. // We've already done a few calls to this scriptContext, don't bother waiting.
  2875. if (scriptContext->callCount >= 3)
  2876. {
  2877. return;
  2878. }
  2879. scriptContext->callCount++;
  2880. if (scriptContext->GetDeferredBody())
  2881. {
  2882. OUTPUT_TRACE(Js::DelayPhase, _u("No delay because the script has a deferred body\n"));
  2883. return;
  2884. }
  2885. if(CONFIG_FLAG(BgJitDelayFgBuffer) >= CONFIG_FLAG(BgJitDelay))
  2886. {
  2887. return;
  2888. }
  2889. class AutoCleanup
  2890. {
  2891. private:
  2892. Js::ScriptContextProfiler *const codeGenProfiler;
  2893. public:
  2894. AutoCleanup(Js::ScriptContextProfiler *const codeGenProfiler) : codeGenProfiler(codeGenProfiler)
  2895. {
  2896. EDGE_ETW_INTERNAL(EventWriteJSCRIPT_NATIVECODEGEN_DELAY_START(this, 0));
  2897. #ifdef PROFILE_EXEC
  2898. ProfileBegin(codeGenProfiler, Js::DelayPhase);
  2899. ProfileBegin(codeGenProfiler, Js::SpeculationPhase);
  2900. #endif
  2901. }
  2902. ~AutoCleanup()
  2903. {
  2904. #ifdef PROFILE_EXEC
  2905. ProfileEnd(codeGenProfiler, Js::SpeculationPhase);
  2906. ProfileEnd(codeGenProfiler, Js::DelayPhase);
  2907. #endif
  2908. EDGE_ETW_INTERNAL(EventWriteJSCRIPT_NATIVECODEGEN_DELAY_STOP(this, 0));
  2909. }
  2910. } autoCleanup(
  2911. #ifdef PROFILE_EXEC
  2912. this->foregroundCodeGenProfiler
  2913. #else
  2914. nullptr
  2915. #endif
  2916. );
  2917. Processor()->PrioritizeManagerAndWait(this, CONFIG_FLAG(BgJitDelay) - CONFIG_FLAG(BgJitDelayFgBuffer));
  2918. }
  2919. void
  2920. FreeNativeCodeGenAllocation(Js::ScriptContext *scriptContext, Js::JavascriptMethod codeAddress, Js::JavascriptMethod thunkAddress)
  2921. {
  2922. if (!scriptContext->GetNativeCodeGenerator())
  2923. {
  2924. return;
  2925. }
  2926. scriptContext->GetNativeCodeGenerator()->QueueFreeNativeCodeGenAllocation((void*)codeAddress, (void*)thunkAddress);
  2927. }
  2928. bool TryReleaseNonHiPriWorkItem(Js::ScriptContext* scriptContext, CodeGenWorkItem* workItem)
  2929. {
  2930. if (!scriptContext->GetNativeCodeGenerator())
  2931. {
  2932. return false;
  2933. }
  2934. return scriptContext->GetNativeCodeGenerator()->TryReleaseNonHiPriWorkItem(workItem);
  2935. }
  2936. // Called from within the lock
  2937. // The work item cannot be used after this point if it returns true
  2938. bool NativeCodeGenerator::TryReleaseNonHiPriWorkItem(CodeGenWorkItem* workItem)
  2939. {
  2940. // If its the highest priority, don't release it, let the job continue
  2941. if (workItem->IsInJitQueue())
  2942. {
  2943. return false;
  2944. }
  2945. workItems.Unlink(workItem);
  2946. Assert(!workItem->RecyclableData());
  2947. workItem->Delete();
  2948. return true;
  2949. }
  2950. void
  2951. NativeCodeGenerator::FreeNativeCodeGenAllocation(void* codeAddress)
  2952. {
  2953. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  2954. {
  2955. #if PDATA_ENABLED && defined(_WIN32)
  2956. DelayDeletingFunctionTable::Clear();
  2957. #endif
  2958. HRESULT hr = JITManager::GetJITManager()->FreeAllocation(this->scriptContext->GetRemoteScriptAddr(), (intptr_t)codeAddress);
  2959. JITManager::HandleServerCallResult(hr, RemoteCallType::MemFree);
  2960. }
  2961. else if(this->backgroundAllocators)
  2962. {
  2963. this->backgroundAllocators->emitBufferManager.FreeAllocation(codeAddress);
  2964. }
  2965. }
  2966. void
  2967. NativeCodeGenerator::QueueFreeNativeCodeGenAllocation(void* codeAddress, void * thunkAddress)
  2968. {
  2969. ASSERT_THREAD();
  2970. if(IsClosed())
  2971. {
  2972. return;
  2973. }
  2974. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !CONFIG_FLAG(OOPCFGRegistration))
  2975. {
  2976. //DeRegister Entry Point for CFG
  2977. if (thunkAddress)
  2978. {
  2979. ThreadContext::GetContextForCurrentThread()->SetValidCallTargetForCFG(thunkAddress, false);
  2980. }
  2981. else
  2982. {
  2983. ThreadContext::GetContextForCurrentThread()->SetValidCallTargetForCFG(codeAddress, false);
  2984. }
  2985. }
  2986. if ((!JITManager::GetJITManager()->IsOOPJITEnabled() && !this->scriptContext->GetThreadContext()->GetPreReservedVirtualAllocator()->IsInRange((void*)codeAddress)) ||
  2987. (JITManager::GetJITManager()->IsOOPJITEnabled() && !PreReservedVirtualAllocWrapper::IsInRange((void*)this->scriptContext->GetThreadContext()->GetPreReservedRegionAddr(), (void*)codeAddress)))
  2988. {
  2989. this->scriptContext->GetJitFuncRangeCache()->RemoveFuncRange((void*)codeAddress);
  2990. }
  2991. // OOP JIT will always queue a job
  2992. // The foreground allocators may have been used
  2993. if (this->foregroundAllocators && this->foregroundAllocators->emitBufferManager.FreeAllocation(codeAddress))
  2994. {
  2995. return;
  2996. }
  2997. // The background allocators were used. Queue a job to free the allocation from the background thread.
  2998. this->freeLoopBodyManager.QueueFreeLoopBodyJob(codeAddress, thunkAddress);
  2999. }
  3000. void NativeCodeGenerator::FreeLoopBodyJobManager::QueueFreeLoopBodyJob(void* codeAddress, void * thunkAddress)
  3001. {
  3002. Assert(!this->isClosed);
  3003. FreeLoopBodyJob* job = HeapNewNoThrow(FreeLoopBodyJob, this, codeAddress, thunkAddress);
  3004. if (job == nullptr)
  3005. {
  3006. FreeLoopBodyJob stackJob(this, codeAddress, thunkAddress, false /* heapAllocated */);
  3007. {
  3008. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  3009. #if DBG
  3010. this->waitingForStackJob = true;
  3011. #endif
  3012. this->stackJobProcessed = false;
  3013. Processor()->AddJob(&stackJob);
  3014. }
  3015. Processor()->PrioritizeJobAndWait(this, &stackJob);
  3016. }
  3017. else
  3018. {
  3019. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  3020. if (Processor()->HasManager(this))
  3021. {
  3022. Processor()->AddJobAndProcessProactively<FreeLoopBodyJobManager, FreeLoopBodyJob*>(this, job);
  3023. }
  3024. else
  3025. {
  3026. HeapDelete(job);
  3027. }
  3028. }
  3029. }
  3030. #ifdef PROFILE_EXEC
  3031. void
  3032. NativeCodeGenerator::CreateProfiler(Js::ScriptContextProfiler * profiler)
  3033. {
  3034. Assert(this->foregroundCodeGenProfiler == nullptr);
  3035. this->foregroundCodeGenProfiler = profiler;
  3036. profiler->AddRef();
  3037. }
  3038. Js::ScriptContextProfiler *
  3039. NativeCodeGenerator::EnsureForegroundCodeGenProfiler()
  3040. {
  3041. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3042. {
  3043. Assert(this->foregroundCodeGenProfiler != nullptr);
  3044. Assert(this->foregroundCodeGenProfiler->IsInitialized());
  3045. }
  3046. return this->foregroundCodeGenProfiler;
  3047. }
  3048. void
  3049. NativeCodeGenerator::SetProfilerFromNativeCodeGen(NativeCodeGenerator * nativeCodeGen)
  3050. {
  3051. Assert(Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag));
  3052. Assert(this->foregroundCodeGenProfiler != nullptr);
  3053. Assert(this->foregroundCodeGenProfiler->IsInitialized());
  3054. Assert(nativeCodeGen->foregroundCodeGenProfiler != nullptr);
  3055. Assert(nativeCodeGen->foregroundCodeGenProfiler->IsInitialized());
  3056. this->foregroundCodeGenProfiler->Release();
  3057. this->foregroundCodeGenProfiler = nativeCodeGen->foregroundCodeGenProfiler;
  3058. this->foregroundCodeGenProfiler->AddRef();
  3059. }
  3060. void
  3061. NativeCodeGenerator::ProfilePrint()
  3062. {
  3063. this->backgroundCodeGenProfiler->ProfilePrint();
  3064. }
  3065. void
  3066. NativeCodeGenerator::ProfileBegin(Js::ScriptContextProfiler *const profiler, Js::Phase phase)
  3067. {
  3068. AssertMsg((profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  3069. "Profiler tag is supplied but the profiler pointer is NULL");
  3070. if (profiler)
  3071. {
  3072. profiler->ProfileBegin(phase);
  3073. }
  3074. }
  3075. void
  3076. NativeCodeGenerator::ProfileEnd(Js::ScriptContextProfiler *const profiler, Js::Phase phase)
  3077. {
  3078. AssertMsg((profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  3079. "Profiler tag is supplied but the profiler pointer is NULL");
  3080. if (profiler)
  3081. {
  3082. profiler->ProfileEnd(phase);
  3083. }
  3084. }
  3085. #endif
  3086. void NativeCodeGenerator::AddToJitQueue(CodeGenWorkItem *const codeGenWorkItem, bool prioritize, bool lock, void* function)
  3087. {
  3088. codeGenWorkItem->VerifyJitMode();
  3089. Js::CodeGenRecyclableData* recyclableData = GatherCodeGenData(codeGenWorkItem->GetFunctionBody(), codeGenWorkItem->GetFunctionBody(), codeGenWorkItem->GetEntryPoint(), codeGenWorkItem, function);
  3090. codeGenWorkItem->SetRecyclableData(recyclableData);
  3091. AutoOptionalCriticalSection autoLock(lock ? Processor()->GetCriticalSection() : nullptr);
  3092. scriptContext->GetThreadContext()->RegisterCodeGenRecyclableData(recyclableData);
  3093. // If we have added a lot of jobs that are still waiting to be jitted, remove the oldest job
  3094. // to ensure we do not spend time jitting stale work items.
  3095. const ExecutionMode jitMode = codeGenWorkItem->GetJitMode();
  3096. if(jitMode == ExecutionMode::FullJit &&
  3097. queuedFullJitWorkItemCount >= (unsigned int)CONFIG_FLAG(JitQueueThreshold))
  3098. {
  3099. CodeGenWorkItem *const workItemRemoved = queuedFullJitWorkItems.Tail()->WorkItem();
  3100. Assert(workItemRemoved->GetJitMode() == ExecutionMode::FullJit);
  3101. if(Processor()->RemoveJob(workItemRemoved))
  3102. {
  3103. queuedFullJitWorkItems.UnlinkFromEnd();
  3104. --queuedFullJitWorkItemCount;
  3105. workItemRemoved->OnRemoveFromJitQueue(this);
  3106. }
  3107. }
  3108. Processor()->AddJob(codeGenWorkItem, prioritize); // This one can throw (really unlikely though), OOM specifically.
  3109. if(jitMode == ExecutionMode::FullJit)
  3110. {
  3111. QueuedFullJitWorkItem *const queuedFullJitWorkItem = codeGenWorkItem->EnsureQueuedFullJitWorkItem();
  3112. if(queuedFullJitWorkItem) // ignore OOM, this work item just won't be removed from the job processor's queue
  3113. {
  3114. if(prioritize)
  3115. {
  3116. queuedFullJitWorkItems.LinkToBeginning(queuedFullJitWorkItem);
  3117. }
  3118. else
  3119. {
  3120. queuedFullJitWorkItems.LinkToEnd(queuedFullJitWorkItem);
  3121. }
  3122. ++queuedFullJitWorkItemCount;
  3123. }
  3124. }
  3125. codeGenWorkItem->OnAddToJitQueue();
  3126. }
  3127. void NativeCodeGenerator::AddWorkItem(CodeGenWorkItem* workitem)
  3128. {
  3129. workitem->ResetJitMode();
  3130. workItems.LinkToEnd(workitem);
  3131. }
  3132. Js::ScriptContextProfiler * NativeCodeGenerator::GetBackgroundCodeGenProfiler(PageAllocator *allocator)
  3133. {
  3134. #ifdef PROFILE_EXEC
  3135. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3136. {
  3137. Js::ScriptContextProfiler *codegenProfiler = this->backgroundCodeGenProfiler;
  3138. while (codegenProfiler)
  3139. {
  3140. if (codegenProfiler->pageAllocator == allocator)
  3141. {
  3142. if (!codegenProfiler->IsInitialized())
  3143. {
  3144. codegenProfiler->Initialize(allocator, nullptr);
  3145. }
  3146. return codegenProfiler;
  3147. }
  3148. codegenProfiler = codegenProfiler->next;
  3149. }
  3150. Assert(false);
  3151. }
  3152. return nullptr;
  3153. #else
  3154. return nullptr;
  3155. #endif
  3156. }
  3157. void NativeCodeGenerator::AllocateBackgroundCodeGenProfiler(PageAllocator *pageAllocator)
  3158. {
  3159. #ifdef PROFILE_EXEC
  3160. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3161. {
  3162. Js::ScriptContextProfiler *codegenProfiler = NoCheckHeapNew(Js::ScriptContextProfiler);
  3163. codegenProfiler->pageAllocator = pageAllocator;
  3164. codegenProfiler->next = this->backgroundCodeGenProfiler;
  3165. this->backgroundCodeGenProfiler = codegenProfiler;
  3166. }
  3167. #endif
  3168. }
  3169. bool NativeCodeGenerator::TryAggressiveInlining(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const inlineeFunctionBody, InliningDecider &inliningDecider, uint& inlineeCount, uint recursiveInlineDepth)
  3170. {
  3171. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackDefault);
  3172. if (!inlineeFunctionBody->GetProfiledCallSiteCount())
  3173. {
  3174. // Nothing to inline. See this as fully inlinable function.
  3175. return true;
  3176. }
  3177. class AutoCleanup
  3178. {
  3179. private:
  3180. Js::FunctionBody *const functionBody;
  3181. public:
  3182. AutoCleanup(Js::FunctionBody *const functionBody) : functionBody(functionBody)
  3183. {
  3184. functionBody->OnBeginInlineInto();
  3185. }
  3186. ~AutoCleanup()
  3187. {
  3188. functionBody->OnEndInlineInto();
  3189. }
  3190. } autoCleanup(inlineeFunctionBody);
  3191. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3192. class AutoTrace
  3193. {
  3194. Js::FunctionBody *const topFunc;
  3195. Js::FunctionBody *const inlineeFunc;
  3196. uint32& inlineeCount;
  3197. bool done;
  3198. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3199. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3200. public:
  3201. AutoTrace(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const inlineeFunctionBody, uint32& inlineeCount) : topFunc(topFunctionBody),
  3202. inlineeFunc(inlineeFunctionBody), done(false), inlineeCount(inlineeCount)
  3203. {
  3204. if (topFunc == inlineeFunc)
  3205. {
  3206. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining started topFunc: %s (%s)\n"), topFunc->GetDisplayName(),
  3207. topFunc->GetDebugNumberSet(debugStringBuffer))
  3208. }
  3209. }
  3210. void Done(bool success)
  3211. {
  3212. if (success)
  3213. {
  3214. done = true;
  3215. if (topFunc == inlineeFunc)
  3216. {
  3217. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining succeeded topFunc: %s (%s), inlinee count: %d\n"), topFunc->GetDisplayName(),
  3218. topFunc->GetDebugNumberSet(debugStringBuffer), inlineeCount);
  3219. }
  3220. else
  3221. {
  3222. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining succeeded topFunc: %s (%s), inlinee: %s (%s) \n"), topFunc->GetDisplayName(),
  3223. topFunc->GetDebugNumberSet(debugStringBuffer),
  3224. inlineeFunc->GetDisplayName(),
  3225. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3226. }
  3227. }
  3228. else
  3229. {
  3230. Assert(done == false);
  3231. }
  3232. }
  3233. void TraceFailure(const char16 *message)
  3234. {
  3235. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining failed topFunc (%s): %s (%s), inlinee: %s (%s) \n"), message, topFunc->GetDisplayName(),
  3236. topFunc->GetDebugNumberSet(debugStringBuffer),
  3237. inlineeFunc->GetDisplayName(),
  3238. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3239. }
  3240. ~AutoTrace()
  3241. {
  3242. if (!done)
  3243. {
  3244. if (topFunc == inlineeFunc)
  3245. {
  3246. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining failed topFunc: %s (%s)\n"), topFunc->GetDisplayName(),
  3247. topFunc->GetDebugNumberSet(debugStringBuffer));
  3248. }
  3249. else
  3250. {
  3251. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining failed topFunc: %s (%s), inlinee: %s (%s) \n"), topFunc->GetDisplayName(),
  3252. topFunc->GetDebugNumberSet(debugStringBuffer),
  3253. inlineeFunc->GetDisplayName(),
  3254. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3255. }
  3256. }
  3257. }
  3258. };
  3259. AutoTrace trace(topFunctionBody, inlineeFunctionBody, inlineeCount);
  3260. #endif
  3261. if (inlineeFunctionBody->GetProfiledSwitchCount())
  3262. {
  3263. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3264. trace.TraceFailure(_u("Switch statement in inlinee"));
  3265. #endif
  3266. return false;
  3267. }
  3268. bool isInlinee = topFunctionBody != inlineeFunctionBody;
  3269. if (isInlinee ? !inliningDecider.InlineIntoInliner(inlineeFunctionBody) : !inliningDecider.InlineIntoTopFunc())
  3270. {
  3271. return false;
  3272. }
  3273. const auto profiledCallSiteCount = inlineeFunctionBody->GetProfiledCallSiteCount();
  3274. for (Js::ProfileId profiledCallSiteId = 0; profiledCallSiteId < profiledCallSiteCount; ++profiledCallSiteId)
  3275. {
  3276. bool isConstructorCall = false;
  3277. bool isPolymorphicCall = false;
  3278. if (!inlineeFunctionBody->IsJsBuiltInCode() && !inliningDecider.HasCallSiteInfo(inlineeFunctionBody, profiledCallSiteId))
  3279. {
  3280. //There is no callsite information. We should hit bailonnoprofile for these callsites. Ignore.
  3281. continue;
  3282. }
  3283. Js::FunctionInfo *inlinee = inliningDecider.GetCallSiteFuncInfo(inlineeFunctionBody, profiledCallSiteId, &isConstructorCall, &isPolymorphicCall);
  3284. if (!inlinee)
  3285. {
  3286. if (isPolymorphicCall)
  3287. {
  3288. //Try and see if this polymorphic call
  3289. Js::FunctionBody* inlineeFunctionBodyArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  3290. bool canInlineArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  3291. uint polyInlineeCount = inliningDecider.InlinePolymorphicCallSite(inlineeFunctionBody, profiledCallSiteId, inlineeFunctionBodyArray,
  3292. Js::DynamicProfileInfo::maxPolymorphicInliningSize, canInlineArray);
  3293. //We should be able to inline everything here.
  3294. if (polyInlineeCount >= 2)
  3295. {
  3296. for (uint i = 0; i < polyInlineeCount; i++)
  3297. {
  3298. bool isInlined = canInlineArray[i];
  3299. if (isInlined)
  3300. {
  3301. ++inlineeCount;
  3302. if (!TryAggressiveInlining(topFunctionBody, inlineeFunctionBodyArray[i], inliningDecider, inlineeCount, inlineeFunctionBody == inlineeFunctionBodyArray[i] ? recursiveInlineDepth + 1 : 0))
  3303. {
  3304. return false;
  3305. }
  3306. }
  3307. else
  3308. {
  3309. return false;
  3310. }
  3311. }
  3312. }
  3313. else
  3314. {
  3315. return false;
  3316. }
  3317. }
  3318. else
  3319. {
  3320. return false;
  3321. }
  3322. }
  3323. else
  3324. {
  3325. inlinee = inliningDecider.Inline(inlineeFunctionBody, inlinee, isConstructorCall, false, false, inliningDecider.GetConstantArgInfo(inlineeFunctionBody, profiledCallSiteId), profiledCallSiteId, inlineeFunctionBody->GetFunctionInfo() == inlinee ? recursiveInlineDepth + 1 : 0, true);
  3326. if (!inlinee)
  3327. {
  3328. return false;
  3329. }
  3330. Js::FunctionBody *const functionBody = inlinee->GetFunctionBody();
  3331. if (!functionBody)
  3332. {
  3333. //Built-in
  3334. continue;
  3335. }
  3336. //Recursive call
  3337. ++inlineeCount;
  3338. if (!TryAggressiveInlining(topFunctionBody, functionBody, inliningDecider, inlineeCount, inlineeFunctionBody == functionBody ? recursiveInlineDepth + 1 : 0 ))
  3339. {
  3340. return false;
  3341. }
  3342. }
  3343. }
  3344. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3345. trace.Done(true);
  3346. #endif
  3347. return true;
  3348. }
  3349. #if _WIN32
  3350. bool
  3351. JITManager::HandleServerCallResult(HRESULT hr, RemoteCallType callType)
  3352. {
  3353. // handle the normal hresults
  3354. switch (hr)
  3355. {
  3356. case S_OK:
  3357. return true;
  3358. case E_ABORT:
  3359. throw Js::OperationAbortedException();
  3360. case 0x800705af: // = HRESULT_FROM_WIN32(ERROR_COMMITMENT_LIMIT) some of our tooling does not yet support constexpr switch labels.
  3361. case E_OUTOFMEMORY:
  3362. if (callType == RemoteCallType::MemFree)
  3363. {
  3364. // if freeing memory fails due to OOM, it means we failed to fill with debug breaks -- so failfast
  3365. RpcFailure_unrecoverable_error(hr);
  3366. }
  3367. else
  3368. {
  3369. Js::Throw::OutOfMemory();
  3370. }
  3371. case VBSERR_OutOfStack:
  3372. throw Js::StackOverflowException();
  3373. default:
  3374. break;
  3375. }
  3376. if (CONFIG_FLAG(CrashOnOOPJITFailure))
  3377. {
  3378. RpcFailure_unrecoverable_error(hr);
  3379. }
  3380. // we only expect to see these hresults in case server has been closed. failfast otherwise
  3381. if (hr != HRESULT_FROM_WIN32(RPC_S_CALL_FAILED) &&
  3382. hr != HRESULT_FROM_WIN32(RPC_S_CALL_FAILED_DNE))
  3383. {
  3384. RpcFailure_unrecoverable_error(hr);
  3385. }
  3386. // if JIT process is gone, record that and stop trying to call it
  3387. GetJITManager()->SetJITFailed(hr);
  3388. switch (callType)
  3389. {
  3390. case RemoteCallType::CodeGen:
  3391. // inform job manager that JIT work item has been cancelled
  3392. throw Js::OperationAbortedException();
  3393. #if DBG
  3394. case RemoteCallType::HeapQuery:
  3395. #endif
  3396. case RemoteCallType::ThunkCreation:
  3397. case RemoteCallType::StateUpdate:
  3398. case RemoteCallType::MemFree:
  3399. // if server process is gone, we can ignore failures updating its state
  3400. return false;
  3401. default:
  3402. Assert(UNREACHED);
  3403. RpcFailure_unrecoverable_error(hr);
  3404. }
  3405. return false;
  3406. }
  3407. #endif