NativeCodeGenerator.cpp 151 KB

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