NativeCodeGenerator.cpp 151 KB

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