NativeCodeGenerator.cpp 147 KB

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