BailOut.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  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 "Debug\DebuggingFlags.h"
  7. #include "Debug\DiagProbe.h"
  8. #include "Debug\DebugManager.h"
  9. #include "Language\JavascriptFunctionArgIndex.h"
  10. extern const IRType RegTypes[RegNumCount];
  11. void
  12. BailOutInfo::Clear(JitArenaAllocator * allocator)
  13. {
  14. // Currently, we don't have a case where we delete bailout info after we allocated the bailout record
  15. Assert(!bailOutRecord);
  16. this->capturedValues.constantValues.Clear(allocator);
  17. this->capturedValues.copyPropSyms.Clear(allocator);
  18. this->usedCapturedValues.constantValues.Clear(allocator);
  19. this->usedCapturedValues.copyPropSyms.Clear(allocator);
  20. if (byteCodeUpwardExposedUsed)
  21. {
  22. JitAdelete(allocator, byteCodeUpwardExposedUsed);
  23. }
  24. if (startCallInfo)
  25. {
  26. Assert(argOutSyms);
  27. JitAdeleteArray(allocator, startCallCount, startCallInfo);
  28. JitAdeleteArray(allocator, totalOutParamCount, argOutSyms);
  29. }
  30. if (liveVarSyms)
  31. {
  32. JitAdelete(allocator, liveVarSyms);
  33. JitAdelete(allocator, liveLosslessInt32Syms);
  34. JitAdelete(allocator, liveFloat64Syms);
  35. }
  36. #ifdef _M_IX86
  37. if (outParamFrameAdjustArgSlot)
  38. {
  39. JitAdelete(allocator, outParamFrameAdjustArgSlot);
  40. }
  41. #endif
  42. }
  43. #ifdef _M_IX86
  44. uint
  45. BailOutInfo::GetStartCallOutParamCount(uint i) const
  46. {
  47. Assert(i < this->startCallCount);
  48. Assert(this->startCallInfo);
  49. return this->startCallInfo[i].argCount;
  50. }
  51. bool
  52. BailOutInfo::NeedsStartCallAdjust(uint i, const IR::Instr * bailOutInstr) const
  53. {
  54. Assert(i < this->startCallCount);
  55. Assert(this->startCallInfo);
  56. Assert(bailOutInstr->m_func->HasInstrNumber());
  57. IR::Instr * instr = this->startCallInfo[i].instr;
  58. if (instr == nullptr || instr->m_opcode == Js::OpCode::StartCall)
  59. {
  60. // The StartCall was unlinked (because it was being deleted, or we know it was
  61. // moved below the bailout instr).
  62. // -------- or --------
  63. // StartCall wasn't lowered because the argouts were orphaned, in which case we don't need
  64. // the adjustment as the orphaned argouts are not stored with the non-orphaned ones
  65. return false;
  66. }
  67. // In scenarios related to partial polymorphic inlining where we move the lowered version of the start call - LEA esp, esp - argcount * 4
  68. // next to the call itself as part of one of the dispatch arms. In this scenario StartCall is marked
  69. // as cloned and we do not need to adjust the offsets from where the args need to be restored.
  70. return instr->GetNumber() < bailOutInstr->GetNumber() && !instr->IsCloned();
  71. }
  72. void
  73. BailOutInfo::RecordStartCallInfo(uint i, uint argRestoreAdjustCount, IR::Instr *instr)
  74. {
  75. Assert(i < this->startCallCount);
  76. Assert(this->startCallInfo);
  77. Assert(instr);
  78. Assert(instr->m_opcode == Js::OpCode::StartCall);
  79. this->startCallInfo[i].instr = instr;
  80. this->startCallInfo[i].argCount = instr->GetArgOutCount(/*getInterpreterArgOutCount*/ true);
  81. this->startCallInfo[i].argRestoreAdjustCount = argRestoreAdjustCount;
  82. }
  83. void
  84. BailOutInfo::UnlinkStartCall(const IR::Instr * instr)
  85. {
  86. Assert(this->startCallCount == 0 || this->startCallInfo != nullptr);
  87. uint i;
  88. for (i = 0; i < this->startCallCount; i++)
  89. {
  90. StartCallInfo *info = &this->startCallInfo[i];
  91. if (info->instr == instr)
  92. {
  93. info->instr = nullptr;
  94. return;
  95. }
  96. }
  97. }
  98. #else
  99. uint
  100. BailOutInfo::GetStartCallOutParamCount(uint i) const
  101. {
  102. Assert(i < this->startCallCount);
  103. Assert(this->startCallInfo);
  104. return this->startCallInfo[i];
  105. }
  106. void
  107. BailOutInfo::RecordStartCallInfo(uint i, uint argRestoreAdjust, IR::Instr *instr)
  108. {
  109. Assert(i < this->startCallCount);
  110. Assert(this->startCallInfo);
  111. Assert(instr);
  112. Assert(instr->m_opcode == Js::OpCode::StartCall);
  113. Assert(instr->GetSrc1());
  114. this->startCallInfo[i] = instr->GetArgOutCount(/*getInterpreterArgOutCount*/ true);
  115. }
  116. #endif
  117. #ifdef MD_GROW_LOCALS_AREA_UP
  118. void
  119. BailOutInfo::FinalizeOffsets(__in_ecount(count) int * offsets, uint count, Func *func, BVSparse<JitArenaAllocator> *bvInlinedArgSlot)
  120. {
  121. // Turn positive SP-relative sym offsets into negative frame-pointer-relative offsets for the convenience
  122. // of the restore-value logic.
  123. int32 inlineeArgStackSize = func->GetInlineeArgumentStackSize();
  124. int localsSize = func->m_localStackHeight + func->m_ArgumentsOffset;
  125. for (uint i = 0; i < count; i++)
  126. {
  127. int offset = -(offsets[i] + StackSymBias);
  128. if (offset < 0)
  129. {
  130. // Not stack offset
  131. continue;
  132. }
  133. if (bvInlinedArgSlot && bvInlinedArgSlot->Test(i))
  134. {
  135. // Inlined out param: the positive offset is relative to the start of the inlinee arg area,
  136. // so we need to subtract the full locals area (including the inlined-arg-area) to get the proper result.
  137. offset -= localsSize;
  138. }
  139. else
  140. {
  141. // The locals size contains the inlined-arg-area size, so remove the inlined-arg-area size from the
  142. // adjustment for normal locals whose offsets are relative to the start of the locals area.
  143. offset -= (localsSize - inlineeArgStackSize);
  144. }
  145. Assert(offset < 0);
  146. offsets[i] = offset;
  147. }
  148. }
  149. #endif
  150. void
  151. BailOutInfo::FinalizeBailOutRecord(Func * func)
  152. {
  153. Assert(func->IsTopFunc());
  154. BailOutRecord * bailOutRecord = this->bailOutRecord;
  155. if (bailOutRecord == nullptr)
  156. {
  157. return;
  158. }
  159. BailOutRecord * currentBailOutRecord = bailOutRecord;
  160. Func * currentBailOutFunc = this->bailOutFunc;
  161. // Top of the inlined arg stack is at the beginning of the locals, find the offset from EBP+2
  162. #ifdef MD_GROW_LOCALS_AREA_UP
  163. uint inlinedArgSlotAdjust = (func->m_localStackHeight + func->m_ArgumentsOffset);
  164. #else
  165. uint inlinedArgSlotAdjust = (func->m_localStackHeight + (2 * MachPtr));
  166. #endif
  167. while (currentBailOutRecord->parent != nullptr)
  168. {
  169. Assert(currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == -1 ||
  170. currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == (int32)(currentBailOutFunc->firstActualStackOffset - inlinedArgSlotAdjust));
  171. Assert(!currentBailOutFunc->IsTopFunc());
  172. Assert(currentBailOutFunc->firstActualStackOffset != -1);
  173. // Find the top of the locals on the stack from EBP
  174. currentBailOutRecord->globalBailOutRecordTable-> firstActualStackOffset = currentBailOutFunc->firstActualStackOffset - inlinedArgSlotAdjust;
  175. currentBailOutRecord = currentBailOutRecord->parent;
  176. currentBailOutFunc = currentBailOutFunc->GetParentFunc();
  177. }
  178. Assert(currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == -1);
  179. Assert(currentBailOutFunc->IsTopFunc());
  180. Assert(currentBailOutFunc->firstActualStackOffset == -1);
  181. #ifndef MD_GROW_LOCALS_AREA_UP
  182. if (this->totalOutParamCount != 0)
  183. {
  184. if (func->HasInlinee())
  185. {
  186. FOREACH_BITSET_IN_SPARSEBV(index, this->outParamInlinedArgSlot)
  187. {
  188. this->outParamOffsets[index] -= inlinedArgSlotAdjust;
  189. }
  190. NEXT_BITSET_IN_SPARSEBV;
  191. }
  192. #ifdef _M_IX86
  193. int frameSize = func->frameSize;
  194. AssertMsg(frameSize != 0, "Frame size not calculated");
  195. FOREACH_BITSET_IN_SPARSEBV(index, this->outParamFrameAdjustArgSlot)
  196. {
  197. this->outParamOffsets[index] -= frameSize;
  198. }
  199. NEXT_BITSET_IN_SPARSEBV;
  200. #endif
  201. }
  202. #else
  203. if (func->IsJitInDebugMode())
  204. {
  205. // Turn positive SP-relative base locals offset into negative frame-pointer-relative offset
  206. func->AjustLocalVarSlotOffset();
  207. }
  208. currentBailOutRecord = bailOutRecord;
  209. do
  210. {
  211. // Note: do this only once
  212. currentBailOutRecord->globalBailOutRecordTable->VisitGlobalBailOutRecordTableRowsAtFirstBailOut(
  213. currentBailOutRecord->m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  214. int32 inlineeArgStackSize = func->GetInlineeArgumentStackSize();
  215. int localsSize = func->m_localStackHeight + func->m_ArgumentsOffset;
  216. int offset = -(row->offset + StackSymBias);
  217. if (offset < 0)
  218. {
  219. // Not stack offset
  220. return;
  221. }
  222. // The locals size contains the inlined-arg-area size, so remove the inlined-arg-area size from the
  223. // adjustment for normal locals whose offsets are relative to the start of the locals area.
  224. offset -= (localsSize - inlineeArgStackSize);
  225. Assert(offset < 0);
  226. row->offset = offset;
  227. });
  228. currentBailOutRecord = currentBailOutRecord->parent;
  229. }
  230. while (currentBailOutRecord != nullptr);
  231. this->FinalizeOffsets(this->outParamOffsets, this->totalOutParamCount, func, func->HasInlinee() ? this->outParamInlinedArgSlot : nullptr);
  232. #endif
  233. // set the bailOutRecord to null so we don't adjust it again if the info is shared
  234. bailOutRecord = nullptr;
  235. }
  236. #if DBG
  237. bool
  238. BailOutInfo::IsBailOutHelper(IR::JnHelperMethod helper)
  239. {
  240. switch (helper)
  241. {
  242. case IR::HelperSaveAllRegistersAndBailOut:
  243. case IR::HelperSaveAllRegistersAndBranchBailOut:
  244. #ifdef _M_IX86
  245. case IR::HelperSaveAllRegistersNoSse2AndBailOut:
  246. case IR::HelperSaveAllRegistersNoSse2AndBranchBailOut:
  247. #endif
  248. return true;
  249. };
  250. return false;
  251. };
  252. #endif
  253. //===================================================================================================================================
  254. // BailOutRecord
  255. //===================================================================================================================================
  256. BailOutRecord::BailOutRecord(uint32 bailOutOffset, uint bailOutCacheIndex, IR::BailOutKind kind, Func * bailOutFunc) :
  257. argOutOffsetInfo(nullptr), bailOutOffset(bailOutOffset),
  258. bailOutCount(0), polymorphicCacheIndex(bailOutCacheIndex), bailOutKind(kind),
  259. branchValueRegSlot(Js::Constants::NoRegister),
  260. ehBailoutData(nullptr), m_bailOutRecordId(0)
  261. #if DBG
  262. , inlineDepth(0)
  263. #endif
  264. {
  265. CompileAssert(offsetof(BailOutRecord, globalBailOutRecordTable) == 0); // the offset is hard-coded in LinearScanMD::SaveAllRegisters
  266. CompileAssert(offsetof(GlobalBailOutRecordDataTable, registerSaveSpace) == 0); // the offset is hard-coded in LinearScanMD::SaveAllRegisters}
  267. Assert(bailOutOffset != Js::Constants::NoByteCodeOffset);
  268. #if DBG
  269. actualCount = bailOutFunc->actualCount;
  270. Assert(bailOutFunc->IsTopFunc() || actualCount != -1);
  271. #endif
  272. }
  273. #if ENABLE_DEBUG_CONFIG_OPTIONS
  274. #define REJIT_TESTTRACE(...) \
  275. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::ReJITPhase)) \
  276. { \
  277. Output::Print(__VA_ARGS__); \
  278. Output::Flush(); \
  279. }
  280. #define REJIT_KIND_TESTTRACE(bailOutKind, ...) \
  281. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::ReJITPhase)) \
  282. { \
  283. if (Js::Configuration::Global.flags.RejitTraceFilter.Empty() || Js::Configuration::Global.flags.RejitTraceFilter.Contains(bailOutKind)) \
  284. { \
  285. Output::Print(__VA_ARGS__); \
  286. Output::Flush(); \
  287. } \
  288. }
  289. wchar_t * const trueString = L"true";
  290. wchar_t * const falseString = L"false";
  291. #else
  292. #define REJIT_TESTTRACE(...)
  293. #define REJIT_KIND_TESTTRACE(...)
  294. #endif
  295. #if ENABLE_DEBUG_CONFIG_OPTIONS
  296. #define BAILOUT_KIND_TRACE(functionBody, bailOutKind, ...) \
  297. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) && \
  298. ((bailOutKind) != IR::BailOnSimpleJitToFullJitLoopBody || CONFIG_FLAG(Verbose))) \
  299. { \
  300. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  301. { \
  302. Output::Print(__VA_ARGS__); \
  303. if (bailOutKind != IR::BailOutInvalid) \
  304. { \
  305. Output::Print(L" Kind: %S", ::GetBailOutKindName(bailOutKind)); \
  306. } \
  307. Output::Print(L"\n"); \
  308. } \
  309. }
  310. #define BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, ...) \
  311. if (Js::Configuration::Global.flags.Verbose && Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase,functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId())) \
  312. { \
  313. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  314. { \
  315. Output::Print(__VA_ARGS__); \
  316. } \
  317. }
  318. #define BAILOUT_TESTTRACE(functionBody, bailOutKind, ...) \
  319. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) && \
  320. ((bailOutKind) != IR::BailOnSimpleJitToFullJitLoopBody || CONFIG_FLAG(Verbose))) \
  321. { \
  322. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  323. { \
  324. Output::Print(__VA_ARGS__); \
  325. } \
  326. }
  327. #define BAILOUT_FLUSH(functionBody) \
  328. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) || \
  329. Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId())) \
  330. { \
  331. Output::Flush(); \
  332. }
  333. #else
  334. #define BAILOUT_KIND_TRACE(functionBody, bailOutKind, ...)
  335. #define BAILOUT_TESTTRACE(functionBody, bailOutKind, ...)
  336. #define BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, ...)
  337. #define BAILOUT_FLUSH(functionBody)
  338. #endif
  339. #if DBG
  340. void BailOutRecord::DumpArgOffsets(uint count, int* offsets, int argOutSlotStart)
  341. {
  342. wchar_t const * name = L"OutParam";
  343. Js::RegSlot regSlotOffset = 0;
  344. for (uint i = 0; i < count; i++)
  345. {
  346. int offset = offsets[i];
  347. // The variables below determine whether we have a Var or native float/int.
  348. bool isFloat64 = this->argOutOffsetInfo->argOutFloat64Syms->Test(argOutSlotStart + i) != 0;
  349. bool isInt32 = this->argOutOffsetInfo->argOutLosslessInt32Syms->Test(argOutSlotStart + i) != 0;
  350. // SIMD_JS
  351. // Simd128 reside in Float64 regs
  352. isFloat64 |= this->argOutOffsetInfo->argOutSimd128F4Syms->Test(argOutSlotStart + i) != 0;
  353. isFloat64 |= this->argOutOffsetInfo->argOutSimd128I4Syms->Test(argOutSlotStart + i) != 0;
  354. Assert(!isFloat64 || !isInt32);
  355. Output::Print(L"%s #%3d: ", name, i + regSlotOffset);
  356. this->DumpValue(offset, isFloat64);
  357. Output::Print(L"\n");
  358. }
  359. }
  360. void BailOutRecord::DumpLocalOffsets(uint count, int argOutSlotStart)
  361. {
  362. wchar_t const * name = L"Register";
  363. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  364. Assert(row != nullptr);
  365. // The variables below determine whether we have a Var or native float/int.
  366. bool isFloat64 = row->isFloat;
  367. bool isInt32 = row->isInt;
  368. // SIMD_JS
  369. // Simd values are in float64 regs
  370. isFloat64 = isFloat64 || row->isSimd128F4;
  371. isFloat64 = isFloat64 || row->isSimd128I4;
  372. Assert(!isFloat64 || !isInt32);
  373. Output::Print(L"%s #%3d: ", name, row->regSlot);
  374. this->DumpValue(row->offset, isFloat64);
  375. Output::Print(L"\n");
  376. });
  377. }
  378. void BailOutRecord::DumpValue(int offset, bool isFloat64)
  379. {
  380. if (offset < 0)
  381. {
  382. Output::Print(L"Stack offset %6d", offset);
  383. }
  384. else if (offset > 0)
  385. {
  386. if ((uint)offset <= GetBailOutRegisterSaveSlotCount())
  387. {
  388. if (isFloat64)
  389. {
  390. #ifdef _M_ARM
  391. Output::Print(L"Register %-4S %4d", RegNames[(offset - RegD0) / 2 + RegD0], offset);
  392. #else
  393. Output::Print(L"Register %-4S %4d", RegNames[offset], offset);
  394. #endif
  395. }
  396. else
  397. {
  398. Output::Print(L"Register %-4S %4d", RegNames[offset], offset);
  399. }
  400. }
  401. else if (BailOutRecord::IsArgumentsObject((uint)offset))
  402. {
  403. Output::Print(L"Arguments object");
  404. }
  405. else
  406. {
  407. // Constants offset starts from max bail out register save slot count
  408. uint constantIndex = offset - (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount()) - 1;
  409. Output::Print(L"Constant index %4d value:0x%p (Var)", constantIndex, this->constants[constantIndex]);
  410. Assert(!isFloat64);
  411. }
  412. }
  413. else
  414. {
  415. Output::Print(L"Not live");
  416. }
  417. }
  418. void BailOutRecord::Dump()
  419. {
  420. if (this->localOffsetsCount)
  421. {
  422. Output::Print(L"**** Locals ***\n");
  423. DumpLocalOffsets(this->localOffsetsCount, 0);
  424. }
  425. uint outParamSlot = 0;
  426. if(this->argOutOffsetInfo)
  427. {
  428. Output::Print(L"**** Out params ***\n");
  429. for (uint i = 0; i < this->argOutOffsetInfo->startCallCount; i++)
  430. {
  431. uint startCallOutParamCount = this->argOutOffsetInfo->startCallOutParamCounts[i];
  432. DumpArgOffsets(startCallOutParamCount, &this->argOutOffsetInfo->outParamOffsets[outParamSlot], this->argOutOffsetInfo->argOutSymStart + outParamSlot);
  433. outParamSlot += startCallOutParamCount;
  434. }
  435. }
  436. }
  437. #endif
  438. /*static*/
  439. bool BailOutRecord::IsArgumentsObject(uint32 offset)
  440. {
  441. bool isArgumentsObject = (GetArgumentsObjectOffset() == offset);
  442. return isArgumentsObject;
  443. }
  444. /*static*/
  445. uint32 BailOutRecord::GetArgumentsObjectOffset()
  446. {
  447. uint32 argumentsObjectOffset = (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount());
  448. return argumentsObjectOffset;
  449. }
  450. Js::Var BailOutRecord::EnsureArguments(Js::InterpreterStackFrame * newInstance, Js::JavascriptCallStackLayout * layout, Js::ScriptContext* scriptContext, Js::Var* pArgumentsObject) const
  451. {
  452. Js::Var nullObj = scriptContext->GetLibrary()->GetNull();
  453. newInstance->OP_LdHeapArguments(nullObj, scriptContext);
  454. Assert(newInstance->m_arguments);
  455. *pArgumentsObject = (Js::ArgumentsObject*)newInstance->m_arguments;
  456. return newInstance->m_arguments;
  457. }
  458. Js::JavascriptCallStackLayout *BailOutRecord::GetStackLayout() const
  459. {
  460. return
  461. Js::JavascriptCallStackLayout::FromFramePointer(
  462. globalBailOutRecordTable->registerSaveSpace[LinearScanMD::GetRegisterSaveIndex(LowererMD::GetRegFramePointer()) - 1]);
  463. }
  464. void
  465. BailOutRecord::RestoreValues(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, Js::InterpreterStackFrame * newInstance,
  466. Js::ScriptContext * scriptContext, bool fromLoopBody, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::Var* pArgumentsObject,
  467. Js::Var branchValue, void * returnAddress, bool useStartCall /* = true */, void * argoutRestoreAddress) const
  468. {
  469. Js::AutoPushReturnAddressForStackWalker saveReturnAddress(scriptContext, returnAddress);
  470. if (this->stackLiteralBailOutRecordCount)
  471. {
  472. // Null out the field on the stack literal that hasn't fully initialized yet.
  473. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row)
  474. {
  475. for (uint i = 0; i < this->stackLiteralBailOutRecordCount; i++)
  476. {
  477. BailOutRecord::StackLiteralBailOutRecord& record = this->stackLiteralBailOutRecord[i];
  478. if (record.regSlot == row->regSlot)
  479. {
  480. // Partially initialized stack literal shouldn't be type specialized yet.
  481. Assert(!row->isFloat);
  482. Assert(!row->isInt);
  483. int offset = row->offset;
  484. Js::Var value;
  485. if (offset < 0)
  486. {
  487. // Stack offset
  488. value = layout->GetOffset(offset);
  489. }
  490. else
  491. {
  492. // The value is in register
  493. // Index is one based, so subtract one
  494. Assert((uint)offset <= GetBailOutRegisterSaveSlotCount());
  495. Js::Var * registerSaveSpace = registerSaves ? registerSaves : scriptContext->GetThreadContext()->GetBailOutRegisterSaveSpace();
  496. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  497. value = registerSaveSpace[offset - 1];
  498. }
  499. Assert(Js::DynamicObject::Is(value));
  500. Assert(ThreadContext::IsOnStack(value));
  501. Js::DynamicObject * obj = Js::DynamicObject::FromVar(value);
  502. uint propertyCount = obj->GetPropertyCount();
  503. for (uint j = record.initFldCount; j < propertyCount; j++)
  504. {
  505. obj->SetSlot(SetSlotArgumentsRoot(Js::Constants::NoProperty, false, j, nullptr));
  506. }
  507. }
  508. }
  509. });
  510. }
  511. if (this->localOffsetsCount)
  512. {
  513. #if ENABLE_DEBUG_CONFIG_OPTIONS
  514. Js::FunctionBody* functionBody = newInstance->function->GetFunctionBody();
  515. BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, L"BailOut: Register #%3d: Not live\n", 0);
  516. for (uint i = 1; i < functionBody->GetConstantCount(); i++)
  517. {
  518. BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, L"BailOut: Register #%3d: Constant table\n", i);
  519. }
  520. #endif
  521. if (scriptContext->IsInDebugMode())
  522. {
  523. this->AdjustOffsetsForDiagMode(layout, newInstance->GetJavascriptFunction());
  524. }
  525. this->RestoreValues(bailOutKind, layout, this->localOffsetsCount,
  526. nullptr, 0, newInstance->m_localSlots, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject);
  527. }
  528. if (useStartCall && this->argOutOffsetInfo)
  529. {
  530. uint outParamSlot = 0;
  531. void * argRestoreAddr = nullptr;
  532. for (uint i = 0; i < this->argOutOffsetInfo->startCallCount; i++)
  533. {
  534. uint startCallOutParamCount = this->argOutOffsetInfo->startCallOutParamCounts[i];
  535. #ifdef _M_IX86
  536. if (argoutRestoreAddress)
  537. {
  538. argRestoreAddr = (void*)((char*)argoutRestoreAddress + (this->startCallArgRestoreAdjustCounts[i] * MachPtr));
  539. }
  540. #endif
  541. newInstance->OP_StartCall(startCallOutParamCount);
  542. this->RestoreValues(bailOutKind, layout, startCallOutParamCount, &this->argOutOffsetInfo->outParamOffsets[outParamSlot],
  543. this->argOutOffsetInfo->argOutSymStart + outParamSlot, newInstance->m_outParams,
  544. scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject, argRestoreAddr);
  545. outParamSlot += startCallOutParamCount;
  546. }
  547. }
  548. // If we're not in a loop body, then the arguments object is not on the local frame.
  549. // If the RestoreValues created an arguments object for us, then it's already on the interpreter instance.
  550. // Otherwise, we need to propagate the object from the jitted frame to the interpreter.
  551. Assert(newInstance->function && newInstance->function->GetFunctionBody());
  552. bool hasArgumentSlot = // Be consistent with Func::HasArgumentSlot.
  553. !fromLoopBody && newInstance->function->GetFunctionBody()->GetInParamsCount() != 0;
  554. if (hasArgumentSlot && newInstance->m_arguments == nullptr)
  555. {
  556. newInstance->m_arguments = *pArgumentsObject;
  557. }
  558. if (bailOutReturnValue != nullptr && bailOutReturnValue->returnValueRegSlot != Js::Constants::NoRegister)
  559. {
  560. Assert(bailOutReturnValue->returnValue != nullptr);
  561. Assert(bailOutReturnValue->returnValueRegSlot < newInstance->GetJavascriptFunction()->GetFunctionBody()->GetLocalsCount());
  562. newInstance->m_localSlots[bailOutReturnValue->returnValueRegSlot] = bailOutReturnValue->returnValue;
  563. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"BailOut: Register #%3d: Return, value: 0x%p\n",
  564. bailOutReturnValue->returnValueRegSlot, bailOutReturnValue->returnValue);
  565. }
  566. if (branchValueRegSlot != Js::Constants::NoRegister)
  567. {
  568. // Used when a t1 = CmCC is optimize to BrCC, and the branch bails out. T1 needs to be restored
  569. Assert(branchValue && Js::JavascriptBoolean::Is(branchValue));
  570. Assert(branchValueRegSlot < newInstance->GetJavascriptFunction()->GetFunctionBody()->GetLocalsCount());
  571. newInstance->m_localSlots[branchValueRegSlot] = branchValue;
  572. }
  573. #if DBG
  574. // Clear the register save area for the next bailout
  575. memset(scriptContext->GetThreadContext()->GetBailOutRegisterSaveSpace(), 0, GetBailOutRegisterSaveSlotCount() * sizeof(Js::Var));
  576. #endif
  577. }
  578. void
  579. BailOutRecord::AdjustOffsetsForDiagMode(Js::JavascriptCallStackLayout * layout, Js::ScriptFunction * function) const
  580. {
  581. // In this function we are going to do
  582. // 1. Check if the value got changed (by checking at the particular location at the stack)
  583. // 2. In that case update the offset to point to the stack offset
  584. Assert(function->GetScriptContext()->IsInDebugMode());
  585. Js::FunctionBody *functionBody = function->GetFunctionBody();
  586. Assert(functionBody != nullptr);
  587. Js::FunctionEntryPointInfo *entryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  588. Assert(entryPointInfo != nullptr);
  589. // Note: the offset may be not initialized/InvalidOffset when there are no non-temp local vars.
  590. if (entryPointInfo->localVarChangedOffset != Js::Constants::InvalidOffset)
  591. {
  592. Assert(functionBody->GetNonTempLocalVarCount() != 0);
  593. char * valueChangeOffset = layout->GetValueChangeOffset(entryPointInfo->localVarChangedOffset);
  594. if (*valueChangeOffset == Js::FunctionBody::LocalsChangeDirtyValue)
  595. {
  596. // The value got changed due to debugger, lets read values from the stack position
  597. // Get the corresponding offset on the stack related to the frame.
  598. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  599. int32 offset = row->offset;
  600. // offset is zero, is it possible that a locals is not living in the debug mode?
  601. Assert(offset != 0);
  602. int32 slotOffset;
  603. if (functionBody->GetSlotOffset(row->regSlot, &slotOffset))
  604. {
  605. slotOffset = entryPointInfo->localVarSlotsOffset + slotOffset;
  606. // If it was taken from the stack location, we should have arrived to the same stack location.
  607. Assert(offset > 0 || offset == slotOffset);
  608. row->offset = slotOffset;
  609. }
  610. });
  611. }
  612. }
  613. }
  614. void
  615. BailOutRecord::IsOffsetNativeIntOrFloat(uint offsetIndex, int argOutSlotStart, bool * pIsFloat64, bool * pIsInt32, bool * pIsSimd128F4, bool * pIsSimd128I4) const
  616. {
  617. bool isFloat64 = this->argOutOffsetInfo->argOutFloat64Syms->Test(argOutSlotStart + offsetIndex) != 0;
  618. bool isInt32 = this->argOutOffsetInfo->argOutLosslessInt32Syms->Test(argOutSlotStart + offsetIndex) != 0;
  619. // SIMD_JS
  620. bool isSimd128F4 = this->argOutOffsetInfo->argOutSimd128F4Syms->Test(argOutSlotStart + offsetIndex) != 0;
  621. bool isSimd128I4 = this->argOutOffsetInfo->argOutSimd128I4Syms->Test(argOutSlotStart + offsetIndex) != 0;
  622. Assert(!isFloat64 || !isInt32 || !isSimd128F4 || !isSimd128I4);
  623. *pIsFloat64 = isFloat64;
  624. *pIsInt32 = isInt32;
  625. *pIsSimd128F4 = isSimd128F4;
  626. *pIsSimd128I4 = isSimd128I4;
  627. }
  628. void
  629. BailOutRecord::RestoreValue(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, Js::Var * values, Js::ScriptContext * scriptContext,
  630. bool fromLoopBody, Js::Var * registerSaves, Js::InterpreterStackFrame * newInstance, Js::Var* pArgumentsObject, void * argoutRestoreAddress,
  631. uint regSlot, int offset, bool isLocal, bool isFloat64, bool isInt32, bool isSimd128F4, bool isSimd128I4) const
  632. {
  633. bool boxStackInstance = true;
  634. Js::Var value = 0;
  635. double dblValue = 0.0;
  636. int32 int32Value = 0;
  637. SIMDValue simdValue = { 0, 0, 0, 0 };
  638. #if ENABLE_DEBUG_CONFIG_OPTIONS
  639. wchar_t const * name = L"OutParam";
  640. if (isLocal)
  641. {
  642. name = L"Register";
  643. }
  644. #endif
  645. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"BailOut: %s #%3d: ", name, regSlot);
  646. if (offset < 0)
  647. {
  648. // Stack offset are negative
  649. if (!argoutRestoreAddress)
  650. {
  651. if (isFloat64)
  652. {
  653. dblValue = layout->GetDoubleAtOffset(offset);
  654. }
  655. else if (isInt32)
  656. {
  657. int32Value = layout->GetInt32AtOffset(offset);
  658. }
  659. else if (isSimd128F4 || isSimd128I4)
  660. {
  661. // SIMD_JS
  662. simdValue = layout->GetSimdValueAtOffset(offset);
  663. }
  664. else
  665. {
  666. value = layout->GetOffset(offset);
  667. AssertMsg(!(scriptContext->IsInDebugMode() &&
  668. newInstance->function->GetFunctionBody()->IsNonTempLocalVar(regSlot) &&
  669. value == (Js::Var)Func::c_debugFillPattern),
  670. "Uninitialized value (debug mode only)? Try -trace:bailout -verbose and check last traced reg in byte code.");
  671. }
  672. }
  673. else if (!isLocal)
  674. {
  675. // If we have:
  676. // try {
  677. // bar(a, b, c);
  678. // } catch(..) {..}
  679. // and we bailout during bar args evaluation, we recover from args from argoutRestoreAddress, not from caller function frame.
  680. // This is because try-catch is implemented as a C wrapper, so args will be a different offset from rbp in that case.
  681. Assert(!isFloat64 && !isInt32 && !isSimd128F4 && !isSimd128I4);
  682. value = *((Js::Var *)(((char *)argoutRestoreAddress) + regSlot * MachPtr));
  683. AssertMsg(!(scriptContext->IsInDebugMode() &&
  684. newInstance->function->GetFunctionBody()->IsNonTempLocalVar(regSlot) &&
  685. value == (Js::Var)Func::c_debugFillPattern),
  686. "Uninitialized value (debug mode only)? Try -trace:bailout -verbose and check last traced reg in byte code.");
  687. }
  688. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Stack offset %6d", offset);
  689. }
  690. else if (offset > 0)
  691. {
  692. if ((uint)offset <= GetBailOutRegisterSaveSlotCount())
  693. {
  694. // Register save space (offset is the register number and index into the register save space)
  695. // Index is one based, so subtract one
  696. Js::Var * registerSaveSpace = registerSaves ? registerSaves : scriptContext->GetThreadContext()->GetBailOutRegisterSaveSpace();
  697. if (isFloat64)
  698. {
  699. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] == TyFloat64);
  700. dblValue = *((double*)&(registerSaveSpace[offset - 1]));
  701. #ifdef _M_ARM
  702. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Register %-4S %4d", RegNames[(offset - RegD0) / 2 + RegD0], offset);
  703. #else
  704. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Register %-4S %4d", RegNames[LinearScanMD::GetRegisterFromSaveIndex(offset)], offset);
  705. #endif
  706. }
  707. else
  708. {
  709. if (isSimd128F4 || isSimd128I4)
  710. {
  711. simdValue = *((SIMDValue *)&(registerSaveSpace[offset - 1]));
  712. }
  713. else if (isInt32)
  714. {
  715. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  716. int32Value = ::Math::PointerCastToIntegralTruncate<int32>(registerSaveSpace[offset - 1]);
  717. }
  718. else
  719. {
  720. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  721. value = registerSaveSpace[offset - 1];
  722. }
  723. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Register %-4S %4d", RegNames[LinearScanMD::GetRegisterFromSaveIndex(offset)], offset);
  724. }
  725. }
  726. else if (BailOutRecord::IsArgumentsObject((uint)offset))
  727. {
  728. Assert(!isFloat64);
  729. Assert(!isInt32);
  730. Assert(!fromLoopBody);
  731. value = *pArgumentsObject;
  732. if (value == nullptr)
  733. {
  734. value = EnsureArguments(newInstance, layout, scriptContext, pArgumentsObject);
  735. }
  736. Assert(value);
  737. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Arguments object");
  738. boxStackInstance = false;
  739. }
  740. else
  741. {
  742. // Constants offset starts from max bail out register save slot count;
  743. uint constantIndex = offset - (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount()) - 1;
  744. if (isInt32)
  745. {
  746. int32Value = ::Math::PointerCastToIntegralTruncate<int32>(this->constants[constantIndex]);
  747. }
  748. else
  749. {
  750. value = this->constants[constantIndex];
  751. }
  752. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Constant index %4d", constantIndex);
  753. boxStackInstance = false;
  754. }
  755. }
  756. else
  757. {
  758. // Consider Assert(false) here
  759. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"Not live\n");
  760. return;
  761. }
  762. if (isFloat64)
  763. {
  764. value = Js::JavascriptNumber::New(dblValue, scriptContext);
  765. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L", value: %f (ToVar: 0x%p)", dblValue, value);
  766. }
  767. else if (isInt32)
  768. {
  769. Assert(!value);
  770. value = Js::JavascriptNumber::ToVar(int32Value, scriptContext);
  771. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L", value: %10d (ToVar: 0x%p)", int32Value, value);
  772. }
  773. // SIMD_JS
  774. else if (isSimd128F4)
  775. {
  776. Assert(!value);
  777. value = Js::JavascriptSIMDFloat32x4::New(&simdValue, scriptContext);
  778. }
  779. else if (isSimd128I4)
  780. {
  781. Assert(!value);
  782. value = Js::JavascriptSIMDInt32x4::New(&simdValue, scriptContext);
  783. }
  784. else
  785. {
  786. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L", value: 0x%p", value);
  787. if (boxStackInstance)
  788. {
  789. Js::Var oldValue = value;
  790. value = Js::JavascriptOperators::BoxStackInstance(oldValue, scriptContext, /* allowStackFunction */ true);
  791. if (oldValue != value)
  792. {
  793. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L" (Boxed: 0x%p)", value);
  794. }
  795. }
  796. }
  797. values[regSlot] = value;
  798. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"\n");
  799. }
  800. void
  801. BailOutRecord::RestoreValues(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, uint count, __in_ecount_opt(count) int * offsets, int argOutSlotStart,
  802. __out_ecount(count) Js::Var * values, Js::ScriptContext * scriptContext,
  803. bool fromLoopBody, Js::Var * registerSaves, Js::InterpreterStackFrame * newInstance, Js::Var* pArgumentsObject, void * argoutRestoreAddress) const
  804. {
  805. bool isLocal = offsets == nullptr;
  806. if (isLocal == true)
  807. {
  808. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  809. Assert(row->offset != 0);
  810. RestoreValue(bailOutKind, layout, values, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject,
  811. argoutRestoreAddress, row->regSlot, row->offset, true, row->isFloat, row->isInt, row->isSimd128F4, row->isSimd128I4);
  812. });
  813. }
  814. else
  815. {
  816. for (uint i = 0; i < count; i++)
  817. {
  818. int offset = 0;
  819. // The variables below determine whether we have a Var or native float/int.
  820. bool isFloat64;
  821. bool isInt32;
  822. bool isSimd128F4, isSimd128I4;
  823. offset = offsets[i];
  824. this->IsOffsetNativeIntOrFloat(i, argOutSlotStart, &isFloat64, &isInt32, &isSimd128F4, &isSimd128I4);
  825. RestoreValue(bailOutKind, layout, values, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject,
  826. argoutRestoreAddress, i, offset, false, isFloat64, isInt32, isSimd128F4, isSimd128I4);
  827. }
  828. }
  829. }
  830. Js::Var BailOutRecord::BailOut(BailOutRecord const * bailOutRecord)
  831. {
  832. Assert(bailOutRecord);
  833. void * argoutRestoreAddr = nullptr;
  834. #ifdef _M_IX86
  835. void * addressOfRetAddress = _AddressOfReturnAddress();
  836. if (bailOutRecord->ehBailoutData && (bailOutRecord->ehBailoutData->catchOffset != 0))
  837. {
  838. // For a bailout in argument evaluation from an EH region, the esp is offset by the TryCatch helper’s frame. So, the argouts are not at the offsets
  839. // stored in the bailout record, which are relative to ebp. Need to restore the argouts from the actual value of esp before calling the Bailout helper
  840. argoutRestoreAddr = (void *)((char*)addressOfRetAddress + ((1 + 1) * MachPtr)); // Account for the parameter and return address of this function
  841. }
  842. #endif
  843. Js::JavascriptCallStackLayout *const layout = bailOutRecord->GetStackLayout();
  844. if(bailOutRecord->globalBailOutRecordTable->isLoopBody)
  845. {
  846. if (bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  847. {
  848. return reinterpret_cast<Js::Var>(BailOutFromLoopBodyInlined(layout, bailOutRecord, _ReturnAddress()));
  849. }
  850. return reinterpret_cast<Js::Var>(BailOutFromLoopBody(layout, bailOutRecord));
  851. }
  852. if(bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  853. {
  854. return BailOutInlined(layout, bailOutRecord, _ReturnAddress());
  855. }
  856. return BailOutFromFunction(layout, bailOutRecord, _ReturnAddress(), argoutRestoreAddr);
  857. }
  858. uint32
  859. BailOutRecord::BailOutFromLoopBody(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord)
  860. {
  861. Assert(bailOutRecord->parent == nullptr);
  862. return BailOutFromLoopBodyCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, bailOutRecord->bailOutKind);
  863. }
  864. Js::Var
  865. BailOutRecord::BailOutFromFunction(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress, void * argoutRestoreAddress)
  866. {
  867. Assert(bailOutRecord->parent == nullptr);
  868. return BailOutCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind, nullptr, nullptr, argoutRestoreAddress);
  869. }
  870. Js::Var
  871. BailOutRecord::BailOutInlined(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress)
  872. {
  873. Assert(bailOutRecord->parent != nullptr);
  874. return BailOutInlinedCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind);
  875. }
  876. uint32
  877. BailOutRecord::BailOutFromLoopBodyInlined(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress)
  878. {
  879. Assert(bailOutRecord->parent != nullptr);
  880. return BailOutFromLoopBodyInlinedCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind);
  881. }
  882. Js::Var
  883. BailOutRecord::BailOutCommonNoCodeGen(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  884. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue, Js::Var * registerSaves,
  885. BailOutReturnValue * bailOutReturnValue, void * argoutRestoreAddress)
  886. {
  887. Assert(bailOutRecord->parent == nullptr);
  888. Assert(Js::ScriptFunction::Is(layout->functionObject));
  889. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&layout->functionObject;
  890. Js::ArgumentReader args(&layout->callInfo, layout->args);
  891. Js::Var result = BailOutHelper(layout, functionRef, args, false, bailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, bailOutReturnValue, layout->GetArgumentsObjectLocation(), branchValue, argoutRestoreAddress);
  892. return result;
  893. }
  894. Js::Var
  895. BailOutRecord::BailOutCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  896. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue, BailOutReturnValue * bailOutReturnValue, void * argoutRestoreAddress)
  897. {
  898. // Do not remove the following code.
  899. // Need to capture the int registers on stack as threadContext->bailOutRegisterSaveSpace is allocated from ThreadAlloc and is not scanned by recycler.
  900. // We don't want to save float (xmm) registers as they can be huge and they cannot contain a var.
  901. Js::Var registerSaves[INT_REG_COUNT];
  902. js_memcpy_s(registerSaves, sizeof(registerSaves), layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  903. sizeof(registerSaves));
  904. Js::Var result = BailOutCommonNoCodeGen(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutKind, branchValue, nullptr, bailOutReturnValue, argoutRestoreAddress);
  905. ScheduleFunctionCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), nullptr, bailOutRecord, bailOutKind, returnAddress);
  906. return result;
  907. }
  908. Js::Var
  909. BailOutRecord::BailOutInlinedCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, uint32 bailOutOffset,
  910. void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue)
  911. {
  912. Assert(bailOutRecord->parent != nullptr);
  913. // Need to capture the register save, one of the bailout might get into jitted code again and bailout again
  914. // overwriting the current register saves
  915. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  916. js_memcpy_s(registerSaves, sizeof(registerSaves), layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  917. sizeof(registerSaves));
  918. BailOutRecord const * currentBailOutRecord = bailOutRecord;
  919. BailOutReturnValue bailOutReturnValue;
  920. Js::ScriptFunction * innerMostInlinee;
  921. BailOutInlinedHelper(layout, currentBailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, &bailOutReturnValue, &innerMostInlinee, false, branchValue);
  922. Js::Var result = BailOutCommonNoCodeGen(layout, currentBailOutRecord, currentBailOutRecord->bailOutOffset, returnAddress, bailOutKind, branchValue,
  923. registerSaves, &bailOutReturnValue);
  924. ScheduleFunctionCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), innerMostInlinee, currentBailOutRecord, bailOutKind, returnAddress);
  925. return result;
  926. }
  927. uint32
  928. BailOutRecord::BailOutFromLoopBodyCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, uint32 bailOutOffset,
  929. IR::BailOutKind bailOutKind, Js::Var branchValue)
  930. {
  931. uint32 result = BailOutFromLoopBodyHelper(layout, bailOutRecord, bailOutOffset, bailOutKind, branchValue);
  932. ScheduleLoopBodyCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), nullptr, bailOutRecord, bailOutKind);
  933. return result;
  934. }
  935. uint32
  936. BailOutRecord::BailOutFromLoopBodyInlinedCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  937. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue)
  938. {
  939. Assert(bailOutRecord->parent != nullptr);
  940. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  941. js_memcpy_s(registerSaves, sizeof(registerSaves), layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  942. sizeof(registerSaves));
  943. BailOutRecord const * currentBailOutRecord = bailOutRecord;
  944. BailOutReturnValue bailOutReturnValue;
  945. Js::ScriptFunction * innerMostInlinee;
  946. BailOutInlinedHelper(layout, currentBailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, &bailOutReturnValue, &innerMostInlinee, true, branchValue);
  947. uint32 result = BailOutFromLoopBodyHelper(layout, currentBailOutRecord, currentBailOutRecord->bailOutOffset,
  948. bailOutKind, nullptr, registerSaves, &bailOutReturnValue);
  949. ScheduleLoopBodyCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), innerMostInlinee, currentBailOutRecord, bailOutKind);
  950. return result;
  951. }
  952. void
  953. BailOutRecord::BailOutInlinedHelper(Js::JavascriptCallStackLayout * layout, BailOutRecord const *& currentBailOutRecord,
  954. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::ScriptFunction ** innerMostInlinee, bool isInLoopBody, Js::Var branchValue)
  955. {
  956. Assert(currentBailOutRecord->parent != nullptr);
  957. BailOutReturnValue * lastBailOutReturnValue = nullptr;
  958. *innerMostInlinee = nullptr;
  959. Js::FunctionBody* functionBody = Js::ScriptFunction::FromVar(layout->functionObject)->GetFunctionBody();
  960. Js::EntryPointInfo *entryPointInfo;
  961. if(isInLoopBody)
  962. {
  963. Js::InterpreterStackFrame * interpreterFrame = functionBody->GetScriptContext()->GetThreadContext()->GetLeafInterpreterFrame();
  964. uint loopNum = interpreterFrame->GetCurrentLoopNum();
  965. entryPointInfo = (Js::EntryPointInfo*)functionBody->GetLoopEntryPointInfoFromNativeAddress((DWORD_PTR)returnAddress, loopNum);
  966. }
  967. else
  968. {
  969. entryPointInfo = (Js::EntryPointInfo*)functionBody->GetEntryPointFromNativeAddress((DWORD_PTR)returnAddress);
  970. }
  971. // Let's restore the inline stack - so that in case of a stack walk we have it available
  972. if (entryPointInfo->HasInlinees())
  973. {
  974. InlineeFrameRecord* inlineeFrameRecord = entryPointInfo->FindInlineeFrame(returnAddress);
  975. if (inlineeFrameRecord)
  976. {
  977. InlinedFrameLayout* outerMostFrame = (InlinedFrameLayout *)(((uint8 *)Js::JavascriptCallStackLayout::ToFramePointer(layout)) - entryPointInfo->frameHeight);
  978. inlineeFrameRecord->RestoreFrames(functionBody, outerMostFrame, layout);
  979. }
  980. }
  981. do
  982. {
  983. InlinedFrameLayout *inlinedFrame = (InlinedFrameLayout *)(((char *)layout) + currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset);
  984. Js::InlineeCallInfo inlineeCallInfo = inlinedFrame->callInfo;
  985. Assert((Js::ArgSlot)inlineeCallInfo.Count == currentBailOutRecord->actualCount);
  986. Js::CallInfo callInfo(Js::CallFlags_Value, (Js::ArgSlot)inlineeCallInfo.Count);
  987. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&(inlinedFrame->function);
  988. AnalysisAssert(*functionRef);
  989. Assert(Js::ScriptFunction::Is(inlinedFrame->function));
  990. if (*innerMostInlinee == nullptr)
  991. {
  992. *innerMostInlinee = *functionRef;
  993. }
  994. Js::ArgumentReader args(&callInfo, inlinedFrame->GetArguments());
  995. Js::Var* pArgumentsObject = &inlinedFrame->arguments;
  996. (*functionRef)->GetFunctionBody()->EnsureDynamicProfileInfo();
  997. bailOutReturnValue->returnValue = BailOutHelper(layout, functionRef, args, true, currentBailOutRecord, bailOutOffset,
  998. returnAddress, bailOutKind, registerSaves, lastBailOutReturnValue, pArgumentsObject, branchValue);
  999. // Clear the inlinee frame CallInfo, just like we'd have done in JITted code.
  1000. inlinedFrame->callInfo.Clear();
  1001. bailOutReturnValue->returnValueRegSlot = currentBailOutRecord->globalBailOutRecordTable->returnValueRegSlot;
  1002. lastBailOutReturnValue = bailOutReturnValue;
  1003. currentBailOutRecord = currentBailOutRecord->parent;
  1004. bailOutOffset = currentBailOutRecord->bailOutOffset;
  1005. }
  1006. while (currentBailOutRecord->parent != nullptr);
  1007. }
  1008. uint32
  1009. BailOutRecord::BailOutFromLoopBodyHelper(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  1010. uint32 bailOutOffset, IR::BailOutKind bailOutKind, Js::Var branchValue, Js::Var *registerSaves, BailOutReturnValue * bailOutReturnValue)
  1011. {
  1012. Assert(bailOutRecord->parent == nullptr);
  1013. Js::JavascriptFunction * function = layout->functionObject;
  1014. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1015. executeFunction->SetRecentlyBailedOutOfJittedLoopBody(true);
  1016. Js::ScriptContext * functionScriptContext = executeFunction->GetScriptContext();
  1017. // Clear the disable implicit call bit in case we bail from that region
  1018. functionScriptContext->GetThreadContext()->ClearDisableImplicitFlags();
  1019. // The current interpreter frame for the loop body
  1020. Js::InterpreterStackFrame * interpreterFrame = functionScriptContext->GetThreadContext()->GetLeafInterpreterFrame();
  1021. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  1022. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1023. #endif
  1024. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, L"BailOut: function: %s (%s) Loop: %d offset: #%04x Opcode: %s",
  1025. executeFunction->GetDisplayName(), executeFunction->GetDebugNumberSet(debugStringBuffer), interpreterFrame->GetCurrentLoopNum(),
  1026. bailOutOffset, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1027. BAILOUT_TESTTRACE(executeFunction, bailOutKind, L"BailOut: function: %s (%s) Loop: %d Opcode: %s\n", executeFunction->GetDisplayName(),
  1028. executeFunction->GetDebugNumberSet(debugStringBuffer), interpreterFrame->GetCurrentLoopNum(), Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1029. // Restore bailout values
  1030. bailOutRecord->RestoreValues(bailOutKind, layout, interpreterFrame, functionScriptContext, true, registerSaves, bailOutReturnValue, layout->GetArgumentsObjectLocation(), branchValue);
  1031. BAILOUT_FLUSH(executeFunction);
  1032. UpdatePolymorphicFieldAccess(function, bailOutRecord);
  1033. // Return the resume byte code offset from the loop body to restart interpreter execution.
  1034. return bailOutOffset;
  1035. }
  1036. void BailOutRecord::UpdatePolymorphicFieldAccess(Js::JavascriptFunction * function, BailOutRecord const * bailOutRecord)
  1037. {
  1038. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1039. Js::DynamicProfileInfo *dynamicProfileInfo = nullptr;
  1040. if (executeFunction->HasDynamicProfileInfo())
  1041. {
  1042. dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1043. Assert(dynamicProfileInfo);
  1044. if (bailOutRecord->polymorphicCacheIndex != (uint)-1)
  1045. {
  1046. dynamicProfileInfo->RecordPolymorphicFieldAccess(function->GetFunctionBody(), bailOutRecord->polymorphicCacheIndex);
  1047. if (IR::IsEquivalentTypeCheckBailOutKind(bailOutRecord->bailOutKind))
  1048. {
  1049. // If we've already got a polymorphic inline cache, and if we've got an equivalent type check
  1050. // bailout here, make sure we don't try any more equivalent obj type spec using that cache.
  1051. Js::PolymorphicInlineCache *polymorphicInlineCache = executeFunction->GetPolymorphicInlineCache(
  1052. bailOutRecord->polymorphicCacheIndex);
  1053. if (polymorphicInlineCache)
  1054. {
  1055. polymorphicInlineCache->SetIgnoreForEquivalentObjTypeSpec(true);
  1056. }
  1057. }
  1058. }
  1059. }
  1060. }
  1061. Js::Var
  1062. BailOutRecord::BailOutHelper(Js::JavascriptCallStackLayout * layout, Js::ScriptFunction ** functionRef, Js::Arguments& args, const bool isInlinee,
  1063. BailOutRecord const * bailOutRecord, uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::Var* pArgumentsObject,
  1064. Js::Var branchValue, void * argoutRestoreAddress)
  1065. {
  1066. Js::ScriptFunction * function = *functionRef;
  1067. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1068. Js::ScriptContext * functionScriptContext = executeFunction->GetScriptContext();
  1069. // Whether to enter StartCall while doing RestoreValues. We don't do that when bailout due to ignore exception under debugger.
  1070. bool useStartCall = true;
  1071. // Clear the disable implicit call bit in case we bail from that region
  1072. functionScriptContext->GetThreadContext()->ClearDisableImplicitFlags();
  1073. bool isInDebugMode = functionScriptContext->IsInDebugMode();
  1074. AssertMsg(!isInDebugMode || Js::Configuration::Global.EnableJitInDebugMode(),
  1075. "In diag mode we can get here (function has to be JIT'ed) only when EnableJitInDiagMode is true!");
  1076. // Adjust bailout offset for debug mode (only scenario when we ignore exception).
  1077. if (isInDebugMode)
  1078. {
  1079. Js::DebugManager* debugManager = functionScriptContext->GetThreadContext()->GetDebugManager();
  1080. DebuggingFlags* debuggingFlags = debugManager->GetDebuggingFlags();
  1081. int byteCodeOffsetAfterEx = debuggingFlags->GetByteCodeOffsetAfterIgnoreException();
  1082. // Note that in case where bailout for ignore exception immediately follows regular bailout after a helper,
  1083. // and ignore exception happens, we would bail out with non-exception kind with exception data recorded.
  1084. // In this case we need to treat the bailout as ignore exception one and continue to next/set stmt.
  1085. // This is fine because we only set byteCodeOffsetAfterEx for helpers (HelperMethodWrapper, when enabled)
  1086. // and ignore exception is needed for all helpers.
  1087. if ((bailOutKind & IR::BailOutIgnoreException) || byteCodeOffsetAfterEx != DebuggingFlags::InvalidByteCodeOffset)
  1088. {
  1089. bool needResetData = true;
  1090. // Note: the func # in debuggingFlags still can be 0 in case actual b/o reason was not BailOutIgnoreException,
  1091. // but BailOutIgnoreException was on the OR'ed values for b/o check.
  1092. bool isSameFunction = debuggingFlags->GetFuncNumberAfterIgnoreException() == DebuggingFlags::InvalidFuncNumber ||
  1093. debuggingFlags->GetFuncNumberAfterIgnoreException() == function->GetFunctionBody()->GetFunctionNumber();
  1094. AssertMsg(isSameFunction, "Bailout due to ignore exception in different function, can't bail out cross functions!");
  1095. if (isSameFunction)
  1096. {
  1097. Assert(!(byteCodeOffsetAfterEx == DebuggingFlags::InvalidByteCodeOffset && debuggingFlags->GetFuncNumberAfterIgnoreException() != DebuggingFlags::InvalidFuncNumber));
  1098. if (byteCodeOffsetAfterEx != DebuggingFlags::InvalidByteCodeOffset)
  1099. {
  1100. // We got an exception in native frame, and need to bail out to interpreter
  1101. if (debugManager->stepController.IsActive())
  1102. {
  1103. // Native frame went away, and there will be interpreter frame on its place.
  1104. // Make sure that frameAddrWhenSet it less than current interpreter frame -- we use it to detect stack depth.
  1105. debugManager->stepController.SetFrameAddr(0);
  1106. }
  1107. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1108. if (bailOutOffset != (uint)byteCodeOffsetAfterEx || !(bailOutKind & IR::BailOutIgnoreException))
  1109. {
  1110. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1111. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, L"BailOut: changing due to ignore exception: function: %s (%s) offset: #%04x -> #%04x Opcode: %s Treating as: %S", executeFunction->GetDisplayName(),
  1112. executeFunction->GetDebugNumberSet(debugStringBuffer), bailOutOffset, byteCodeOffsetAfterEx, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode), ::GetBailOutKindName(IR::BailOutIgnoreException));
  1113. }
  1114. #endif
  1115. // Set the byte code offset to continue from next user statement.
  1116. bailOutOffset = byteCodeOffsetAfterEx;
  1117. // Reset current call count so that we don't do StartCall for inner calls. See WinBlue 272569.
  1118. // The idea is that next statement can never be set to the inner StartCall (another call as part of an ArgOut),
  1119. // it will be next statement in the function.
  1120. useStartCall = false;
  1121. }
  1122. else
  1123. {
  1124. needResetData = false;
  1125. }
  1126. }
  1127. if (needResetData)
  1128. {
  1129. // Reset/correct the flag as either we processed it or we need to correct wrong flag.
  1130. debuggingFlags->ResetByteCodeOffsetAndFuncAfterIgnoreException();
  1131. }
  1132. }
  1133. }
  1134. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  1135. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1136. #endif
  1137. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, L"BailOut: function: %s (%s) offset: #%04x Opcode: %s", executeFunction->GetDisplayName(),
  1138. executeFunction->GetDebugNumberSet(debugStringBuffer), bailOutOffset, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1139. BAILOUT_TESTTRACE(executeFunction, bailOutKind, L"BailOut: function: %s (%s) Opcode: %s\n", executeFunction->GetDisplayName(),
  1140. executeFunction->GetDebugNumberSet(debugStringBuffer), Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1141. if (isInlinee && args.Info.Count != 0)
  1142. {
  1143. // Box arguments. Inlinee arguments may be allocated on the stack.
  1144. for(uint i = 0; i < args.Info.Count; ++i)
  1145. {
  1146. const Js::Var arg = args.Values[i];
  1147. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, L"BailOut: Argument #%3u: value: 0x%p", i, arg);
  1148. const Js::Var boxedArg = Js::JavascriptOperators::BoxStackInstance(arg, functionScriptContext, true);
  1149. if(boxedArg != arg)
  1150. {
  1151. args.Values[i] = boxedArg;
  1152. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, L" (Boxed: 0x%p)", boxedArg);
  1153. }
  1154. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, L"\n");
  1155. }
  1156. }
  1157. bool fReleaseAlloc = false;
  1158. Js::InterpreterStackFrame* newInstance = nullptr;
  1159. Js::Var* allocation = nullptr;
  1160. if (executeFunction->IsGenerator())
  1161. {
  1162. // If the FunctionBody is a generator then this call is being made by one of the three
  1163. // generator resuming methods: next(), throw(), or return(). They all pass the generator
  1164. // object as the first of two arguments. The real user arguments are obtained from the
  1165. // generator object. The second argument is the ResumeYieldData which is only needed
  1166. // when resuming a generator and not needed when yielding from a generator, as is occurring
  1167. // here.
  1168. AssertMsg(args.Info.Count == 2, "Generator ScriptFunctions should only be invoked by generator APIs with the pair of arguments they pass in -- the generator object and a ResumeYieldData pointer");
  1169. Js::JavascriptGenerator* generator = Js::JavascriptGenerator::FromVar(args[0]);
  1170. newInstance = generator->GetFrame();
  1171. if (newInstance != nullptr)
  1172. {
  1173. // BailOut will recompute OutArg pointers based on BailOutRecord. Reset them back
  1174. // to initial position before that happens so that OP_StartCall calls don't accumulate
  1175. // incorrectly over multiple yield bailouts.
  1176. newInstance->ResetOut();
  1177. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  1178. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  1179. newInstance->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  1180. }
  1181. else
  1182. {
  1183. //
  1184. // Allocate a new InterpreterStackFrame instance on the recycler heap.
  1185. // It will live with the JavascriptGenerator object.
  1186. //
  1187. Js::Arguments generatorArgs = generator->GetArguments();
  1188. Js::InterpreterStackFrame::Setup setup(function, generatorArgs, isInlinee);
  1189. size_t varAllocCount = setup.GetAllocationVarCount();
  1190. size_t varSizeInBytes = varAllocCount * sizeof(Js::Var);
  1191. DWORD_PTR stackAddr = reinterpret_cast<DWORD_PTR>(&generator); // as mentioned above, use any stack address from this frame to ensure correct debugging functionality
  1192. Js::Var loopHeaderArray = executeFunction->GetHasAllocatedLoopHeaders() ? executeFunction->GetLoopHeaderArrayPtr() : nullptr;
  1193. allocation = RecyclerNewPlus(functionScriptContext->GetRecycler(), varSizeInBytes, Js::Var);
  1194. // Initialize the interpreter stack frame (constants) but not the param, the bailout record will restore the value
  1195. #if DBG
  1196. // Allocate invalidVar on GC instead of stack since this InterpreterStackFrame will out live the current real frame
  1197. Js::RecyclableObject* invalidVar = (Js::RecyclableObject*)RecyclerNewPlusLeaf(functionScriptContext->GetRecycler(), sizeof(Js::RecyclableObject), Js::Var);
  1198. memset(invalidVar, 0xFE, sizeof(Js::RecyclableObject));
  1199. newInstance = setup.InitializeAllocation(allocation, false, false, loopHeaderArray, stackAddr, invalidVar);
  1200. #else
  1201. newInstance = setup.InitializeAllocation(allocation, false, false, loopHeaderArray, stackAddr);
  1202. #endif
  1203. newInstance->m_reader.Create(executeFunction);
  1204. generator->SetFrame(newInstance);
  1205. }
  1206. }
  1207. else
  1208. {
  1209. Js::InterpreterStackFrame::Setup setup(function, args, isInlinee);
  1210. size_t varAllocCount = setup.GetAllocationVarCount();
  1211. size_t varSizeInBytes = varAllocCount * sizeof(Js::Var);
  1212. // If the locals area exceeds a certain limit, allocate it from a private arena rather than
  1213. // this frame. The current limit is based on an old assert on the number of locals we would allow here.
  1214. if (varAllocCount > Js::InterpreterStackFrame::LocalsThreshold)
  1215. {
  1216. ArenaAllocator *tmpAlloc = nullptr;
  1217. fReleaseAlloc = functionScriptContext->EnsureInterpreterArena(&tmpAlloc);
  1218. allocation = (Js::Var*)tmpAlloc->Alloc(varSizeInBytes);
  1219. }
  1220. else
  1221. {
  1222. PROBE_STACK_PARTIAL_INITIALIZED_BAILOUT_FRAME(functionScriptContext, Js::Constants::MinStackInterpreter + varSizeInBytes, returnAddress);
  1223. allocation = (Js::Var*)_alloca(varSizeInBytes);
  1224. }
  1225. Js::Var loopHeaderArray = nullptr;
  1226. if (executeFunction->GetHasAllocatedLoopHeaders())
  1227. {
  1228. // Loop header array is recycler allocated, so we push it on the stack
  1229. // When we scan the stack, we'll recognize it as a recycler allocated
  1230. // object, and mark it's contents and keep the individual loop header
  1231. // wrappers alive
  1232. loopHeaderArray = executeFunction->GetLoopHeaderArrayPtr();
  1233. }
  1234. // Set stack address for STEP_OUT/recursion detection for new frame.
  1235. // This frame is originally jitted frame for which we create a new interpreter frame on top of it on stack,
  1236. // set the stack address to some stack location that belong to the original jitted frame.
  1237. DWORD_PTR frameStackAddr = reinterpret_cast<DWORD_PTR>(layout->GetArgv());
  1238. // Initialize the interpreter stack frame (constants) but not the param, the bailout record will restore the value
  1239. #if DBG
  1240. Js::RecyclableObject * invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  1241. memset(invalidStackVar, 0xFE, sizeof(Js::RecyclableObject));
  1242. newInstance = setup.InitializeAllocation(allocation, false, false, loopHeaderArray, frameStackAddr, invalidStackVar);
  1243. #else
  1244. newInstance = setup.InitializeAllocation(allocation, false, false, loopHeaderArray, frameStackAddr);
  1245. #endif
  1246. newInstance->m_reader.Create(executeFunction);
  1247. }
  1248. newInstance->ehBailoutData = bailOutRecord->ehBailoutData;
  1249. newInstance->OrFlags(Js::InterpreterStackFrameFlags_FromBailOut);
  1250. ThreadContext *threadContext = newInstance->GetScriptContext()->GetThreadContext();
  1251. // If this is a bailout on implicit calls, then it must have occurred at the current statement.
  1252. // Otherwise, assume that the bits are stale, so clear them before entering the interpreter.
  1253. if (!BailOutInfo::IsBailOutOnImplicitCalls(bailOutKind))
  1254. {
  1255. threadContext->ClearImplicitCallFlags();
  1256. }
  1257. Js::RegSlot varCount = function->GetFunctionBody()->GetVarCount();
  1258. if (varCount)
  1259. {
  1260. Js::RegSlot constantCount = function->GetFunctionBody()->GetConstantCount();
  1261. memset(newInstance->m_localSlots + constantCount, 0, varCount * sizeof(Js::Var));
  1262. }
  1263. Js::RegSlot localFrameDisplayReg = executeFunction->GetLocalFrameDisplayReg();
  1264. Js::RegSlot localClosureReg = executeFunction->GetLocalClosureReg();
  1265. if (!isInlinee)
  1266. {
  1267. // If byte code was generated to do stack closures, restore closure pointers before the normal RestoreValues.
  1268. // If code was jitted for stack closures, we have to restore the pointers from known stack locations.
  1269. // (RestoreValues won't do it.) If stack closures were disabled for this function before we jitted,
  1270. // then the values on the stack are garbage, but if we need them then RestoreValues will overwrite with
  1271. // the correct values.
  1272. if (localFrameDisplayReg != Js::Constants::NoRegister)
  1273. {
  1274. Js::FrameDisplay *localFrameDisplay;
  1275. uintptr_t frameDisplayIndex = (uintptr_t)(
  1276. #if _M_IX86 || _M_AMD64
  1277. executeFunction->GetInParamsCount() == 0 ?
  1278. Js::JavascriptFunctionArgIndex_StackFrameDisplayNoArg :
  1279. #endif
  1280. Js::JavascriptFunctionArgIndex_StackFrameDisplay) - 2;
  1281. localFrameDisplay = (Js::FrameDisplay*)layout->GetArgv()[frameDisplayIndex];
  1282. newInstance->SetLocalFrameDisplay(localFrameDisplay);
  1283. }
  1284. if (localClosureReg != Js::Constants::NoRegister)
  1285. {
  1286. Js::Var localClosure;
  1287. uintptr_t scopeSlotsIndex = (uintptr_t)(
  1288. #if _M_IX86 || _M_AMD64
  1289. executeFunction->GetInParamsCount() == 0 ?
  1290. Js::JavascriptFunctionArgIndex_StackScopeSlotsNoArg :
  1291. #endif
  1292. Js::JavascriptFunctionArgIndex_StackScopeSlots) - 2;
  1293. localClosure = layout->GetArgv()[scopeSlotsIndex];
  1294. newInstance->SetLocalClosure(localClosure);
  1295. }
  1296. }
  1297. // Restore bailout values
  1298. bailOutRecord->RestoreValues(bailOutKind, layout, newInstance, functionScriptContext, false, registerSaves, bailOutReturnValue, pArgumentsObject, branchValue, returnAddress, useStartCall, argoutRestoreAddress);
  1299. // For functions that don't get the scope slot and frame display pointers back from the known stack locations
  1300. // (see above), get them back from the designated registers.
  1301. // In either case, clear the values from those registers, because the interpreter should not be able to access
  1302. // those values through the registers (only through its private fields).
  1303. if (localFrameDisplayReg != Js::Constants::NoRegister)
  1304. {
  1305. Js::FrameDisplay *frameDisplay = (Js::FrameDisplay*)newInstance->GetNonVarReg(localFrameDisplayReg);
  1306. if (frameDisplay)
  1307. {
  1308. newInstance->SetLocalFrameDisplay(frameDisplay);
  1309. newInstance->SetNonVarReg(localFrameDisplayReg, nullptr);
  1310. }
  1311. }
  1312. if (localClosureReg != Js::Constants::NoRegister)
  1313. {
  1314. Js::Var closure = newInstance->GetNonVarReg(localClosureReg);
  1315. if (closure)
  1316. {
  1317. newInstance->SetLocalClosure(closure);
  1318. newInstance->SetNonVarReg(localClosureReg, nullptr);
  1319. }
  1320. }
  1321. uint32 innerScopeCount = executeFunction->GetInnerScopeCount();
  1322. for (uint32 i = 0; i < innerScopeCount; i++)
  1323. {
  1324. Js::RegSlot reg = executeFunction->FirstInnerScopeReg() + i;
  1325. newInstance->SetInnerScopeFromIndex(i, newInstance->GetNonVarReg(reg));
  1326. newInstance->SetNonVarReg(reg, nullptr);
  1327. }
  1328. newInstance->SetClosureInitDone(bailOutOffset != 0 || !(bailOutKind & IR::BailOutForDebuggerBits));
  1329. // RestoreValues may call EnsureArguments and cause functions to be boxed.
  1330. // Since the interpreter frame that hasn't started yet, StackScriptFunction::Box would not have replaced the function object
  1331. // in the restoring interpreter frame. Let's make sure the current interpreter frame has the unboxed version.
  1332. // Note: Only use the unboxed version if we have replaced the function argument on the stack via boxing
  1333. // so that the interpreter frame we are bailing out to matches the one in the function argument list
  1334. // (which is used by the stack walker to match up stack frame and the interpreter frame).
  1335. // Some function are boxed but we continue to use the stack version to call the function - those that only live in register
  1336. // and are not captured in frame displays.
  1337. // Those uses are fine, but that means the function argument list will have the stack function object that is passed it and
  1338. // not be replaced with a just boxed one.
  1339. Js::ScriptFunction * currentFunctionObject = *functionRef;
  1340. if (function != currentFunctionObject)
  1341. {
  1342. Assert(currentFunctionObject == Js::StackScriptFunction::GetCurrentFunctionObject(function));
  1343. newInstance->SetExecutingStackFunction(currentFunctionObject);
  1344. }
  1345. UpdatePolymorphicFieldAccess(function, bailOutRecord);
  1346. BAILOUT_FLUSH(executeFunction);
  1347. executeFunction->BeginExecution();
  1348. // Restart at the bailout byte code offset.
  1349. newInstance->m_reader.SetCurrentOffset(bailOutOffset);
  1350. Js::Var aReturn = nullptr;
  1351. {
  1352. // Following _AddressOfReturnAddress <= real address of "returnAddress". Suffices for RemoteStackWalker to test partially initialized interpreter frame.
  1353. Js::InterpreterStackFrame::PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, _AddressOfReturnAddress());
  1354. aReturn = isInDebugMode ? newInstance->DebugProcess() : newInstance->Process();
  1355. // Note: in debug mode we always have to bailout to debug thunk,
  1356. // as normal interpreter thunk expects byte code compiled w/o debugging.
  1357. }
  1358. executeFunction->EndExecution();
  1359. if (executeFunction->HasDynamicProfileInfo())
  1360. {
  1361. Js::DynamicProfileInfo *dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1362. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  1363. }
  1364. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"BailOut: Return Value: 0x%p", aReturn);
  1365. if (bailOutRecord->globalBailOutRecordTable->isInlinedConstructor)
  1366. {
  1367. AssertMsg(!executeFunction->IsGenerator(), "Generator functions are not expected to be inlined. If this changes then need to use the real user args here from the generator object");
  1368. Assert(args.Info.Count != 0);
  1369. aReturn = Js::JavascriptFunction::FinishConstructor(aReturn, args.Values[0], function);
  1370. Js::Var oldValue = aReturn;
  1371. aReturn = Js::JavascriptOperators::BoxStackInstance(oldValue, functionScriptContext, /* allowStackFunction */ true);
  1372. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1373. if (oldValue != aReturn)
  1374. {
  1375. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L" (Boxed: 0x%p)", aReturn);
  1376. }
  1377. #endif
  1378. }
  1379. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, L"\n");
  1380. return aReturn;
  1381. }
  1382. // Note on rejit states
  1383. //
  1384. // To avoid always incurring the cost of collecting runtime stats (function calls count and valid bailOutKind),
  1385. // the initial codegen'd version of a function does not collect them. After a second bailout we rejit the function
  1386. // with runtime stats collection. On subsequent bailouts we can evaluate our heuristics and decide whether to rejit.
  1387. //
  1388. // Function bodies always use the least optimized version of the code as default. At the same time, there can be
  1389. // function objects with some older, more optimized, version of the code active. When a bailout occurs out of such
  1390. // code we avoid a rejit by checking if the offending optimization has been disabled in the default code and if so
  1391. // we "rethunk" the bailing out function rather that incurring a rejit.
  1392. void BailOutRecord::ScheduleFunctionCodeGen(Js::ScriptFunction * function, Js::ScriptFunction * innerMostInlinee,
  1393. BailOutRecord const * bailOutRecord, IR::BailOutKind bailOutKind, void * returnAddress)
  1394. {
  1395. if (bailOutKind == IR::BailOnSimpleJitToFullJitLoopBody ||
  1396. bailOutKind == IR::BailOutForGeneratorYield ||
  1397. bailOutKind == IR::LazyBailOut)
  1398. {
  1399. return;
  1400. }
  1401. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1402. if (PHASE_OFF(Js::ReJITPhase, executeFunction))
  1403. {
  1404. return;
  1405. }
  1406. Js::AutoPushReturnAddressForStackWalker saveReturnAddress(executeFunction->GetScriptContext(), returnAddress);
  1407. BailOutRecord * bailOutRecordNotConst = (BailOutRecord *)(void *)bailOutRecord;
  1408. bailOutRecordNotConst->bailOutCount++;
  1409. Js::FunctionEntryPointInfo *entryPointInfo = function->GetFunctionEntryPointInfo();
  1410. uint8 callsCount = entryPointInfo->callsCount;
  1411. RejitReason rejitReason = RejitReason::None;
  1412. bool reThunk = false;
  1413. callsCount = callsCount <= Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() ? 0 : callsCount - Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() ;
  1414. if (bailOutKind == IR::BailOutOnNoProfile && executeFunction->IncrementBailOnMisingProfileCount() > CONFIG_FLAG(BailOnNoProfileLimit))
  1415. {
  1416. // A rejit here should improve code quality, so lets avoid too many unnecessary bailouts.
  1417. executeFunction->ResetBailOnMisingProfileCount();
  1418. bailOutRecordNotConst->bailOutCount = 0;
  1419. callsCount = 0;
  1420. }
  1421. else if (bailOutRecordNotConst->bailOutCount > CONFIG_FLAG(RejitMaxBailOutCount))
  1422. {
  1423. switch(bailOutKind)
  1424. {
  1425. case IR::BailOutOnPolymorphicInlineFunction:
  1426. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  1427. case IR::BailOutFailedInlineTypeCheck:
  1428. case IR::BailOutOnInlineFunction:
  1429. case IR::BailOutFailedTypeCheck:
  1430. case IR::BailOutFailedFixedFieldTypeCheck:
  1431. case IR::BailOutFailedCtorGuardCheck:
  1432. case IR::BailOutFailedFixedFieldCheck:
  1433. case IR::BailOutFailedEquivalentTypeCheck:
  1434. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  1435. {
  1436. // If we consistently see RejitMaxBailOutCount bailouts for these kinds, then likely we have stale profile data and it is beneficial to rejit.
  1437. // Note you need to include only bailout kinds which don't disable the entire optimizations.
  1438. REJIT_KIND_TESTTRACE(bailOutKind, L"Force rejit as RejitMaxBailoOutCount reached for a bailout record: function: %s, bailOutKindName: (%S), bailOutCount: %d, callCount: %d RejitMaxBailoutCount: %d\r\n",
  1439. function->GetFunctionBody()->GetDisplayName(), ::GetBailOutKindName(bailOutKind), bailOutRecordNotConst->bailOutCount, callsCount, CONFIG_FLAG(RejitMaxBailOutCount));
  1440. bailOutRecordNotConst->bailOutCount = 0;
  1441. callsCount = 0;
  1442. break;
  1443. }
  1444. default: break;
  1445. }
  1446. }
  1447. entryPointInfo->callsCount = callsCount;
  1448. Assert(bailOutKind != IR::BailOutInvalid);
  1449. if ((executeFunction->HasDynamicProfileInfo() && callsCount == 0) ||
  1450. PHASE_FORCE(Js::ReJITPhase, executeFunction))
  1451. {
  1452. Js::DynamicProfileInfo * profileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1453. if ((bailOutKind & (IR::BailOutOnResultConditions | IR::BailOutOnDivSrcConditions)) || bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOnIntMin || bailOutKind == IR::BailOnDivResultNotInt)
  1454. {
  1455. // Note WRT BailOnIntMin: it wouldn't make sense to re-jit without changing anything here, as interpreter will not change the (int) type,
  1456. // so the options are: (1) rejit with disabling int type spec, (2) don't rejit, always bailout.
  1457. // It seems to be better to rejit.
  1458. if (bailOutKind & IR::BailOutOnMulOverflow)
  1459. {
  1460. if (profileInfo->IsAggressiveMulIntTypeSpecDisabled(false))
  1461. {
  1462. reThunk = true;
  1463. }
  1464. else
  1465. {
  1466. profileInfo->DisableAggressiveMulIntTypeSpec(false);
  1467. rejitReason = RejitReason::AggressiveMulIntTypeSpecDisabled;
  1468. }
  1469. }
  1470. else if ((bailOutKind & (IR::BailOutOnDivByZero | IR::BailOutOnDivOfMinInt)) || bailOutKind == IR::BailOnDivResultNotInt)
  1471. {
  1472. if (profileInfo->IsDivIntTypeSpecDisabled(false))
  1473. {
  1474. reThunk = true;
  1475. }
  1476. else
  1477. {
  1478. profileInfo->DisableDivIntTypeSpec(false);
  1479. rejitReason = RejitReason::DivIntTypeSpecDisabled;
  1480. }
  1481. }
  1482. else
  1483. {
  1484. if (profileInfo->IsAggressiveIntTypeSpecDisabled(false))
  1485. {
  1486. reThunk = true;
  1487. }
  1488. else
  1489. {
  1490. profileInfo->DisableAggressiveIntTypeSpec(false);
  1491. rejitReason = RejitReason::AggressiveIntTypeSpecDisabled;
  1492. }
  1493. }
  1494. }
  1495. else if (bailOutKind & IR::BailOutForDebuggerBits)
  1496. {
  1497. // Do not rejit, do not rethunk, just ignore the bailout.
  1498. }
  1499. else switch(bailOutKind)
  1500. {
  1501. case IR::BailOutOnNotPrimitive:
  1502. if (profileInfo->IsLossyIntTypeSpecDisabled())
  1503. {
  1504. reThunk = true;
  1505. }
  1506. else
  1507. {
  1508. profileInfo->DisableLossyIntTypeSpec();
  1509. rejitReason = RejitReason::LossyIntTypeSpecDisabled;
  1510. }
  1511. break;
  1512. case IR::BailOutOnMemOpError:
  1513. if (profileInfo->IsMemOpDisabled())
  1514. {
  1515. reThunk = true;
  1516. }
  1517. else
  1518. {
  1519. profileInfo->DisableMemOp();
  1520. rejitReason = RejitReason::MemOpDisabled;
  1521. }
  1522. break;
  1523. case IR::BailOutPrimitiveButString:
  1524. case IR::BailOutNumberOnly:
  1525. if (profileInfo->IsFloatTypeSpecDisabled())
  1526. {
  1527. reThunk = true;
  1528. }
  1529. else
  1530. {
  1531. profileInfo->DisableFloatTypeSpec();
  1532. rejitReason = RejitReason::FloatTypeSpecDisabled;
  1533. }
  1534. break;
  1535. case IR::BailOutOnImplicitCalls:
  1536. case IR::BailOutOnImplicitCallsPreOp:
  1537. case IR::BailOutExpectingObject:
  1538. // Check if the implicit call flags in the profile have changed since we last JITed this
  1539. // function body. If so, and they indicate an implicit call of some sort occurred
  1540. // then we need to reJIT.
  1541. if (executeFunction->GetSavedImplicitCallsFlags() == Js::ImplicitCall_None ||
  1542. executeFunction->GetSavedImplicitCallsFlags() == Js::ImplicitCall_HasNoInfo)
  1543. {
  1544. profileInfo->RecordImplicitCallFlags(executeFunction->GetScriptContext()->GetThreadContext()->GetImplicitCallFlags());
  1545. rejitReason = RejitReason::ImplicitCallFlagsChanged;
  1546. }
  1547. else
  1548. {
  1549. reThunk = true;
  1550. }
  1551. break;
  1552. case IR::BailOnModByPowerOf2:
  1553. rejitReason = RejitReason::ModByPowerOf2;
  1554. break;
  1555. case IR::BailOutOnNotArray:
  1556. if(profileInfo->IsArrayCheckHoistDisabled(false))
  1557. {
  1558. reThunk = true;
  1559. }
  1560. else
  1561. {
  1562. profileInfo->DisableArrayCheckHoist(false);
  1563. rejitReason = RejitReason::ArrayCheckHoistDisabled;
  1564. }
  1565. break;
  1566. case IR::BailOutOnNotNativeArray:
  1567. rejitReason = RejitReason::ExpectingNativeArray;
  1568. break;
  1569. case IR::BailOutConvertedNativeArray:
  1570. rejitReason = RejitReason::ConvertedNativeArray;
  1571. break;
  1572. case IR::BailOutConventionalTypedArrayAccessOnly:
  1573. if(profileInfo->IsTypedArrayTypeSpecDisabled(false))
  1574. {
  1575. reThunk = true;
  1576. }
  1577. else
  1578. {
  1579. profileInfo->DisableTypedArrayTypeSpec(false);
  1580. rejitReason = RejitReason::TypedArrayTypeSpecDisabled;
  1581. }
  1582. break;
  1583. case IR::BailOutConventionalNativeArrayAccessOnly:
  1584. rejitReason = RejitReason::ExpectingConventionalNativeArrayAccess;
  1585. break;
  1586. case IR::BailOutOnMissingValue:
  1587. if(profileInfo->IsArrayMissingValueCheckHoistDisabled(false))
  1588. {
  1589. reThunk = true;
  1590. }
  1591. else
  1592. {
  1593. profileInfo->DisableArrayMissingValueCheckHoist(false);
  1594. rejitReason = RejitReason::ArrayMissingValueCheckHoistDisabled;
  1595. }
  1596. break;
  1597. case IR::BailOutOnArrayAccessHelperCall:
  1598. // This is a pre-op bailout, so the interpreter will update the profile data for this byte-code instruction to
  1599. // prevent excessive bailouts here in the future
  1600. rejitReason = RejitReason::ArrayAccessNeededHelperCall;
  1601. break;
  1602. case IR::BailOutOnInvalidatedArrayHeadSegment:
  1603. if(profileInfo->IsJsArraySegmentHoistDisabled(false))
  1604. {
  1605. reThunk = true;
  1606. }
  1607. else
  1608. {
  1609. profileInfo->DisableJsArraySegmentHoist(false);
  1610. rejitReason = RejitReason::JsArraySegmentHoistDisabled;
  1611. }
  1612. break;
  1613. case IR::BailOutOnIrregularLength:
  1614. if(profileInfo->IsLdLenIntSpecDisabled())
  1615. {
  1616. reThunk = true;
  1617. }
  1618. else
  1619. {
  1620. profileInfo->DisableLdLenIntSpec();
  1621. rejitReason = RejitReason::LdLenIntSpecDisabled;
  1622. }
  1623. break;
  1624. case IR::BailOutOnFailedHoistedBoundCheck:
  1625. if(profileInfo->IsBoundCheckHoistDisabled(false))
  1626. {
  1627. reThunk = true;
  1628. }
  1629. else
  1630. {
  1631. profileInfo->DisableBoundCheckHoist(false);
  1632. rejitReason = RejitReason::BoundCheckHoistDisabled;
  1633. }
  1634. break;
  1635. case IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck:
  1636. if(profileInfo->IsLoopCountBasedBoundCheckHoistDisabled(false))
  1637. {
  1638. reThunk = true;
  1639. }
  1640. else
  1641. {
  1642. profileInfo->DisableLoopCountBasedBoundCheckHoist(false);
  1643. rejitReason = RejitReason::LoopCountBasedBoundCheckHoistDisabled;
  1644. }
  1645. break;
  1646. case IR::BailOutExpectingInteger:
  1647. rejitReason = RejitReason::DisableSwitchOptExpectingInteger;
  1648. break;
  1649. case IR::BailOutExpectingString:
  1650. rejitReason = RejitReason::DisableSwitchOptExpectingString;
  1651. break;
  1652. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  1653. rejitReason = RejitReason::FailedPolymorphicInlineeTypeCheck;
  1654. break;
  1655. case IR::BailOutOnPolymorphicInlineFunction:
  1656. case IR::BailOutFailedInlineTypeCheck:
  1657. case IR::BailOutOnInlineFunction:
  1658. // Check if the inliner state has changed since we last JITed this function body. If so
  1659. // then we need to reJIT.
  1660. if (innerMostInlinee)
  1661. {
  1662. // There is no way now to check if the inlinee version has changed. Just rejit.
  1663. // This should be changed to getting the inliner version corresponding to inlinee.
  1664. rejitReason = RejitReason::InlineeChanged;
  1665. }
  1666. else
  1667. {
  1668. if (executeFunction->GetSavedInlinerVersion() == profileInfo->GetInlinerVersion())
  1669. {
  1670. reThunk = true;
  1671. }
  1672. else
  1673. {
  1674. rejitReason = RejitReason::InlineeChanged;
  1675. }
  1676. }
  1677. break;
  1678. case IR::BailOutOnNoProfile:
  1679. if (profileInfo->IsNoProfileBailoutsDisabled())
  1680. {
  1681. reThunk = true;
  1682. }
  1683. else if (executeFunction->IncrementBailOnMisingProfileRejitCount() > (uint)CONFIG_FLAG(BailOnNoProfileRejitLimit))
  1684. {
  1685. profileInfo->DisableNoProfileBailouts();
  1686. rejitReason = RejitReason::NoProfile;
  1687. }
  1688. else
  1689. {
  1690. executeFunction->ResetBailOnMisingProfileCount();
  1691. rejitReason = RejitReason::NoProfile;
  1692. }
  1693. break;
  1694. case IR::BailOutCheckThis:
  1695. // Presumably we've started passing a different "this" pointer to callees.
  1696. if (profileInfo->IsCheckThisDisabled())
  1697. {
  1698. reThunk = true;
  1699. }
  1700. else
  1701. {
  1702. profileInfo->DisableCheckThis();
  1703. rejitReason = RejitReason::CheckThisDisabled;
  1704. }
  1705. break;
  1706. case IR::BailOutOnTaggedValue:
  1707. rejitReason = RejitReason::FailedTagCheck;
  1708. break;
  1709. case IR::BailOutFailedTypeCheck:
  1710. case IR::BailOutFailedFixedFieldTypeCheck:
  1711. {
  1712. // An inline cache must have gone from monomorphic to polymorphic.
  1713. // This is already noted in the profile data, so optimization of the given ld/st will
  1714. // be inhibited on re-jit.
  1715. // Consider disabling the optimization across the function after n failed type checks.
  1716. if (innerMostInlinee)
  1717. {
  1718. rejitReason = bailOutKind == IR::BailOutFailedTypeCheck ? RejitReason::FailedTypeCheck : RejitReason::FailedFixedFieldTypeCheck;
  1719. }
  1720. else
  1721. {
  1722. uint32 state;
  1723. state = profileInfo->GetPolymorphicCacheState();
  1724. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1725. if (PHASE_TRACE(Js::ObjTypeSpecPhase, executeFunction))
  1726. {
  1727. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1728. Output::Print(
  1729. L"Objtypespec (%s): States on bailout: Saved cache: %d, Live cache: %d\n",
  1730. executeFunction->GetDebugNumberSet(debugStringBuffer), executeFunction->GetSavedPolymorphicCacheState(), state);
  1731. Output::Flush();
  1732. }
  1733. #endif
  1734. if (state <= executeFunction->GetSavedPolymorphicCacheState())
  1735. {
  1736. reThunk = true;
  1737. }
  1738. else
  1739. {
  1740. rejitReason = bailOutKind == IR::BailOutFailedTypeCheck ?
  1741. RejitReason::FailedTypeCheck : RejitReason::FailedFixedFieldTypeCheck;
  1742. }
  1743. }
  1744. break;
  1745. }
  1746. case IR::BailOutFailedEquivalentTypeCheck:
  1747. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  1748. if (profileInfo->IsEquivalentObjTypeSpecDisabled())
  1749. {
  1750. reThunk = true;
  1751. }
  1752. else
  1753. {
  1754. rejitReason = bailOutKind == IR::BailOutFailedEquivalentTypeCheck ?
  1755. RejitReason::FailedEquivalentTypeCheck : RejitReason::FailedEquivalentFixedFieldTypeCheck;
  1756. }
  1757. break;
  1758. case IR::BailOutFailedFixedFieldCheck:
  1759. rejitReason = RejitReason::FailedFixedFieldCheck;
  1760. break;
  1761. case IR::BailOutFailedCtorGuardCheck:
  1762. // (ObjTypeSpec): Consider scheduling re-JIT right after the first bailout. We will never successfully execute the
  1763. // function from which we just bailed out, unless we take a different code path through it.
  1764. // A constructor cache guard may be invalidated for one of two reasons:
  1765. // a) the constructor's prototype property has changed, or
  1766. // b) one of the properties protected by the guard (this constructor cache served as) has changed in some way (e.g. became read-only).
  1767. // In the former case, the cache itself will be marked as polymorphic and on re-JIT we won't do the optimization.
  1768. // In the latter case, the inline cache for the offending property will be cleared and on re-JIT the guard will not be enlisted
  1769. // to protect that property operation.
  1770. rejitReason = RejitReason::CtorGuardInvalidated;
  1771. break;
  1772. case IR::BailOutOnFloor:
  1773. {
  1774. if (profileInfo->IsFloorInliningDisabled())
  1775. {
  1776. reThunk = true;
  1777. }
  1778. else
  1779. {
  1780. profileInfo->DisableFloorInlining();
  1781. rejitReason = RejitReason::FloorInliningDisabled;
  1782. }
  1783. break;
  1784. }
  1785. }
  1786. Assert(!(rejitReason != RejitReason::None && reThunk));
  1787. }
  1788. if(PHASE_FORCE(Js::ReJITPhase, executeFunction) && rejitReason == RejitReason::None)
  1789. {
  1790. rejitReason = RejitReason::Forced;
  1791. }
  1792. REJIT_KIND_TESTTRACE(bailOutKind, L"Bailout from function: function: %s, bailOutKindName: (%S), bailOutCount: %d, callCount: %d, reJitReason: %S, reThunk: %s\r\n",
  1793. function->GetFunctionBody()->GetDisplayName(), ::GetBailOutKindName(bailOutKind), bailOutRecord->bailOutCount, callsCount,
  1794. RejitReasonNames[rejitReason], reThunk ? trueString : falseString);
  1795. #ifdef REJIT_STATS
  1796. if(PHASE_STATS(Js::ReJITPhase, executeFunction))
  1797. {
  1798. executeFunction->GetScriptContext()->LogBailout(executeFunction, bailOutKind);
  1799. }
  1800. #endif
  1801. if (reThunk && executeFunction->DontRethunkAfterBailout())
  1802. {
  1803. // This function is marked for rethunking, but the last ReJIT we've done was for a JIT loop body
  1804. // So the latest rejitted version of this function may not have the right optimization disabled.
  1805. // Rejit just to be safe.
  1806. reThunk = false;
  1807. rejitReason = RejitReason::AfterLoopBodyRejit;
  1808. }
  1809. if (reThunk)
  1810. {
  1811. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = executeFunction->GetDefaultFunctionEntryPointInfo();
  1812. function->UpdateThunkEntryPoint(defaultEntryPointInfo, executeFunction->GetDirectEntryPoint(defaultEntryPointInfo));
  1813. }
  1814. else if (rejitReason != RejitReason::None)
  1815. {
  1816. #ifdef REJIT_STATS
  1817. if(PHASE_STATS(Js::ReJITPhase, executeFunction))
  1818. {
  1819. executeFunction->GetScriptContext()->LogRejit(executeFunction, rejitReason);
  1820. }
  1821. #endif
  1822. executeFunction->ClearDontRethunkAfterBailout();
  1823. GenerateFunction(executeFunction->GetScriptContext()->GetNativeCodeGenerator(), executeFunction, function);
  1824. if(executeFunction->GetExecutionMode() != ExecutionMode::FullJit)
  1825. {
  1826. // With expiry, it's possible that the execution mode is currently interpreter or simple JIT. Transition to full JIT
  1827. // after successfully scheduling the rejit work item (in case of OOM).
  1828. executeFunction->TraceExecutionMode("Rejit (before)");
  1829. executeFunction->TransitionToFullJitExecutionMode();
  1830. executeFunction->TraceExecutionMode("Rejit");
  1831. }
  1832. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1833. if(PHASE_TRACE(Js::ReJITPhase, executeFunction))
  1834. {
  1835. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1836. Output::Print(
  1837. L"Rejit: function: %s (%s), bailOutCount: %hu",
  1838. executeFunction->GetDisplayName(),
  1839. executeFunction->GetDebugNumberSet(debugStringBuffer),
  1840. bailOutRecord->bailOutCount);
  1841. Output::Print(L" callCount: %u", callsCount);
  1842. Output::Print(L" reason: %S", RejitReasonNames[rejitReason]);
  1843. if(bailOutKind != IR::BailOutInvalid)
  1844. {
  1845. Output::Print(L" (%S)", ::GetBailOutKindName(bailOutKind));
  1846. }
  1847. Output::Print(L"\n");
  1848. Output::Flush();
  1849. }
  1850. #endif
  1851. }
  1852. }
  1853. // To avoid always incurring the cost of collecting runtime stats (valid bailOutKind),
  1854. // the initial codegen'd version of a loop body does not collect them. After a second bailout we rejit the body
  1855. // with runtime stats collection. On subsequent bailouts we can evaluate our heuristics.
  1856. void BailOutRecord::ScheduleLoopBodyCodeGen(Js::ScriptFunction * function, Js::ScriptFunction * innerMostInlinee, BailOutRecord const * bailOutRecord, IR::BailOutKind bailOutKind)
  1857. {
  1858. Assert(bailOutKind != IR::LazyBailOut);
  1859. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1860. if (PHASE_OFF(Js::ReJITPhase, executeFunction))
  1861. {
  1862. return;
  1863. }
  1864. Js::LoopHeader * loopHeader = nullptr;
  1865. Js::InterpreterStackFrame * interpreterFrame = executeFunction->GetScriptContext()->GetThreadContext()->GetLeafInterpreterFrame();
  1866. loopHeader = executeFunction->GetLoopHeader(interpreterFrame->GetCurrentLoopNum());
  1867. Assert(loopHeader != nullptr);
  1868. BailOutRecord * bailOutRecordNotConst = (BailOutRecord *)(void *)bailOutRecord;
  1869. RejitReason rejitReason = RejitReason::None;
  1870. Assert(bailOutKind != IR::BailOutInvalid);
  1871. if (bailOutRecordNotConst->bailOutCount < 1)
  1872. {
  1873. // Ignore the first bailout
  1874. bailOutRecordNotConst->bailOutCount++;
  1875. }
  1876. else if (executeFunction->HasDynamicProfileInfo())
  1877. {
  1878. Js::DynamicProfileInfo * profileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1879. if ((bailOutKind & (IR::BailOutOnResultConditions | IR::BailOutOnDivSrcConditions)) || bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOnIntMin)
  1880. {
  1881. if (bailOutKind & IR::BailOutOnMulOverflow)
  1882. {
  1883. profileInfo->DisableAggressiveMulIntTypeSpec(true);
  1884. rejitReason = RejitReason::AggressiveMulIntTypeSpecDisabled;
  1885. }
  1886. else if ((bailOutKind & (IR::BailOutOnDivByZero | IR::BailOutOnDivOfMinInt)) || bailOutKind == IR::BailOnDivResultNotInt)
  1887. {
  1888. profileInfo->DisableDivIntTypeSpec(true);
  1889. rejitReason = RejitReason::DivIntTypeSpecDisabled;
  1890. }
  1891. else
  1892. {
  1893. profileInfo->DisableAggressiveIntTypeSpec(true);
  1894. rejitReason = RejitReason::AggressiveIntTypeSpecDisabled;
  1895. }
  1896. executeFunction->SetDontRethunkAfterBailout();
  1897. }
  1898. else switch(bailOutKind)
  1899. {
  1900. case IR::BailOutOnNotPrimitive:
  1901. profileInfo->DisableLossyIntTypeSpec();
  1902. executeFunction->SetDontRethunkAfterBailout();
  1903. rejitReason = RejitReason::LossyIntTypeSpecDisabled;
  1904. break;
  1905. case IR::BailOutOnMemOpError:
  1906. profileInfo->DisableMemOp();
  1907. executeFunction->SetDontRethunkAfterBailout();
  1908. rejitReason = RejitReason::MemOpDisabled;
  1909. break;
  1910. case IR::BailOutPrimitiveButString:
  1911. case IR::BailOutNumberOnly:
  1912. profileInfo->DisableFloatTypeSpec();
  1913. executeFunction->SetDontRethunkAfterBailout();
  1914. rejitReason = RejitReason::FloatTypeSpecDisabled;
  1915. break;
  1916. case IR::BailOutOnImplicitCalls:
  1917. case IR::BailOutOnImplicitCallsPreOp:
  1918. case IR::BailOutExpectingObject:
  1919. rejitReason = RejitReason::ImplicitCallFlagsChanged;
  1920. break;
  1921. case IR::BailOutExpectingInteger:
  1922. rejitReason = RejitReason::DisableSwitchOptExpectingInteger;
  1923. break;
  1924. case IR::BailOutExpectingString:
  1925. rejitReason = RejitReason::DisableSwitchOptExpectingString;
  1926. break;
  1927. case IR::BailOnModByPowerOf2:
  1928. rejitReason = RejitReason::ModByPowerOf2;
  1929. break;
  1930. case IR::BailOutOnNotArray:
  1931. profileInfo->DisableArrayCheckHoist(true);
  1932. executeFunction->SetDontRethunkAfterBailout();
  1933. rejitReason = RejitReason::ArrayCheckHoistDisabled;
  1934. break;
  1935. case IR::BailOutOnNotNativeArray:
  1936. rejitReason = RejitReason::ExpectingNativeArray;
  1937. break;
  1938. case IR::BailOutConvertedNativeArray:
  1939. rejitReason = RejitReason::ConvertedNativeArray;
  1940. break;
  1941. case IR::BailOutConventionalTypedArrayAccessOnly:
  1942. profileInfo->DisableTypedArrayTypeSpec(true);
  1943. executeFunction->SetDontRethunkAfterBailout();
  1944. rejitReason = RejitReason::TypedArrayTypeSpecDisabled;
  1945. break;
  1946. case IR::BailOutConventionalNativeArrayAccessOnly:
  1947. rejitReason = RejitReason::ExpectingConventionalNativeArrayAccess;
  1948. break;
  1949. case IR::BailOutOnMissingValue:
  1950. profileInfo->DisableArrayMissingValueCheckHoist(true);
  1951. rejitReason = RejitReason::ArrayMissingValueCheckHoistDisabled;
  1952. break;
  1953. case IR::BailOutOnArrayAccessHelperCall:
  1954. // This is a pre-op bailout, so the interpreter will update the profile data for this byte-code instruction to
  1955. // prevent excessive bailouts here in the future
  1956. rejitReason = RejitReason::ArrayAccessNeededHelperCall;
  1957. break;
  1958. case IR::BailOutOnInvalidatedArrayHeadSegment:
  1959. profileInfo->DisableJsArraySegmentHoist(true);
  1960. executeFunction->SetDontRethunkAfterBailout();
  1961. rejitReason = RejitReason::JsArraySegmentHoistDisabled;
  1962. break;
  1963. case IR::BailOutOnIrregularLength:
  1964. profileInfo->DisableLdLenIntSpec();
  1965. executeFunction->SetDontRethunkAfterBailout();
  1966. rejitReason = RejitReason::LdLenIntSpecDisabled;
  1967. break;
  1968. case IR::BailOutOnFailedHoistedBoundCheck:
  1969. profileInfo->DisableBoundCheckHoist(true);
  1970. executeFunction->SetDontRethunkAfterBailout();
  1971. rejitReason = RejitReason::BoundCheckHoistDisabled;
  1972. break;
  1973. case IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck:
  1974. profileInfo->DisableLoopCountBasedBoundCheckHoist(true);
  1975. executeFunction->SetDontRethunkAfterBailout();
  1976. rejitReason = RejitReason::LoopCountBasedBoundCheckHoistDisabled;
  1977. break;
  1978. case IR::BailOutOnInlineFunction:
  1979. case IR::BailOutOnPolymorphicInlineFunction:
  1980. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  1981. rejitReason = RejitReason::InlineeChanged;
  1982. break;
  1983. case IR::BailOutOnNoProfile:
  1984. rejitReason = RejitReason::NoProfile;
  1985. executeFunction->ResetBailOnMisingProfileCount();
  1986. break;
  1987. case IR::BailOutCheckThis:
  1988. profileInfo->DisableCheckThis();
  1989. executeFunction->SetDontRethunkAfterBailout();
  1990. rejitReason = RejitReason::CheckThisDisabled;
  1991. break;
  1992. case IR::BailOutFailedTypeCheck:
  1993. // An inline cache must have gone from monomorphic to polymorphic.
  1994. // This is already noted in the profile data, so optimization of the given ld/st will
  1995. // be inhibited on re-jit.
  1996. // Consider disabling the optimization across the function after n failed type checks.
  1997. // Disable ObjTypeSpec in a large loop body after the first rejit itself.
  1998. // Rejitting a large loop body takes more time and the fact that loop bodies are prioritized ahead of functions to be jitted only augments the problem.
  1999. if(executeFunction->GetByteCodeInLoopCount() > (uint)CONFIG_FLAG(LoopBodySizeThresholdToDisableOpts))
  2000. {
  2001. profileInfo->DisableObjTypeSpecInJitLoopBody();
  2002. if(PHASE_TRACE1(Js::DisabledObjTypeSpecPhase))
  2003. {
  2004. Output::Print(L"Disabled obj type spec in jit loop body for loop %d in %s (%d)\n",
  2005. executeFunction->GetLoopNumber(loopHeader), executeFunction->GetDisplayName(), executeFunction->GetFunctionNumber());
  2006. Output::Flush();
  2007. }
  2008. }
  2009. rejitReason = RejitReason::FailedTypeCheck;
  2010. break;
  2011. case IR::BailOutFailedFixedFieldTypeCheck:
  2012. // An inline cache must have gone from monomorphic to polymorphic or some fixed field
  2013. // became non-fixed. Either one is already noted in the profile data and type system,
  2014. // so optimization of the given instruction will be inhibited on re-jit.
  2015. // Consider disabling the optimization across the function after n failed type checks.
  2016. rejitReason = RejitReason::FailedFixedFieldTypeCheck;
  2017. break;
  2018. case IR::BailOutFailedEquivalentTypeCheck:
  2019. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  2020. rejitReason = bailOutKind == IR::BailOutFailedEquivalentTypeCheck ?
  2021. RejitReason::FailedEquivalentTypeCheck : RejitReason::FailedEquivalentFixedFieldTypeCheck;
  2022. break;
  2023. case IR::BailOutFailedCtorGuardCheck:
  2024. // (ObjTypeSpec): Consider scheduling re-JIT right after the first bailout. We will never successfully execute the
  2025. // function from which we just bailed out, unless we take a different code path through it.
  2026. // A constructor cache guard may be invalidated for one of two reasons:
  2027. // a) the constructor's prototype property has changed, or
  2028. // b) one of the properties protected by the guard (this constructor cache served as) has changed in some way (e.g. became
  2029. // read-only).
  2030. // In the former case, the cache itself will be marked as polymorphic and on re-JIT we won't do the optimization.
  2031. // In the latter case, the inline cache for the offending property will be cleared and on re-JIT the guard will not be enlisted
  2032. // to protect that property operation.
  2033. rejitReason = RejitReason::CtorGuardInvalidated;
  2034. break;
  2035. case IR::BailOutOnFloor:
  2036. {
  2037. profileInfo->DisableFloorInlining();
  2038. rejitReason = RejitReason::FloorInliningDisabled;
  2039. break;
  2040. }
  2041. case IR::BailOutFailedFixedFieldCheck:
  2042. rejitReason = RejitReason::FailedFixedFieldCheck;
  2043. break;
  2044. case IR::BailOutOnTaggedValue:
  2045. rejitReason = RejitReason::FailedTagCheck;
  2046. break;
  2047. }
  2048. if(PHASE_FORCE(Js::ReJITPhase, executeFunction) && rejitReason == RejitReason::None)
  2049. {
  2050. rejitReason = RejitReason::Forced;
  2051. }
  2052. }
  2053. REJIT_KIND_TESTTRACE(bailOutKind, L"Bailout from loop: function: %s, loopNumber: %d, bailOutKindName: (%S), reJitReason: %S\r\n",
  2054. function->GetFunctionBody()->GetDisplayName(), executeFunction->GetLoopNumber(loopHeader),
  2055. ::GetBailOutKindName(bailOutKind), RejitReasonNames[rejitReason]);
  2056. #ifdef REJIT_STATS
  2057. if(PHASE_STATS(Js::ReJITPhase, executeFunction))
  2058. {
  2059. executeFunction->GetScriptContext()->LogBailout(executeFunction, bailOutKind);
  2060. }
  2061. #endif
  2062. if (rejitReason != RejitReason::None)
  2063. {
  2064. #ifdef REJIT_STATS
  2065. if(PHASE_STATS(Js::ReJITPhase, executeFunction))
  2066. {
  2067. executeFunction->GetScriptContext()->LogRejit(executeFunction, rejitReason);
  2068. }
  2069. #endif
  2070. // Single bailout triggers re-JIT of loop body. the actual codegen scheduling of the new
  2071. // loop body happens in the interpreter
  2072. loopHeader->interpretCount = executeFunction->GetLoopInterpretCount(loopHeader) - 2;
  2073. loopHeader->CreateEntryPoint();
  2074. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2075. if(PHASE_TRACE(Js::ReJITPhase, executeFunction))
  2076. {
  2077. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2078. Output::Print(
  2079. L"Rejit(loop): function: %s (%s) loop: %u bailOutCount: %hu reason: %S",
  2080. executeFunction->GetDisplayName(),
  2081. executeFunction->GetDebugNumberSet(debugStringBuffer),
  2082. executeFunction->GetLoopNumber(loopHeader),
  2083. bailOutRecord->bailOutCount,
  2084. RejitReasonNames[rejitReason]);
  2085. if(bailOutKind != IR::BailOutInvalid)
  2086. {
  2087. Output::Print(L" (%S)", ::GetBailOutKindName(bailOutKind));
  2088. }
  2089. Output::Print(L"\n");
  2090. Output::Flush();
  2091. }
  2092. #endif
  2093. }
  2094. }
  2095. Js::Var BailOutRecord::BailOutForElidedYield(void * framePointer)
  2096. {
  2097. Js::JavascriptCallStackLayout * const layout = Js::JavascriptCallStackLayout::FromFramePointer(framePointer);
  2098. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&layout->functionObject;
  2099. Js::ScriptFunction * function = *functionRef;
  2100. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  2101. Js::ScriptContext * functionScriptContext = executeFunction->GetScriptContext();
  2102. bool isInDebugMode = functionScriptContext->IsInDebugMode();
  2103. Js::JavascriptGenerator* generator = static_cast<Js::JavascriptGenerator*>(layout->args[0]);
  2104. Js::InterpreterStackFrame* frame = generator->GetFrame();
  2105. ThreadContext *threadContext = frame->GetScriptContext()->GetThreadContext();
  2106. Js::ResumeYieldData* resumeYieldData = static_cast<Js::ResumeYieldData*>(layout->args[1]);
  2107. frame->SetNonVarReg(executeFunction->GetYieldRegister(), resumeYieldData);
  2108. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  2109. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  2110. frame->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  2111. executeFunction->BeginExecution();
  2112. Js::Var aReturn = nullptr;
  2113. {
  2114. // Following _AddressOfReturnAddress <= real address of "returnAddress". Suffices for RemoteStackWalker to test partially initialized interpreter frame.
  2115. Js::InterpreterStackFrame::PushPopFrameHelper pushPopFrameHelper(frame, _ReturnAddress(), _AddressOfReturnAddress());
  2116. aReturn = isInDebugMode ? frame->DebugProcess() : frame->Process();
  2117. // Note: in debug mode we always have to bailout to debug thunk,
  2118. // as normal interpreter thunk expects byte code compiled w/o debugging.
  2119. }
  2120. executeFunction->EndExecution();
  2121. if (executeFunction->HasDynamicProfileInfo())
  2122. {
  2123. Js::DynamicProfileInfo *dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  2124. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  2125. }
  2126. return aReturn;
  2127. }
  2128. BranchBailOutRecord::BranchBailOutRecord(uint32 trueBailOutOffset, uint32 falseBailOutOffset, Js::RegSlot resultByteCodeReg, IR::BailOutKind kind, Func * bailOutFunc)
  2129. : BailOutRecord(trueBailOutOffset, (uint)-1, kind, bailOutFunc), falseBailOutOffset(falseBailOutOffset)
  2130. {
  2131. branchValueRegSlot = resultByteCodeReg;
  2132. };
  2133. Js::Var BranchBailOutRecord::BailOut(BranchBailOutRecord const * bailOutRecord, BOOL cond)
  2134. {
  2135. Assert(bailOutRecord);
  2136. void * argoutRestoreAddr = nullptr;
  2137. #ifdef _M_IX86
  2138. void * addressOfRetAddress = _AddressOfReturnAddress();
  2139. if (bailOutRecord->ehBailoutData && (bailOutRecord->ehBailoutData->catchOffset != 0))
  2140. {
  2141. argoutRestoreAddr = (void *)((char*)addressOfRetAddress + ((2 + 1) * MachPtr)); // Account for the parameters and return address of this function
  2142. }
  2143. #endif
  2144. Js::JavascriptCallStackLayout *const layout = bailOutRecord->GetStackLayout();
  2145. if(bailOutRecord->globalBailOutRecordTable->isLoopBody)
  2146. {
  2147. if (bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  2148. {
  2149. return reinterpret_cast<Js::Var>(BailOutFromLoopBodyInlined(layout, bailOutRecord, cond, _ReturnAddress()));
  2150. }
  2151. return reinterpret_cast<Js::Var>(BailOutFromLoopBody(layout, bailOutRecord, cond));
  2152. }
  2153. if(bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  2154. {
  2155. return BailOutInlined(layout, bailOutRecord, cond, _ReturnAddress());
  2156. }
  2157. return BailOutFromFunction(layout, bailOutRecord, cond, _ReturnAddress(), argoutRestoreAddr);
  2158. }
  2159. Js::Var
  2160. BranchBailOutRecord::BailOutFromFunction(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress, void * argoutRestoreAddress)
  2161. {
  2162. Assert(bailOutRecord->parent == nullptr);
  2163. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2164. Js::Var branchValue = nullptr;
  2165. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2166. {
  2167. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2168. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2169. }
  2170. return __super::BailOutCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, branchValue, nullptr, argoutRestoreAddress);
  2171. }
  2172. uint32
  2173. BranchBailOutRecord::BailOutFromLoopBody(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond)
  2174. {
  2175. Assert(bailOutRecord->parent == nullptr);
  2176. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2177. Js::Var branchValue = nullptr;
  2178. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2179. {
  2180. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2181. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2182. }
  2183. return __super::BailOutFromLoopBodyCommon(layout, bailOutRecord, bailOutOffset, bailOutRecord->bailOutKind, branchValue);
  2184. }
  2185. Js::Var
  2186. BranchBailOutRecord::BailOutInlined(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress)
  2187. {
  2188. Assert(bailOutRecord->parent != nullptr);
  2189. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2190. Js::Var branchValue = nullptr;
  2191. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2192. {
  2193. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2194. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2195. }
  2196. return __super::BailOutInlinedCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, branchValue);
  2197. }
  2198. uint32
  2199. BranchBailOutRecord::BailOutFromLoopBodyInlined(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress)
  2200. {
  2201. Assert(bailOutRecord->parent != nullptr);
  2202. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2203. Js::Var branchValue = nullptr;
  2204. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2205. {
  2206. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2207. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2208. }
  2209. return __super::BailOutFromLoopBodyInlinedCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, branchValue);
  2210. }
  2211. void LazyBailOutRecord::SetBailOutKind()
  2212. {
  2213. this->bailoutRecord->SetBailOutKind(IR::BailOutKind::LazyBailOut);
  2214. }
  2215. #if DBG
  2216. void LazyBailOutRecord::Dump(Js::FunctionBody* functionBody)
  2217. {
  2218. OUTPUT_PRINT(functionBody);
  2219. Output::Print(L"Bytecode Offset: #%04x opcode: %s", this->bailoutRecord->GetBailOutOffset(), Js::OpCodeUtil::GetOpCodeName(this->bailoutRecord->GetBailOutOpCode()));
  2220. }
  2221. #endif
  2222. void GlobalBailOutRecordDataTable::Finalize(NativeCodeData::Allocator *allocator, JitArenaAllocator *tempAlloc)
  2223. {
  2224. GlobalBailOutRecordDataRow *newRows = NativeCodeDataNewArrayZ(allocator, GlobalBailOutRecordDataRow, length);
  2225. memcpy(newRows, globalBailOutRecordDataRows, sizeof(GlobalBailOutRecordDataRow) * length);
  2226. JitAdeleteArray(tempAlloc, length, globalBailOutRecordDataRows);
  2227. globalBailOutRecordDataRows = newRows;
  2228. size = length;
  2229. #if DBG
  2230. if (length > 0)
  2231. {
  2232. uint32 currStart = globalBailOutRecordDataRows[0].start;
  2233. for (uint32 i = 1; i < length; i++)
  2234. {
  2235. AssertMsg(currStart <= globalBailOutRecordDataRows[i].start,
  2236. "Rows in the table must be in order by start ID");
  2237. currStart = globalBailOutRecordDataRows[i].start;
  2238. }
  2239. }
  2240. #endif
  2241. }
  2242. void GlobalBailOutRecordDataTable::AddOrUpdateRow(JitArenaAllocator *allocator, uint32 bailOutRecordId, uint32 regSlot, bool isFloat, bool isInt, bool isSimd128F4, bool isSimd128I4, int32 offset, uint *lastUpdatedRowIndex)
  2243. {
  2244. Assert(offset != 0);
  2245. const int INITIAL_TABLE_SIZE = 64;
  2246. if (size == 0)
  2247. {
  2248. Assert(length == 0);
  2249. size = INITIAL_TABLE_SIZE;
  2250. globalBailOutRecordDataRows = JitAnewArrayZ(allocator, GlobalBailOutRecordDataRow, size);
  2251. }
  2252. Assert(lastUpdatedRowIndex != nullptr);
  2253. if ((*lastUpdatedRowIndex) != -1)
  2254. {
  2255. GlobalBailOutRecordDataRow *rowToUpdate = &globalBailOutRecordDataRows[(*lastUpdatedRowIndex)];
  2256. if(rowToUpdate->offset == offset &&
  2257. rowToUpdate->isInt == (unsigned)isInt &&
  2258. rowToUpdate->isFloat == (unsigned)isFloat &&
  2259. // SIMD_JS
  2260. rowToUpdate->isSimd128F4 == (unsigned) isSimd128F4 &&
  2261. rowToUpdate->isSimd128I4 == (unsigned) isSimd128I4 &&
  2262. rowToUpdate->end + 1 == bailOutRecordId)
  2263. {
  2264. Assert(rowToUpdate->regSlot == regSlot);
  2265. rowToUpdate->end = bailOutRecordId;
  2266. return;
  2267. }
  2268. }
  2269. if (length == size)
  2270. {
  2271. size = length << 1;
  2272. globalBailOutRecordDataRows = (GlobalBailOutRecordDataRow *)allocator->Realloc(globalBailOutRecordDataRows, length * sizeof(GlobalBailOutRecordDataRow), size * sizeof(GlobalBailOutRecordDataRow));
  2273. }
  2274. GlobalBailOutRecordDataRow *rowToInsert = &globalBailOutRecordDataRows[length];
  2275. rowToInsert->start = bailOutRecordId;
  2276. rowToInsert->end = bailOutRecordId;
  2277. rowToInsert->offset = offset;
  2278. rowToInsert->isFloat = isFloat;
  2279. rowToInsert->isInt = isInt;
  2280. // SIMD_JS
  2281. rowToInsert->isSimd128F4 = isSimd128F4;
  2282. rowToInsert->isSimd128I4 = isSimd128I4;
  2283. rowToInsert->regSlot = regSlot;
  2284. *lastUpdatedRowIndex = length++;
  2285. }