NativeCodeGenerator.cpp 149 KB

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