BailOut.cpp 131 KB

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