ByteCodeWriter.cpp 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "RuntimeByteCodePch.h"
  7. namespace Js
  8. {
  9. CompileAssert(!OpCodeInfo<Js::OpCode::Br>::HasMultiSizeLayout);
  10. CompileAssert(!OpCodeInfo<Js::OpCode::BrLong>::HasMultiSizeLayout);
  11. const uint ByteCodeWriter::JumpAroundSize = OpCodeUtil::EncodedSize(Js::OpCode::Br, SmallLayout) + sizeof(OpLayoutBr);
  12. const uint ByteCodeWriter::LongBranchSize = OpCodeUtil::EncodedSize(Js::OpCode::BrLong, SmallLayout) + sizeof(OpLayoutBrLong);
  13. void ByteCodeWriter::Create()
  14. {
  15. m_loopNest = 0;
  16. m_byteCodeCount = 0;
  17. m_byteCodeWithoutLDACount = 0;
  18. m_byteCodeInLoopCount = 0;
  19. m_functionWrite = nullptr;
  20. m_pMatchingNode = nullptr;
  21. m_matchingNodeRefCount = 0;
  22. m_tmpRegCount = 0;
  23. DebugOnly(isInitialized = false);
  24. DebugOnly(isInUse = false);
  25. }
  26. void ByteCodeWriter::InitData(ArenaAllocator* alloc, int32 initCodeBufferSize)
  27. {
  28. Assert(!isInUse);
  29. Assert(!isInitialized);
  30. DebugOnly(isInitialized = true);
  31. m_labelOffsets = JsUtil::List<uint, ArenaAllocator>::New(alloc);
  32. m_jumpOffsets = JsUtil::List<JumpInfo, ArenaAllocator>::New(alloc);
  33. m_loopHeaders = JsUtil::List<LoopHeaderData, ArenaAllocator>::New(alloc);
  34. m_byteCodeData.Create(initCodeBufferSize, alloc);
  35. m_subexpressionNodesStack = Anew(alloc, JsUtil::Stack<SubexpressionNode>, alloc);
  36. // These data units have exponential growth strategy - let's start small and grow them
  37. m_auxiliaryData.Create(256, alloc);
  38. m_auxContextData.Create(256, alloc);
  39. callRegToLdFldCacheIndexMap = Anew(alloc, CallRegToLdFldCacheIndexMap,
  40. alloc,
  41. 17);
  42. #ifdef BYTECODE_BRANCH_ISLAND
  43. useBranchIsland = true;
  44. inEnsureLongBranch = false;
  45. lastOpcode = Js::OpCode::FunctionEntry;
  46. this->UpdateNextBranchIslandOffset(0, 0);
  47. m_longJumpOffsets = JsUtil::List<JumpInfo, ArenaAllocator>::New(alloc);
  48. #endif
  49. }
  50. ///----------------------------------------------------------------------------
  51. ///
  52. /// Begin() configures this instance to generate byte-code for a specific
  53. /// JavascriptFunction:
  54. ///
  55. /// - Byte-code will be written until the caller uses End() to close and commit
  56. /// the stream to the given function, or Reset() to discard and reset to an
  57. /// empty state.
  58. ///
  59. /// - Each ByteCodeWriter may be used multiple times, but may only generate a
  60. /// single byte-code stream for a single function at a time.
  61. ///
  62. ///----------------------------------------------------------------------------
  63. void ByteCodeWriter::Begin(FunctionBody* functionWrite, ArenaAllocator* alloc, bool doJitLoopBodies, bool hasLoop, bool inDebugMode)
  64. {
  65. Assert(!isInUse);
  66. AssertMsg(m_functionWrite == nullptr, "Cannot nest Begin() calls");
  67. AssertMsg(functionWrite != nullptr, "Must have valid function to write");
  68. AssertMsg(functionWrite->GetByteCode() == nullptr, "Function should not already have a byte-code body");
  69. AssertMsg(functionWrite->GetLocalsCount() > 0, "Must always have R0 for return-value");
  70. DebugOnly(isInUse = true);
  71. m_functionWrite = functionWrite;
  72. m_doJitLoopBodies = doJitLoopBodies;
  73. m_doInterruptProbe = functionWrite->GetScriptContext()->GetThreadContext()->DoInterruptProbe(functionWrite);
  74. m_hasLoop = hasLoop;
  75. m_isInDebugMode = inDebugMode;
  76. }
  77. template <typename T>
  78. void ByteCodeWriter::PatchJumpOffset(JsUtil::List<JumpInfo, ArenaAllocator> * jumpOffset, byte * byteBuffer, uint byteCount)
  79. {
  80. jumpOffset->Map([=](int index, JumpInfo& jumpInfo)
  81. {
  82. //
  83. // Read "labelID" stored at the offset within the byte-code.
  84. //
  85. uint jumpByteOffset = jumpInfo.patchOffset;
  86. AssertMsg(jumpByteOffset < byteCount - sizeof(T),
  87. "Must have valid jump site within byte-code to back-patch");
  88. unaligned T * pnBackPatch = reinterpret_cast<unaligned T *>(&byteBuffer[jumpByteOffset]);
  89. ByteCodeLabel labelID = jumpInfo.labelId;
  90. CheckLabel(labelID);
  91. uint offsetToEndOfLayoutByteSize = *pnBackPatch;
  92. Assert(offsetToEndOfLayoutByteSize < 0x20);
  93. //
  94. // Use "labelID" to lookup the destination offset, replacing the temporary data in the
  95. // byte-code.
  96. //
  97. uint labelByteOffset = m_labelOffsets->Item(labelID);
  98. AssertMsg(labelByteOffset != UINT_MAX, "ERROR: Destination labels must be marked before closing");
  99. int relativeJumpOffset = labelByteOffset - jumpByteOffset - offsetToEndOfLayoutByteSize;
  100. #ifdef BYTECODE_BRANCH_ISLAND
  101. Assert(!useBranchIsland || (jumpOffset != m_jumpOffsets || (relativeJumpOffset < GetBranchLimit() && relativeJumpOffset >= -GetBranchLimit())));
  102. #endif
  103. Assert((T)relativeJumpOffset == relativeJumpOffset);
  104. *pnBackPatch = (T)relativeJumpOffset;
  105. });
  106. }
  107. ///----------------------------------------------------------------------------
  108. ///
  109. /// End() completes generating byte-code for the given JavascriptFunction and
  110. /// commits it to the function's body.
  111. ///
  112. ///----------------------------------------------------------------------------
  113. #ifdef LOG_BYTECODE_AST_RATIO
  114. void ByteCodeWriter::End(int32 currentAstSize, int32 maxAstSize)
  115. #else
  116. void ByteCodeWriter::End()
  117. #endif
  118. {
  119. Assert(isInUse);
  120. CheckOpen();
  121. Empty(OpCode::EndOfBlock);
  122. ByteBlock* finalByteCodeBlock = nullptr;
  123. ScriptContext* scriptContext = m_functionWrite->GetScriptContext();
  124. m_byteCodeData.Copy(scriptContext->GetRecycler(), &finalByteCodeBlock);
  125. byte * byteBuffer = finalByteCodeBlock->GetBuffer();
  126. uint byteCount = m_byteCodeData.GetCurrentOffset();
  127. //
  128. // Update all branch targets with their actual label destinations.
  129. //
  130. #ifdef BYTECODE_BRANCH_ISLAND
  131. if (useBranchIsland)
  132. {
  133. PatchJumpOffset<JumpOffset>(m_jumpOffsets, byteBuffer, byteCount);
  134. PatchJumpOffset<LongJumpOffset>(m_longJumpOffsets, byteBuffer, byteCount);
  135. }
  136. else
  137. {
  138. PatchJumpOffset<LongJumpOffset>(m_jumpOffsets, byteBuffer, byteCount);
  139. }
  140. #else
  141. PatchJumpOffset<JumpOffset>(m_jumpOffsets, byteBuffer, byteCount);
  142. #endif
  143. // Patch up the root object load inline cache with the start index
  144. uint rootObjectLoadInlineCacheStart = this->m_functionWrite->GetRootObjectLoadInlineCacheStart();
  145. rootObjectLoadInlineCacheOffsets.Map([=](size_t offset)
  146. {
  147. Assert(offset < byteCount - sizeof(int));
  148. unaligned uint * pnBackPatch = reinterpret_cast<unaligned uint *>(&byteBuffer[offset]);
  149. *pnBackPatch += rootObjectLoadInlineCacheStart;
  150. });
  151. // Patch up the root object load method inline cache with the start index
  152. uint rootObjectLoadMethodInlineCacheStart = this->m_functionWrite->GetRootObjectLoadMethodInlineCacheStart();
  153. rootObjectLoadMethodInlineCacheOffsets.Map([=](size_t offset)
  154. {
  155. Assert(offset < byteCount - sizeof(int));
  156. unaligned uint * pnBackPatch = reinterpret_cast<unaligned uint *>(&byteBuffer[offset]);
  157. *pnBackPatch += rootObjectLoadMethodInlineCacheStart;
  158. });
  159. // Patch up the root object store inline cache with the start index
  160. uint rootObjectStoreInlineCacheStart = this->m_functionWrite->GetRootObjectStoreInlineCacheStart();
  161. rootObjectStoreInlineCacheOffsets.Map([=](size_t offset)
  162. {
  163. Assert(offset < byteCount - sizeof(int));
  164. unaligned uint * pnBackPatch = reinterpret_cast<unaligned uint *>(&byteBuffer[offset]);
  165. *pnBackPatch += rootObjectStoreInlineCacheStart;
  166. });
  167. //
  168. // Store the final trimmed byte-code on the function.
  169. //
  170. ByteBlock* finalAuxiliaryBlock = nullptr;
  171. ByteBlock* finalAuxiliaryContextBlock = nullptr;
  172. m_auxiliaryData.Copy(m_functionWrite->GetScriptContext()->GetRecycler(), &finalAuxiliaryBlock);
  173. m_auxContextData.Copy(m_functionWrite->GetScriptContext()->GetRecycler(), &finalAuxiliaryContextBlock);
  174. m_functionWrite->AllocateInlineCache();
  175. m_functionWrite->AllocateObjectLiteralTypeArray();
  176. m_functionWrite->AllocateForInCache();
  177. if (!PHASE_OFF(Js::ScriptFunctionWithInlineCachePhase, m_functionWrite) && !PHASE_OFF(Js::InlineApplyTargetPhase, m_functionWrite))
  178. {
  179. if (m_functionWrite->CanFunctionObjectHaveInlineCaches())
  180. {
  181. m_functionWrite->SetInlineCachesOnFunctionObject(true);
  182. }
  183. }
  184. if (this->DoJitLoopBodies() &&
  185. !(this->m_functionWrite->GetFunctionBody()->GetHasTry() && PHASE_OFF(Js::JITLoopBodyInTryCatchPhase, this->m_functionWrite)) &&
  186. !(this->m_functionWrite->GetFunctionBody()->GetHasFinally() && PHASE_OFF(Js::JITLoopBodyInTryFinallyPhase, this->m_functionWrite)))
  187. {
  188. AllocateLoopHeaders();
  189. }
  190. m_functionWrite->MarkScript(finalByteCodeBlock, finalAuxiliaryBlock, finalAuxiliaryContextBlock,
  191. m_byteCodeCount, m_byteCodeInLoopCount, m_byteCodeWithoutLDACount);
  192. #if ENABLE_PROFILE_INFO
  193. m_functionWrite->LoadDynamicProfileInfo();
  194. #endif
  195. JS_ETW(EventWriteJSCRIPT_BYTECODEGEN_METHOD(m_functionWrite->GetHostSourceContext(), m_functionWrite->GetScriptContext(), m_functionWrite->GetLocalFunctionId(), m_functionWrite->GetByteCodeCount(), this->GetTotalSize(), m_functionWrite->GetExternalDisplayName()));
  196. #ifdef LOG_BYTECODE_AST_RATIO
  197. // log the bytecode AST ratio
  198. if (currentAstSize == maxAstSize)
  199. {
  200. float astBytecodeRatio = (float)currentAstSize / (float)byteCount;
  201. Output::Print(_u("\tAST Bytecode ratio: %f\n"), astBytecodeRatio);
  202. }
  203. #endif
  204. // TODO: add validation for source mapping under #dbg
  205. //
  206. // Reset the writer to prepare for the next user.
  207. //
  208. Reset();
  209. }
  210. void ByteCodeWriter::AllocateLoopHeaders()
  211. {
  212. m_functionWrite->AllocateLoopHeaders();
  213. m_loopHeaders->Map([this](int index, ByteCodeWriter::LoopHeaderData& data)
  214. {
  215. LoopHeader *loopHeader = m_functionWrite->GetLoopHeader(index);
  216. loopHeader->startOffset = data.startOffset;
  217. loopHeader->endOffset = data.endOffset;
  218. loopHeader->isNested = data.isNested;
  219. });
  220. }
  221. ///----------------------------------------------------------------------------
  222. ///
  223. /// Reset() discards any current byte-code and resets to a known "empty" state:
  224. /// - This method may be called at any time between Create() and Dispose().
  225. ///
  226. ///----------------------------------------------------------------------------
  227. void ByteCodeWriter::Reset()
  228. {
  229. DebugOnly(isInUse = false);
  230. Assert(isInitialized);
  231. m_byteCodeData.Reset();
  232. m_auxiliaryData.Reset();
  233. m_auxContextData.Reset();
  234. #ifdef BYTECODE_BRANCH_ISLAND
  235. lastOpcode = Js::OpCode::FunctionEntry;
  236. this->UpdateNextBranchIslandOffset(0, 0);
  237. m_longJumpOffsets->Clear();
  238. #endif
  239. m_labelOffsets->Clear();
  240. m_jumpOffsets->Clear();
  241. m_loopHeaders->Clear();
  242. rootObjectLoadInlineCacheOffsets.Clear(m_labelOffsets->GetAllocator());
  243. rootObjectStoreInlineCacheOffsets.Clear(m_labelOffsets->GetAllocator());
  244. rootObjectLoadMethodInlineCacheOffsets.Clear(m_labelOffsets->GetAllocator());
  245. callRegToLdFldCacheIndexMap->ResetNoDelete();
  246. m_pMatchingNode = nullptr;
  247. m_matchingNodeRefCount = 0;
  248. m_functionWrite = nullptr;
  249. m_byteCodeCount = 0;
  250. m_byteCodeWithoutLDACount = 0;
  251. m_byteCodeInLoopCount = 0;
  252. m_loopNest = 0;
  253. m_currentDebuggerScope = nullptr;
  254. }
  255. inline Js::RegSlot ByteCodeWriter::ConsumeReg(Js::RegSlot reg)
  256. {
  257. CheckReg(reg);
  258. Assert(this->m_functionWrite);
  259. return this->m_functionWrite->MapRegSlot(reg);
  260. }
  261. void ByteCodeWriter::CheckOpen()
  262. {
  263. AssertMsg(m_functionWrite != nullptr, "Must Begin() a function to write byte-code into");
  264. }
  265. inline void ByteCodeWriter::CheckOp(OpCode op, OpLayoutType layoutType)
  266. {
  267. AssertMsg(OpCodeUtil::IsValidByteCodeOpcode(op), "Ensure valid OpCode");
  268. #if ENABLE_NATIVE_CODEGEN
  269. AssertMsg(!OpCodeAttr::BackEndOnly(op), "Can't write back end only OpCode");
  270. #endif
  271. AssertMsg(OpCodeUtil::GetOpCodeLayout(op) == layoutType, "Ensure correct layout for OpCode");
  272. AssertMsg(!CONFIG_FLAG(LdChakraLib) || !OpCodeAttr::LoadRoot(op), "JsBuiltIn code shouldn't touch the global");
  273. }
  274. void ByteCodeWriter::CheckLabel(ByteCodeLabel labelID)
  275. {
  276. AssertMsg(labelID >= 0 && labelID < m_labelOffsets->Count(),
  277. "Label must be previously defined before being marked in the byte-code");
  278. }
  279. inline void ByteCodeWriter::CheckReg(RegSlot registerID)
  280. {
  281. AssertMsg(registerID != Js::Constants::NoRegister, "bad register");
  282. if (registerID == Js::Constants::NoRegister)
  283. Js::Throw::InternalError();
  284. }
  285. void ByteCodeWriter::Empty(OpCode op)
  286. {
  287. CheckOpen();
  288. CheckOp(op, OpLayoutType::Empty);
  289. m_byteCodeData.Encode(op, this);
  290. }
  291. #define MULTISIZE_LAYOUT_WRITE(layout, ...) \
  292. if (!TryWrite##layout<SmallLayoutSizePolicy>(__VA_ARGS__) && !TryWrite##layout<MediumLayoutSizePolicy>(__VA_ARGS__)) \
  293. { \
  294. bool success = TryWrite##layout<LargeLayoutSizePolicy>(__VA_ARGS__); \
  295. Assert(success); \
  296. }
  297. template <typename SizePolicy>
  298. bool ByteCodeWriter::TryWriteReg1(OpCode op, RegSlot R0)
  299. {
  300. OpLayoutT_Reg1<SizePolicy> layout;
  301. if (SizePolicy::Assign(layout.R0, R0))
  302. {
  303. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  304. return true;
  305. }
  306. return false;
  307. }
  308. void ByteCodeWriter::Reg1(OpCode op, RegSlot R0)
  309. {
  310. CheckOpen();
  311. CheckOp(op, OpLayoutType::Reg1);
  312. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  313. R0 = ConsumeReg(R0);
  314. MULTISIZE_LAYOUT_WRITE(Reg1, op, R0);
  315. }
  316. template <typename SizePolicy>
  317. bool ByteCodeWriter::TryWriteReg2(OpCode op, RegSlot R0, RegSlot R1)
  318. {
  319. OpLayoutT_Reg2<SizePolicy> layout;
  320. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1))
  321. {
  322. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  323. return true;
  324. }
  325. return false;
  326. }
  327. void ByteCodeWriter::Reg2(OpCode op, RegSlot R0, RegSlot R1)
  328. {
  329. CheckOpen();
  330. CheckOp(op, OpLayoutType::Reg2);
  331. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  332. R0 = ConsumeReg(R0);
  333. R1 = ConsumeReg(R1);
  334. bool isProfiled = false;
  335. bool isProfiled2 = false;
  336. Js::ProfileId profileId = Js::Constants::NoProfileId;
  337. Js::ProfileId profileId2 = Js::Constants::NoProfileId;
  338. if (op == Js::OpCode::BeginSwitch && DoDynamicProfileOpcode(SwitchOptPhase) &&
  339. this->m_functionWrite->AllocProfiledSwitch(&profileId))
  340. {
  341. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  342. isProfiled = true;
  343. }
  344. Assert(DoProfileNewScObjArrayOp(op) == false);
  345. Assert(DoProfileNewScObjectOp(op) == false);
  346. MULTISIZE_LAYOUT_WRITE(Reg2, op, R0, R1);
  347. if (isProfiled)
  348. {
  349. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  350. if (isProfiled2)
  351. {
  352. m_byteCodeData.Encode(&profileId2, sizeof(Js::ProfileId));
  353. }
  354. }
  355. }
  356. template <typename SizePolicy>
  357. bool ByteCodeWriter::TryWriteReg3(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2)
  358. {
  359. OpLayoutT_Reg3<SizePolicy> layout;
  360. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2))
  361. {
  362. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  363. return true;
  364. }
  365. return false;
  366. }
  367. void ByteCodeWriter::Reg3(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2)
  368. {
  369. CheckOpen();
  370. CheckOp(op, OpLayoutType::Reg3);
  371. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  372. R0 = ConsumeReg(R0);
  373. R1 = ConsumeReg(R1);
  374. R2 = ConsumeReg(R2);
  375. ProfileId profileId = 0;
  376. bool isProfiled = false;
  377. if ((DoDynamicProfileOpcode(FloatTypeSpecPhase) && (op == Js::OpCode::Div_A || op == Js::OpCode::Rem_A)) &&
  378. this->m_functionWrite->AllocProfiledDivOrRem(&profileId))
  379. {
  380. isProfiled = true;
  381. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  382. }
  383. else if (op == Js::OpCode::IsIn && this->m_functionWrite->AllocProfiledLdElemId(&profileId))
  384. {
  385. isProfiled = true;
  386. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  387. }
  388. MULTISIZE_LAYOUT_WRITE(Reg3, op, R0, R1, R2);
  389. if (isProfiled)
  390. {
  391. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  392. }
  393. }
  394. template <typename SizePolicy>
  395. bool ByteCodeWriter::TryWriteReg3C(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, CacheId cacheId)
  396. {
  397. OpLayoutT_Reg3C<SizePolicy> layout;
  398. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  399. && SizePolicy::Assign(layout.inlineCacheIndex, cacheId))
  400. {
  401. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  402. return true;
  403. }
  404. return false;
  405. }
  406. void ByteCodeWriter::Reg3C(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, uint cacheId)
  407. {
  408. CheckOpen();
  409. CheckOp(op, OpLayoutType::Reg3C);
  410. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  411. R0 = ConsumeReg(R0);
  412. R1 = ConsumeReg(R1);
  413. R2 = ConsumeReg(R2);
  414. MULTISIZE_LAYOUT_WRITE(Reg3C, op, R0, R1, R2, cacheId);
  415. }
  416. template <typename SizePolicy>
  417. bool ByteCodeWriter::TryWriteReg2U(OpCode op, RegSlot R0, RegSlot R1, uint index)
  418. {
  419. OpLayoutT_Reg2U<SizePolicy> layout;
  420. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.SlotIndex, index))
  421. {
  422. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  423. return true;
  424. }
  425. return false;
  426. }
  427. template <typename SizePolicy>
  428. bool ByteCodeWriter::TryWriteReg4(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3)
  429. {
  430. OpLayoutT_Reg4<SizePolicy> layout;
  431. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  432. && SizePolicy::Assign(layout.R3, R3))
  433. {
  434. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  435. return true;
  436. }
  437. return false;
  438. }
  439. void ByteCodeWriter::Reg4(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3)
  440. {
  441. CheckOpen();
  442. CheckOp(op, OpLayoutType::Reg4);
  443. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  444. R0 = ConsumeReg(R0);
  445. R1 = ConsumeReg(R1);
  446. R2 = ConsumeReg(R2);
  447. R3 = ConsumeReg(R3);
  448. MULTISIZE_LAYOUT_WRITE(Reg4, op, R0, R1, R2, R3);
  449. }
  450. template <typename SizePolicy>
  451. bool ByteCodeWriter::TryWriteReg4U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, uint index)
  452. {
  453. OpLayoutT_Reg4U<SizePolicy> layout;
  454. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  455. && SizePolicy::Assign(layout.R3, R3) && SizePolicy::Assign(layout.SlotIndex, index))
  456. {
  457. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  458. return true;
  459. }
  460. return false;
  461. }
  462. void ByteCodeWriter::Reg4U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, uint slotIndex)
  463. {
  464. CheckOpen();
  465. CheckOp(op, OpLayoutType::Reg4U);
  466. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  467. R0 = ConsumeReg(R0);
  468. R1 = ConsumeReg(R1);
  469. R2 = ConsumeReg(R2);
  470. R3 = ConsumeReg(R3);
  471. MULTISIZE_LAYOUT_WRITE(Reg4U, op, R0, R1, R2, R3, slotIndex);
  472. }
  473. template <typename SizePolicy>
  474. bool ByteCodeWriter::TryWriteReg5U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, RegSlot R4, uint index)
  475. {
  476. OpLayoutT_Reg5U<SizePolicy> layout;
  477. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  478. && SizePolicy::Assign(layout.R3, R3) && SizePolicy::Assign(layout.R4, R4) && SizePolicy::Assign(layout.SlotIndex, index))
  479. {
  480. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  481. return true;
  482. }
  483. return false;
  484. }
  485. void ByteCodeWriter::Reg5U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, RegSlot R4, uint slotIndex)
  486. {
  487. CheckOpen();
  488. CheckOp(op, OpLayoutType::Reg5U);
  489. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  490. R0 = ConsumeReg(R0);
  491. R1 = ConsumeReg(R1);
  492. R2 = ConsumeReg(R2);
  493. R3 = ConsumeReg(R3);
  494. R4 = ConsumeReg(R4);
  495. MULTISIZE_LAYOUT_WRITE(Reg5U, op, R0, R1, R2, R3, R4, slotIndex);
  496. }
  497. template <typename SizePolicy>
  498. bool ByteCodeWriter::TryWriteReg2B1(OpCode op, RegSlot R0, RegSlot R1, uint8 B2)
  499. {
  500. OpLayoutT_Reg2B1<SizePolicy> layout;
  501. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.B2, B2))
  502. {
  503. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  504. return true;
  505. }
  506. return false;
  507. }
  508. void ByteCodeWriter::Reg2B1(OpCode op, RegSlot R0, RegSlot R1, uint8 B2)
  509. {
  510. CheckOpen();
  511. CheckOp(op, OpLayoutType::Reg2B1);
  512. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  513. R0 = ConsumeReg(R0);
  514. R1 = ConsumeReg(R1);
  515. MULTISIZE_LAYOUT_WRITE(Reg2B1, op, R0, R1, B2);
  516. }
  517. template <typename SizePolicy>
  518. bool ByteCodeWriter::TryWriteReg3B1(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, uint8 B3)
  519. {
  520. OpLayoutT_Reg3B1<SizePolicy> layout;
  521. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  522. && SizePolicy::Assign(layout.B3, B3))
  523. {
  524. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  525. return true;
  526. }
  527. return false;
  528. }
  529. void ByteCodeWriter::Reg3B1(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, uint8 B3)
  530. {
  531. CheckOpen();
  532. CheckOp(op, OpLayoutType::Reg3B1);
  533. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  534. R0 = ConsumeReg(R0);
  535. R1 = ConsumeReg(R1);
  536. R2 = ConsumeReg(R2);
  537. MULTISIZE_LAYOUT_WRITE(Reg3B1, op, R0, R1, R2, B3);
  538. }
  539. template <typename SizePolicy>
  540. bool ByteCodeWriter::TryWriteReg5(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, RegSlot R4)
  541. {
  542. OpLayoutT_Reg5<SizePolicy> layout;
  543. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2)
  544. && SizePolicy::Assign(layout.R3, R3) && SizePolicy::Assign(layout.R4, R4))
  545. {
  546. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  547. return true;
  548. }
  549. return false;
  550. }
  551. void ByteCodeWriter::Reg5(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, RegSlot R3, RegSlot R4)
  552. {
  553. CheckOpen();
  554. CheckOp(op, OpLayoutType::Reg5);
  555. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  556. R0 = ConsumeReg(R0);
  557. R1 = ConsumeReg(R1);
  558. R2 = ConsumeReg(R2);
  559. R3 = ConsumeReg(R3);
  560. R4 = ConsumeReg(R4);
  561. MULTISIZE_LAYOUT_WRITE(Reg5, op, R0, R1, R2, R3, R4);
  562. }
  563. template <typename SizePolicy>
  564. bool ByteCodeWriter::TryWriteUnsigned1(OpCode op, uint C1)
  565. {
  566. OpLayoutT_Unsigned1<SizePolicy> layout;
  567. if (SizePolicy::Assign(layout.C1, C1))
  568. {
  569. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  570. return true;
  571. }
  572. return false;
  573. }
  574. void ByteCodeWriter::Unsigned1(OpCode op, uint C1)
  575. {
  576. CheckOpen();
  577. CheckOp(op, OpLayoutType::Unsigned1);
  578. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  579. MULTISIZE_LAYOUT_WRITE(Unsigned1, op, C1);
  580. }
  581. void ByteCodeWriter::ArgIn0(RegSlot reg)
  582. {
  583. AssertMsg(0 < m_functionWrite->GetInParamsCount(),
  584. "Ensure source arg was declared in prologue");
  585. Reg1(OpCode::ArgIn0, reg);
  586. }
  587. template void ByteCodeWriter::ArgOut<true>(ArgSlot arg, RegSlot reg, ProfileId callSiteId, bool emitProfiledArgout);
  588. template void ByteCodeWriter::ArgOut<false>(ArgSlot arg, RegSlot reg, ProfileId callSiteId, bool emitProfiledArgout);
  589. template <typename SizePolicy>
  590. bool ByteCodeWriter::TryWriteArg(OpCode op, ArgSlot arg, RegSlot reg)
  591. {
  592. OpLayoutT_Arg<SizePolicy> layout;
  593. if (SizePolicy::Assign(layout.Arg, arg) && SizePolicy::Assign(layout.Reg, reg))
  594. {
  595. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  596. return true;
  597. }
  598. return false;
  599. }
  600. template <bool isVar>
  601. void ByteCodeWriter::ArgOut(ArgSlot arg, RegSlot reg, ProfileId callSiteId, bool emitProfiledArgout)
  602. {
  603. CheckOpen();
  604. Assert(OpCodeAttr::HasMultiSizeLayout(OpCode::ArgOut_A) && OpCodeAttr::HasMultiSizeLayout(OpCode::ArgOut_ANonVar));
  605. // Note: don't "consume" the arg slot, as the passed-in value is the final one.
  606. reg = ConsumeReg(reg);
  607. OpCode op;
  608. if (isVar)
  609. {
  610. op = OpCode::ArgOut_A;
  611. }
  612. else
  613. {
  614. op = OpCode::ArgOut_ANonVar;
  615. MULTISIZE_LAYOUT_WRITE(Arg, op, arg, reg);
  616. return;
  617. }
  618. if (emitProfiledArgout
  619. && DoDynamicProfileOpcode(InlinePhase)
  620. && arg > 0 && arg < Js::Constants::MaximumArgumentCountForConstantArgumentInlining
  621. && reg > FunctionBody::FirstRegSlot
  622. && callSiteId != Js::Constants::NoProfileId
  623. )
  624. {
  625. MULTISIZE_LAYOUT_WRITE(Arg, Js::OpCode::ProfiledArgOut_A, arg, reg);
  626. m_byteCodeData.Encode(&callSiteId, sizeof(Js::ProfileId));
  627. }
  628. else
  629. {
  630. MULTISIZE_LAYOUT_WRITE(Arg, op, arg, reg);
  631. return;
  632. }
  633. }
  634. template <typename SizePolicy>
  635. bool ByteCodeWriter::TryWriteArgNoSrc(OpCode op, ArgSlot arg)
  636. {
  637. OpLayoutT_ArgNoSrc<SizePolicy> layout;
  638. if (SizePolicy::Assign(layout.Arg, arg))
  639. {
  640. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  641. return true;
  642. }
  643. return false;
  644. }
  645. void ByteCodeWriter::ArgOutEnv(ArgSlot arg)
  646. {
  647. CheckOpen();
  648. Assert(OpCodeAttr::HasMultiSizeLayout(OpCode::ArgOut_Env));
  649. MULTISIZE_LAYOUT_WRITE(ArgNoSrc, OpCode::ArgOut_Env, arg);
  650. }
  651. void ByteCodeWriter::Br(ByteCodeLabel labelID)
  652. {
  653. Br(OpCode::Br, labelID);
  654. }
  655. // For switch case - default branching
  656. void ByteCodeWriter::Br(OpCode op, ByteCodeLabel labelID)
  657. {
  658. CheckOpen();
  659. CheckOp(op, OpLayoutType::Br);
  660. CheckLabel(labelID);
  661. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  662. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBr) - offsetof(OpLayoutBr, RelativeJumpOffset);
  663. OpLayoutBr data;
  664. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  665. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  666. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  667. }
  668. void ByteCodeWriter::BrS(OpCode op, ByteCodeLabel labelID, byte val)
  669. {
  670. CheckOpen();
  671. CheckOp(op, OpLayoutType::BrS);
  672. CheckLabel(labelID);
  673. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  674. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBrS) - offsetof(OpLayoutBrS, RelativeJumpOffset);
  675. OpLayoutBrS data;
  676. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  677. data.val = val;
  678. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  679. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  680. }
  681. template <typename SizePolicy>
  682. bool ByteCodeWriter::TryWriteBrReg1(OpCode op, ByteCodeLabel labelID, RegSlot R1)
  683. {
  684. OpLayoutT_BrReg1<SizePolicy> layout;
  685. if (SizePolicy::Assign(layout.R1, R1))
  686. {
  687. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutT_BrReg1<SizePolicy>) - offsetof(OpLayoutT_BrReg1<SizePolicy>, RelativeJumpOffset);
  688. layout.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  689. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  690. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  691. return true;
  692. }
  693. return false;
  694. }
  695. void ByteCodeWriter::BrReg1(OpCode op, ByteCodeLabel labelID, RegSlot R1)
  696. {
  697. CheckOpen();
  698. CheckOp(op, OpLayoutType::BrReg1);
  699. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  700. CheckLabel(labelID);
  701. R1 = ConsumeReg(R1);
  702. MULTISIZE_LAYOUT_WRITE(BrReg1, op, labelID, R1);
  703. }
  704. template <typename SizePolicy>
  705. bool ByteCodeWriter::TryWriteBrReg1Unsigned1(OpCode op, ByteCodeLabel labelID, RegSlot R1, uint C2)
  706. {
  707. OpLayoutT_BrReg1Unsigned1<SizePolicy> layout;
  708. if (SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.C2, C2))
  709. {
  710. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutT_BrReg2<SizePolicy>) - offsetof(OpLayoutT_BrReg2<SizePolicy>, RelativeJumpOffset);
  711. layout.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  712. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  713. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  714. return true;
  715. }
  716. return false;
  717. }
  718. void ByteCodeWriter::BrReg1Unsigned1(OpCode op, ByteCodeLabel labelID, RegSlot R1, uint C2)
  719. {
  720. CheckOpen();
  721. CheckOp(op, OpLayoutType::BrReg1Unsigned1);
  722. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  723. CheckLabel(labelID);
  724. R1 = ConsumeReg(R1);
  725. MULTISIZE_LAYOUT_WRITE(BrReg1Unsigned1, op, labelID, R1, C2);
  726. }
  727. template <typename SizePolicy>
  728. bool ByteCodeWriter::TryWriteBrReg2(OpCode op, ByteCodeLabel labelID, RegSlot R1, RegSlot R2)
  729. {
  730. OpLayoutT_BrReg2<SizePolicy> layout;
  731. if (SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2))
  732. {
  733. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutT_BrReg2<SizePolicy>) - offsetof(OpLayoutT_BrReg2<SizePolicy>, RelativeJumpOffset);
  734. layout.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  735. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  736. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  737. return true;
  738. }
  739. return false;
  740. }
  741. void ByteCodeWriter::BrReg2(OpCode op, ByteCodeLabel labelID, RegSlot R1, RegSlot R2)
  742. {
  743. CheckOpen();
  744. CheckOp(op, OpLayoutType::BrReg2);
  745. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  746. CheckLabel(labelID);
  747. R1 = ConsumeReg(R1);
  748. R2 = ConsumeReg(R2);
  749. MULTISIZE_LAYOUT_WRITE(BrReg2, op, labelID, R1, R2);
  750. }
  751. void ByteCodeWriter::BrProperty(OpCode op, ByteCodeLabel labelID, RegSlot instance, PropertyIdIndexType index)
  752. {
  753. CheckOpen();
  754. CheckOp(op, OpLayoutType::BrProperty);
  755. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  756. CheckLabel(labelID);
  757. instance = ConsumeReg(instance);
  758. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBrProperty) - offsetof(OpLayoutBrProperty, RelativeJumpOffset);
  759. OpLayoutBrProperty data;
  760. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  761. data.Instance = instance;
  762. data.PropertyIdIndex = index;
  763. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  764. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  765. }
  766. void ByteCodeWriter::BrLocalProperty(OpCode op, ByteCodeLabel labelID, PropertyIdIndexType index)
  767. {
  768. CheckOpen();
  769. CheckOp(op, OpLayoutType::BrLocalProperty);
  770. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  771. CheckLabel(labelID);
  772. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBrLocalProperty) - offsetof(OpLayoutBrLocalProperty, RelativeJumpOffset);
  773. OpLayoutBrLocalProperty data;
  774. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  775. data.PropertyIdIndex = index;
  776. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  777. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  778. }
  779. void ByteCodeWriter::BrEnvProperty(OpCode op, ByteCodeLabel labelID, PropertyIdIndexType index, int32 slotIndex)
  780. {
  781. CheckOpen();
  782. CheckOp(op, OpLayoutType::BrEnvProperty);
  783. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  784. CheckLabel(labelID);
  785. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBrEnvProperty) - offsetof(OpLayoutBrEnvProperty, RelativeJumpOffset);
  786. OpLayoutBrEnvProperty data;
  787. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  788. data.SlotIndex = slotIndex;
  789. data.PropertyIdIndex = index;
  790. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  791. AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
  792. }
  793. bool ByteCodeWriter::DoDynamicProfileOpcode(Phase tag, bool noHeuristics) const
  794. {
  795. #if ENABLE_PROFILE_INFO
  796. if (!DynamicProfileInfo::IsEnabled(tag, this->m_functionWrite))
  797. {
  798. return false;
  799. }
  800. // Other heuristics
  801. switch (tag)
  802. {
  803. case Phase::InlinePhase:
  804. // Do profile opcode everywhere if we are an inline candidate
  805. // Otherwise, only in loops if the function has loop
  806. #pragma prefast(suppress:6236, "DevDiv bug 830883. False positive when PHASE_OFF is #defined as '(false)'.")
  807. return PHASE_FORCE(Phase::InlinePhase, this->m_functionWrite) ||
  808. ((noHeuristics || !this->m_hasLoop || (this->m_loopNest != 0) ||
  809. !(PHASE_OFF(InlineOutsideLoopsPhase, this->m_functionWrite))));
  810. default:
  811. return true;
  812. }
  813. #else
  814. return false;
  815. #endif
  816. }
  817. bool ByteCodeWriter::ShouldIncrementCallSiteId(OpCode op)
  818. {
  819. if ((DoProfileCallOp(op) && DoDynamicProfileOpcode(InlinePhase)) ||
  820. (DoProfileNewScObjArrayOp(op) && (DoDynamicProfileOpcode(NativeArrayPhase, true) || DoDynamicProfileOpcode(InlinePhase, true))) ||
  821. (DoProfileNewScObjectOp(op) && (DoDynamicProfileOpcode(InlinePhase, true) || DoDynamicProfileOpcode(FixedNewObjPhase, true))))
  822. {
  823. return true;
  824. }
  825. return false;
  826. }
  827. void ByteCodeWriter::StartCall(OpCode op, ArgSlot ArgCount)
  828. {
  829. CheckOpen();
  830. CheckOp(op, OpLayoutType::StartCall);
  831. OpLayoutStartCall data;
  832. data.ArgCount = ArgCount;
  833. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  834. }
  835. template <typename SizePolicy>
  836. bool ByteCodeWriter::TryWriteCallIExtended(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, CallIExtendedOptions options, uint32 spreadArgsOffset)
  837. {
  838. OpLayoutT_CallIExtended<SizePolicy> layout;
  839. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  840. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.Options, options)
  841. && SizePolicy::Assign(layout.SpreadAuxOffset, spreadArgsOffset))
  842. {
  843. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  844. return true;
  845. }
  846. return false;
  847. }
  848. template <typename SizePolicy>
  849. bool ByteCodeWriter::TryWriteCallIExtendedWithICIndex(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, InlineCacheIndex inlineCacheIndex, bool isRootLoad, CallIExtendedOptions options, uint32 spreadArgsOffset)
  850. {
  851. OpLayoutT_CallIExtendedWithICIndex<SizePolicy> layout;
  852. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  853. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.inlineCacheIndex, inlineCacheIndex)
  854. && SizePolicy::Assign(layout.Options, options) && SizePolicy::Assign(layout.SpreadAuxOffset, spreadArgsOffset))
  855. {
  856. size_t offset = m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  857. if (isRootLoad)
  858. {
  859. Assert(m_byteCodeData.GetCurrentOffset() == offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum) + sizeof(OpLayoutT_CallIExtendedWithICIndex<SizePolicy>));
  860. size_t inlineCacheOffset = offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum)
  861. + offsetof(OpLayoutT_CallIExtendedWithICIndex<SizePolicy>, inlineCacheIndex);
  862. rootObjectLoadMethodInlineCacheOffsets.Prepend(m_labelOffsets->GetAllocator(), inlineCacheOffset);
  863. }
  864. return true;
  865. }
  866. return false;
  867. }
  868. template <typename SizePolicy>
  869. bool ByteCodeWriter::TryWriteCallIExtendedFlags(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, CallIExtendedOptions options, uint32 spreadArgsOffset, CallFlags callFlags)
  870. {
  871. OpLayoutT_CallIExtendedFlags<SizePolicy> layout;
  872. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  873. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.Options, options)
  874. && SizePolicy::Assign(layout.SpreadAuxOffset, spreadArgsOffset) && SizePolicy::Assign(layout.callFlags, callFlags))
  875. {
  876. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  877. return true;
  878. }
  879. return false;
  880. }
  881. template <typename SizePolicy>
  882. bool ByteCodeWriter::TryWriteCallIExtendedFlagsWithICIndex(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, InlineCacheIndex inlineCacheIndex, bool isRootLoad, CallIExtendedOptions options, uint32 spreadArgsOffset, CallFlags callFlags)
  883. {
  884. OpLayoutT_CallIExtendedFlagsWithICIndex<SizePolicy> layout;
  885. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  886. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.inlineCacheIndex, inlineCacheIndex)
  887. && SizePolicy::Assign(layout.Options, options) && SizePolicy::Assign(layout.SpreadAuxOffset, spreadArgsOffset)
  888. && SizePolicy::Assign(layout.callFlags, callFlags))
  889. {
  890. size_t offset = m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  891. if (isRootLoad)
  892. {
  893. Assert(m_byteCodeData.GetCurrentOffset() == offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum) + sizeof(OpLayoutT_CallIExtendedFlagsWithICIndex<SizePolicy>));
  894. size_t inlineCacheOffset = offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum)
  895. + offsetof(OpLayoutT_CallIExtendedFlagsWithICIndex<SizePolicy>, inlineCacheIndex);
  896. rootObjectLoadMethodInlineCacheOffsets.Prepend(m_labelOffsets->GetAllocator(), inlineCacheOffset);
  897. }
  898. return true;
  899. }
  900. return false;
  901. }
  902. void ByteCodeWriter::CallIExtended(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, CallIExtendedOptions options, const void *buffer, uint byteCount, ProfileId callSiteId, CallFlags callFlags)
  903. {
  904. CheckOpen();
  905. bool hasCallFlags = !(callFlags == CallFlags_None);
  906. if (hasCallFlags)
  907. {
  908. CheckOp(op, OpLayoutType::CallIExtendedFlags);
  909. }
  910. else
  911. {
  912. CheckOp(op, OpLayoutType::CallIExtended);
  913. }
  914. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  915. // givenArgCount could be <, ==, or > than Function's "InParams" count
  916. if (returnValueRegister != Js::Constants::NoRegister)
  917. {
  918. returnValueRegister = ConsumeReg(returnValueRegister);
  919. }
  920. functionRegister = ConsumeReg(functionRegister);
  921. // CallISpread is not going to use the ldFld cache index, but still remove it from the map as we expect
  922. // the entry for a cache index to be removed once we have seen the corresponding call.
  923. CacheIdUnit unit;
  924. unit.cacheId = Js::Constants::NoInlineCacheIndex;
  925. callRegToLdFldCacheIndexMap->TryGetValueAndRemove(functionRegister, &unit);
  926. bool isProfiled = false, isProfiled2 = false;
  927. ProfileId profileId = callSiteId, profileId2 = Constants::NoProfileId;
  928. bool isCallWithICIndex = false;
  929. if (DoProfileCallOp(op))
  930. {
  931. if (DoDynamicProfileOpcode(InlinePhase) &&
  932. callSiteId != Js::Constants::NoProfileId)
  933. {
  934. op = Js::OpCodeUtil::ConvertCallOpToProfiled(op);
  935. isProfiled = true;
  936. }
  937. else if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) || DoDynamicProfileOpcode(FloatTypeSpecPhase)) &&
  938. this->m_functionWrite->AllocProfiledReturnTypeId(&profileId))
  939. {
  940. op = Js::OpCodeUtil::ConvertCallOpToProfiledReturnType(op);
  941. isProfiled = true;
  942. }
  943. }
  944. else if (DoProfileNewScObjArrayOp(op) &&
  945. (DoDynamicProfileOpcode(NativeArrayPhase, true) || DoDynamicProfileOpcode(InlinePhase, true)) &&
  946. callSiteId != Js::Constants::NoProfileId &&
  947. this->m_functionWrite->AllocProfiledArrayCallSiteId(&profileId2))
  948. {
  949. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  950. isProfiled = true;
  951. isProfiled2 = true;
  952. }
  953. else if (DoProfileNewScObjectOp(op) && (DoDynamicProfileOpcode(InlinePhase, true) || DoDynamicProfileOpcode(FixedNewObjPhase, true)) &&
  954. callSiteId != Js::Constants::NoProfileId)
  955. {
  956. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  957. isProfiled = true;
  958. }
  959. uint spreadArgsOffset = 0;
  960. if (options & CallIExtended_SpreadArgs)
  961. {
  962. Assert(buffer != nullptr && byteCount > 0);
  963. spreadArgsOffset = InsertAuxiliaryData(buffer, byteCount);
  964. }
  965. if (isCallWithICIndex)
  966. {
  967. if (hasCallFlags == true)
  968. {
  969. MULTISIZE_LAYOUT_WRITE(CallIExtendedFlagsWithICIndex, op, returnValueRegister, functionRegister, givenArgCount, unit.cacheId, unit.isRootObjectCache, options, spreadArgsOffset, callFlags);
  970. }
  971. else
  972. {
  973. MULTISIZE_LAYOUT_WRITE(CallIExtendedWithICIndex, op, returnValueRegister, functionRegister, givenArgCount, unit.cacheId, unit.isRootObjectCache, options, spreadArgsOffset);
  974. }
  975. }
  976. else
  977. {
  978. if (hasCallFlags == true)
  979. {
  980. MULTISIZE_LAYOUT_WRITE(CallIExtendedFlags, op, returnValueRegister, functionRegister, givenArgCount, options, spreadArgsOffset, callFlags);
  981. }
  982. else
  983. {
  984. MULTISIZE_LAYOUT_WRITE(CallIExtended, op, returnValueRegister, functionRegister, givenArgCount, options, spreadArgsOffset);
  985. }
  986. }
  987. if (isProfiled)
  988. {
  989. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  990. if (isProfiled2)
  991. {
  992. m_byteCodeData.Encode(&profileId2, sizeof(Js::ProfileId));
  993. }
  994. }
  995. }
  996. template <typename SizePolicy>
  997. bool ByteCodeWriter::TryWriteCallIWithICIndex(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, InlineCacheIndex inlineCacheIndex, bool isRootLoad)
  998. {
  999. OpLayoutT_CallIWithICIndex<SizePolicy> layout;
  1000. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  1001. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.inlineCacheIndex, inlineCacheIndex))
  1002. {
  1003. size_t offset = m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1004. if (isRootLoad)
  1005. {
  1006. Assert(m_byteCodeData.GetCurrentOffset() == offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum) + sizeof(OpLayoutT_CallIWithICIndex<SizePolicy>));
  1007. size_t inlineCacheOffset = offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum)
  1008. + offsetof(OpLayoutT_CallIWithICIndex<SizePolicy>, inlineCacheIndex);
  1009. rootObjectLoadMethodInlineCacheOffsets.Prepend(m_labelOffsets->GetAllocator(), inlineCacheOffset);
  1010. }
  1011. return true;
  1012. }
  1013. return false;
  1014. }
  1015. template <typename SizePolicy>
  1016. bool ByteCodeWriter::TryWriteCallIFlagsWithICIndex(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, InlineCacheIndex inlineCacheIndex, bool isRootLoad, CallFlags callFlags)
  1017. {
  1018. OpLayoutT_CallIFlagsWithICIndex<SizePolicy> layout;
  1019. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  1020. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.inlineCacheIndex, inlineCacheIndex)
  1021. && SizePolicy::Assign(layout.callFlags, callFlags))
  1022. {
  1023. size_t offset = m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1024. if (isRootLoad)
  1025. {
  1026. Assert(m_byteCodeData.GetCurrentOffset() == offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum) + sizeof(OpLayoutT_CallIFlagsWithICIndex<SizePolicy>));
  1027. size_t inlineCacheOffset = offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum)
  1028. + offsetof(OpLayoutT_CallIFlagsWithICIndex<SizePolicy>, inlineCacheIndex);
  1029. rootObjectLoadMethodInlineCacheOffsets.Prepend(m_labelOffsets->GetAllocator(), inlineCacheOffset);
  1030. }
  1031. return true;
  1032. }
  1033. return false;
  1034. }
  1035. template <typename SizePolicy>
  1036. bool ByteCodeWriter::TryWriteCallI(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount)
  1037. {
  1038. OpLayoutT_CallI<SizePolicy> layout;
  1039. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  1040. && SizePolicy::Assign(layout.ArgCount, givenArgCount))
  1041. {
  1042. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1043. return true;
  1044. }
  1045. return false;
  1046. }
  1047. template <typename SizePolicy>
  1048. bool ByteCodeWriter::TryWriteCallIFlags(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, CallFlags callFlags)
  1049. {
  1050. OpLayoutT_CallIFlags<SizePolicy> layout;
  1051. if (SizePolicy::Assign(layout.Return, returnValueRegister) && SizePolicy::Assign(layout.Function, functionRegister)
  1052. && SizePolicy::Assign(layout.ArgCount, givenArgCount) && SizePolicy::Assign(layout.callFlags, callFlags))
  1053. {
  1054. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1055. return true;
  1056. }
  1057. return false;
  1058. }
  1059. void ByteCodeWriter::RemoveEntryForRegSlotFromCacheIdMap(RegSlot regSlot)
  1060. {
  1061. regSlot = ConsumeReg(regSlot);
  1062. CacheIdUnit unit;
  1063. unit.cacheId = Js::Constants::NoInlineCacheIndex;
  1064. callRegToLdFldCacheIndexMap->TryGetValueAndRemove(regSlot, &unit);
  1065. }
  1066. void ByteCodeWriter::CallI(OpCode op, RegSlot returnValueRegister, RegSlot functionRegister, ArgSlot givenArgCount, ProfileId callSiteId, CallFlags callFlags)
  1067. {
  1068. CheckOpen();
  1069. bool hasCallFlags = !(callFlags == CallFlags_None);
  1070. if (hasCallFlags == true)
  1071. {
  1072. CheckOp(op, OpLayoutType::CallIFlags);
  1073. }
  1074. else
  1075. {
  1076. CheckOp(op, OpLayoutType::CallI);
  1077. }
  1078. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1079. // givenArgCount could be <, ==, or > than Function's "InParams" count
  1080. if (returnValueRegister != Js::Constants::NoRegister)
  1081. {
  1082. returnValueRegister = ConsumeReg(returnValueRegister);
  1083. }
  1084. functionRegister = ConsumeReg(functionRegister);
  1085. bool isProfiled = false;
  1086. bool isProfiled2 = false;
  1087. bool isCallWithICIndex = false;
  1088. ProfileId profileId = callSiteId;
  1089. ProfileId profileId2 = Constants::NoProfileId;
  1090. CacheIdUnit unit;
  1091. unit.cacheId = Js::Constants::NoInlineCacheIndex;
  1092. callRegToLdFldCacheIndexMap->TryGetValueAndRemove(functionRegister, &unit);
  1093. if (DoProfileCallOp(op))
  1094. {
  1095. if (DoDynamicProfileOpcode(InlinePhase) &&
  1096. callSiteId != Js::Constants::NoProfileId)
  1097. {
  1098. if (unit.cacheId == Js::Constants::NoInlineCacheIndex)
  1099. {
  1100. op = Js::OpCodeUtil::ConvertCallOpToProfiled(op);
  1101. }
  1102. else
  1103. {
  1104. isCallWithICIndex = true;
  1105. op = Js::OpCodeUtil::ConvertCallOpToProfiled(op, true);
  1106. }
  1107. isProfiled = true;
  1108. }
  1109. else if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) || DoDynamicProfileOpcode(FloatTypeSpecPhase)) &&
  1110. this->m_functionWrite->AllocProfiledReturnTypeId(&profileId))
  1111. {
  1112. op = Js::OpCodeUtil::ConvertCallOpToProfiledReturnType(op);
  1113. isProfiled = true;
  1114. }
  1115. }
  1116. else if (DoProfileNewScObjArrayOp(op) &&
  1117. (DoDynamicProfileOpcode(NativeArrayPhase, true) || DoDynamicProfileOpcode(InlinePhase, true)) &&
  1118. callSiteId != Js::Constants::NoProfileId &&
  1119. this->m_functionWrite->AllocProfiledArrayCallSiteId(&profileId2))
  1120. {
  1121. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1122. isProfiled = true;
  1123. isProfiled2 = true;
  1124. }
  1125. else if (DoProfileNewScObjectOp(op) &&
  1126. (DoDynamicProfileOpcode(InlinePhase, true) || DoDynamicProfileOpcode(FixedNewObjPhase, true)) &&
  1127. callSiteId != Js::Constants::NoProfileId)
  1128. {
  1129. if (unit.cacheId == Js::Constants::NoInlineCacheIndex)
  1130. {
  1131. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1132. }
  1133. else
  1134. {
  1135. isCallWithICIndex = true;
  1136. OpCodeUtil::ConvertNonCallOpToProfiledWithICIndex(op);
  1137. }
  1138. isProfiled = true;
  1139. }
  1140. if (isCallWithICIndex)
  1141. {
  1142. if (hasCallFlags == true)
  1143. {
  1144. MULTISIZE_LAYOUT_WRITE(CallIFlagsWithICIndex, op, returnValueRegister, functionRegister, givenArgCount, unit.cacheId, unit.isRootObjectCache, callFlags);
  1145. }
  1146. else
  1147. {
  1148. MULTISIZE_LAYOUT_WRITE(CallIWithICIndex, op, returnValueRegister, functionRegister, givenArgCount, unit.cacheId, unit.isRootObjectCache);
  1149. }
  1150. }
  1151. else
  1152. {
  1153. if (hasCallFlags == true)
  1154. {
  1155. MULTISIZE_LAYOUT_WRITE(CallIFlags, op, returnValueRegister, functionRegister, givenArgCount, callFlags);
  1156. }
  1157. else
  1158. {
  1159. MULTISIZE_LAYOUT_WRITE(CallI, op, returnValueRegister, functionRegister, givenArgCount);
  1160. }
  1161. }
  1162. if (isProfiled)
  1163. {
  1164. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1165. if (isProfiled2)
  1166. {
  1167. m_byteCodeData.Encode(&profileId2, sizeof(Js::ProfileId));
  1168. }
  1169. }
  1170. }
  1171. template <typename SizePolicy>
  1172. bool ByteCodeWriter::TryWriteElementI(OpCode op, RegSlot Value, RegSlot Instance, RegSlot Element)
  1173. {
  1174. OpLayoutT_ElementI<SizePolicy> layout;
  1175. if (SizePolicy::Assign(layout.Value, Value) && SizePolicy::Assign(layout.Instance, Instance)
  1176. && SizePolicy::Assign(layout.Element, Element))
  1177. {
  1178. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1179. return true;
  1180. }
  1181. return false;
  1182. }
  1183. void ByteCodeWriter::Element(OpCode op, RegSlot Value, RegSlot Instance, RegSlot Element, bool instanceAtReturnRegOK, bool forceStrictMode)
  1184. {
  1185. CheckOpen();
  1186. CheckOp(op, OpLayoutType::ElementI);
  1187. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1188. Value = ConsumeReg(Value);
  1189. Instance = ConsumeReg(Instance);
  1190. Element = ConsumeReg(Element);
  1191. if (this->m_functionWrite->GetIsStrictMode() || forceStrictMode)
  1192. {
  1193. if (op == OpCode::DeleteElemI_A)
  1194. {
  1195. op = OpCode::DeleteElemIStrict_A;
  1196. }
  1197. }
  1198. bool isProfiledLayout = false;
  1199. Js::ProfileId profileId = Js::Constants::NoProfileId;
  1200. Assert(instanceAtReturnRegOK || Instance != 0);
  1201. if (DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1202. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1203. DoDynamicProfileOpcode(TypedArrayTypeSpecPhase) ||
  1204. DoDynamicProfileOpcode(ArrayCheckHoistPhase))
  1205. {
  1206. OpCode newop;
  1207. switch (op)
  1208. {
  1209. case OpCode::LdElemI_A:
  1210. newop = OpCode::ProfiledLdElemI_A;
  1211. if (this->m_functionWrite->AllocProfiledLdElemId(&profileId))
  1212. {
  1213. isProfiledLayout = true;
  1214. op = newop;
  1215. }
  1216. break;
  1217. case Js::OpCode::StElemI_A:
  1218. newop = OpCode::ProfiledStElemI_A;
  1219. goto StoreCommon;
  1220. case Js::OpCode::StElemI_A_Strict:
  1221. newop = OpCode::ProfiledStElemI_A_Strict;
  1222. StoreCommon:
  1223. if (this->m_functionWrite->AllocProfiledStElemId(&profileId))
  1224. {
  1225. isProfiledLayout = true;
  1226. op = newop;
  1227. }
  1228. break;
  1229. }
  1230. }
  1231. MULTISIZE_LAYOUT_WRITE(ElementI, op, Value, Instance, Element);
  1232. if (isProfiledLayout)
  1233. {
  1234. Assert(profileId != Js::Constants::NoProfileId);
  1235. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1236. }
  1237. }
  1238. template <typename SizePolicy>
  1239. bool ByteCodeWriter::TryWriteElementUnsigned1(OpCode op, RegSlot Value, RegSlot Instance, uint32 Element)
  1240. {
  1241. OpLayoutT_ElementUnsigned1<SizePolicy> layout;
  1242. if (SizePolicy::Assign(layout.Value, Value) && SizePolicy::Assign(layout.Instance, Instance)
  1243. && SizePolicy::Assign(layout.Element, Element))
  1244. {
  1245. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. void ByteCodeWriter::ElementUnsigned1(OpCode op, RegSlot Value, RegSlot Instance, uint32 Element)
  1251. {
  1252. CheckOpen();
  1253. CheckOp(op, OpLayoutType::ElementUnsigned1);
  1254. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1255. Value = ConsumeReg(Value);
  1256. Instance = ConsumeReg(Instance);
  1257. MULTISIZE_LAYOUT_WRITE(ElementUnsigned1, op, Value, Instance, Element);
  1258. }
  1259. template <typename SizePolicy>
  1260. bool ByteCodeWriter::TryWriteElementScopedC(OpCode op, RegSlot value, PropertyIdIndexType propertyIdIndex)
  1261. {
  1262. OpLayoutT_ElementScopedC<SizePolicy> layout;
  1263. if (SizePolicy::Assign(layout.Value, value)
  1264. && SizePolicy::Assign(layout.PropertyIdIndex, propertyIdIndex))
  1265. {
  1266. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1267. return true;
  1268. }
  1269. return false;
  1270. }
  1271. void ByteCodeWriter::ScopedProperty(OpCode op, RegSlot value, PropertyIdIndexType propertyIdIndex, bool forceStrictMode)
  1272. {
  1273. CheckOpen();
  1274. CheckOp(op, OpLayoutType::ElementScopedC);
  1275. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1276. value = ConsumeReg(value);
  1277. #if DBG
  1278. switch (op)
  1279. {
  1280. case OpCode::ScopedDeleteFld:
  1281. case OpCode::ScopedEnsureNoRedeclFld:
  1282. case OpCode::ScopedInitFunc:
  1283. break;
  1284. default:
  1285. AssertMsg(false, "The specified OpCode is not intended for scoped field-access");
  1286. break;
  1287. }
  1288. #endif
  1289. if (this->m_functionWrite->GetIsStrictMode() || forceStrictMode)
  1290. {
  1291. if (op == OpCode::ScopedDeleteFld)
  1292. {
  1293. op = OpCode::ScopedDeleteFldStrict;
  1294. }
  1295. }
  1296. MULTISIZE_LAYOUT_WRITE(ElementScopedC, op, value, propertyIdIndex);
  1297. }
  1298. template <typename SizePolicy>
  1299. bool ByteCodeWriter::TryWriteElementC(OpCode op, RegSlot value, RegSlot instance, PropertyIdIndexType propertyIdIndex)
  1300. {
  1301. OpLayoutT_ElementC<SizePolicy> layout;
  1302. if (SizePolicy::Assign(layout.Value, value) && SizePolicy::Assign(layout.Instance, instance)
  1303. && SizePolicy::Assign(layout.PropertyIdIndex, propertyIdIndex))
  1304. {
  1305. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. void ByteCodeWriter::Property(OpCode op, RegSlot value, RegSlot instance, PropertyIdIndexType propertyIdIndex, bool forceStrictMode)
  1311. {
  1312. CheckOpen();
  1313. CheckOp(op, OpLayoutType::ElementC);
  1314. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1315. value = ConsumeReg(value);
  1316. instance = ConsumeReg(instance);
  1317. #if DBG
  1318. switch (op)
  1319. {
  1320. case OpCode::InitSetFld:
  1321. case OpCode::InitGetFld:
  1322. case OpCode::InitClassMemberGet:
  1323. case OpCode::InitClassMemberSet:
  1324. case OpCode::InitProto:
  1325. case OpCode::DeleteFld:
  1326. case OpCode::DeleteFld_ReuseLoc:
  1327. case OpCode::DeleteRootFld:
  1328. case OpCode::LdElemUndefScoped:
  1329. case OpCode::StFuncExpr:
  1330. break;
  1331. default:
  1332. AssertMsg(false, "The specified OpCode is not intended for field-access");
  1333. break;
  1334. }
  1335. #endif
  1336. if (this->m_functionWrite->GetIsStrictMode() || forceStrictMode)
  1337. {
  1338. if (op == OpCode::DeleteFld)
  1339. {
  1340. op = OpCode::DeleteFldStrict;
  1341. }
  1342. else if (op == OpCode::DeleteRootFld)
  1343. {
  1344. // We will reach here when in the language service mode, since in that mode we have skipped that error.
  1345. op = OpCode::DeleteRootFldStrict;
  1346. }
  1347. }
  1348. MULTISIZE_LAYOUT_WRITE(ElementC, op, value, instance, propertyIdIndex);
  1349. }
  1350. template <typename SizePolicy>
  1351. bool ByteCodeWriter::TryWriteElementSlot(OpCode op, RegSlot value, RegSlot instance, uint32 slotId)
  1352. {
  1353. OpLayoutT_ElementSlot<SizePolicy> layout;
  1354. if (SizePolicy::Assign(layout.Value, value) && SizePolicy::Assign(layout.Instance, instance)
  1355. && SizePolicy::Assign(layout.SlotIndex, slotId))
  1356. {
  1357. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1358. return true;
  1359. }
  1360. return false;
  1361. }
  1362. void ByteCodeWriter::Slot(OpCode op, RegSlot value, RegSlot instance, uint32 slotId)
  1363. {
  1364. CheckOpen();
  1365. CheckOp(op, OpLayoutType::ElementSlot);
  1366. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1367. value = ConsumeReg(value);
  1368. instance = ConsumeReg(instance);
  1369. #if DBG
  1370. switch (op)
  1371. {
  1372. #if ENABLE_NATIVE_CODEGEN
  1373. case OpCode::LdSlotArr:
  1374. case OpCode::StSlot:
  1375. case OpCode::StSlotChkUndecl:
  1376. #endif
  1377. case OpCode::StObjSlot:
  1378. case OpCode::StObjSlotChkUndecl:
  1379. case OpCode::StPropIdArrFromVar:
  1380. break;
  1381. default:
  1382. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1383. break;
  1384. }
  1385. #endif
  1386. MULTISIZE_LAYOUT_WRITE(ElementSlot, op, value, instance, slotId);
  1387. }
  1388. void ByteCodeWriter::Slot(OpCode op, RegSlot value, RegSlot instance, uint32 slotId, ProfileId profileId)
  1389. {
  1390. CheckOpen();
  1391. CheckOp(op, OpLayoutType::ElementSlot);
  1392. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1393. value = ConsumeReg(value);
  1394. instance = ConsumeReg(instance);
  1395. switch (op)
  1396. {
  1397. case OpCode::LdSlot:
  1398. case OpCode::LdObjSlot:
  1399. if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) || DoDynamicProfileOpcode(FloatTypeSpecPhase)) &&
  1400. profileId != Constants::NoProfileId)
  1401. {
  1402. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1403. }
  1404. break;
  1405. default:
  1406. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1407. break;
  1408. }
  1409. MULTISIZE_LAYOUT_WRITE(ElementSlot, op, value, instance, slotId);
  1410. if (OpCodeAttr::IsProfiledOp(op))
  1411. {
  1412. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1413. }
  1414. }
  1415. template <typename SizePolicy>
  1416. bool ByteCodeWriter::TryWriteElementSlotI1(OpCode op, RegSlot value, uint32 slotId)
  1417. {
  1418. OpLayoutT_ElementSlotI1<SizePolicy> layout;
  1419. if (SizePolicy::Assign(layout.Value, value)
  1420. && SizePolicy::Assign(layout.SlotIndex, slotId))
  1421. {
  1422. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1423. return true;
  1424. }
  1425. return false;
  1426. }
  1427. void ByteCodeWriter::SlotI1(OpCode op, RegSlot value, uint32 slotId)
  1428. {
  1429. CheckOpen();
  1430. CheckOp(op, OpLayoutType::ElementSlotI1);
  1431. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1432. value = ConsumeReg(value);
  1433. #if DBG
  1434. switch (op)
  1435. {
  1436. case OpCode::LdEnvObj:
  1437. case OpCode::LdEnvObj_ReuseLoc:
  1438. case OpCode::StLocalSlot:
  1439. case OpCode::StParamSlot:
  1440. case OpCode::StLocalObjSlot:
  1441. case OpCode::StParamObjSlot:
  1442. case OpCode::StLocalSlotChkUndecl:
  1443. case OpCode::StParamSlotChkUndecl:
  1444. case OpCode::StLocalObjSlotChkUndecl:
  1445. case OpCode::StParamObjSlotChkUndecl:
  1446. {
  1447. break;
  1448. }
  1449. default:
  1450. {
  1451. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1452. break;
  1453. }
  1454. }
  1455. #endif
  1456. MULTISIZE_LAYOUT_WRITE(ElementSlotI1, op, value, slotId);
  1457. }
  1458. void ByteCodeWriter::SlotI1(OpCode op, RegSlot value, uint32 slotId, ProfileId profileId)
  1459. {
  1460. CheckOpen();
  1461. CheckOp(op, OpLayoutType::ElementSlotI1);
  1462. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1463. value = ConsumeReg(value);
  1464. switch (op)
  1465. {
  1466. case OpCode::LdLocalSlot:
  1467. case OpCode::LdParamSlot:
  1468. case OpCode::LdLocalObjSlot:
  1469. case OpCode::LdParamObjSlot:
  1470. if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) || DoDynamicProfileOpcode(FloatTypeSpecPhase)) &&
  1471. profileId != Constants::NoProfileId)
  1472. {
  1473. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1474. }
  1475. break;
  1476. default:
  1477. {
  1478. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1479. break;
  1480. }
  1481. }
  1482. MULTISIZE_LAYOUT_WRITE(ElementSlotI1, op, value, slotId);
  1483. if (OpCodeAttr::IsProfiledOp(op))
  1484. {
  1485. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1486. }
  1487. }
  1488. template <typename SizePolicy>
  1489. bool ByteCodeWriter::TryWriteElementSlotI2(OpCode op, RegSlot value, uint32 slotId1, uint32 slotId2)
  1490. {
  1491. OpLayoutT_ElementSlotI2<SizePolicy> layout;
  1492. if (SizePolicy::Assign(layout.Value, value)
  1493. && SizePolicy::Assign(layout.SlotIndex1, slotId1)
  1494. && SizePolicy::Assign(layout.SlotIndex2, slotId2))
  1495. {
  1496. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1497. return true;
  1498. }
  1499. return false;
  1500. }
  1501. void ByteCodeWriter::SlotI2(OpCode op, RegSlot value, uint32 slotId1, uint32 slotId2)
  1502. {
  1503. CheckOpen();
  1504. CheckOp(op, OpLayoutType::ElementSlotI2);
  1505. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1506. value = ConsumeReg(value);
  1507. #if DBG
  1508. switch (op)
  1509. {
  1510. case OpCode::StInnerSlot:
  1511. case OpCode::StInnerSlotChkUndecl:
  1512. case OpCode::StInnerObjSlot:
  1513. case OpCode::StInnerObjSlotChkUndecl:
  1514. case OpCode::StEnvSlot:
  1515. case OpCode::StEnvSlotChkUndecl:
  1516. case OpCode::StEnvObjSlot:
  1517. case OpCode::StEnvObjSlotChkUndecl:
  1518. case OpCode::StModuleSlot:
  1519. case OpCode::LdModuleSlot:
  1520. {
  1521. break;
  1522. }
  1523. default:
  1524. {
  1525. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1526. break;
  1527. }
  1528. }
  1529. #endif
  1530. MULTISIZE_LAYOUT_WRITE(ElementSlotI2, op, value, slotId1, slotId2);
  1531. }
  1532. void ByteCodeWriter::SlotI2(OpCode op, RegSlot value, uint32 slotId1, uint32 slotId2, ProfileId profileId)
  1533. {
  1534. CheckOpen();
  1535. CheckOp(op, OpLayoutType::ElementSlotI2);
  1536. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1537. value = ConsumeReg(value);
  1538. switch (op)
  1539. {
  1540. case OpCode::LdInnerSlot:
  1541. case OpCode::LdInnerObjSlot:
  1542. case OpCode::LdEnvSlot:
  1543. case OpCode::LdEnvObjSlot:
  1544. case OpCode::LdModuleSlot:
  1545. if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) || DoDynamicProfileOpcode(FloatTypeSpecPhase)) &&
  1546. profileId != Constants::NoProfileId)
  1547. {
  1548. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1549. }
  1550. break;
  1551. default:
  1552. {
  1553. AssertMsg(false, "The specified OpCode is not intended for slot access");
  1554. break;
  1555. }
  1556. }
  1557. MULTISIZE_LAYOUT_WRITE(ElementSlotI2, op, value, slotId1, slotId2);
  1558. if (OpCodeAttr::IsProfiledOp(op))
  1559. {
  1560. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1561. }
  1562. }
  1563. template <typename SizePolicy>
  1564. bool ByteCodeWriter::TryWriteElementSlotI3(OpCode op, RegSlot value, RegSlot instance, uint32 slotId, RegSlot homeObj)
  1565. {
  1566. OpLayoutT_ElementSlotI3<SizePolicy> layout;
  1567. if (SizePolicy::Assign(layout.Value, value)
  1568. && SizePolicy::Assign(layout.Instance, instance)
  1569. && SizePolicy::Assign(layout.SlotIndex, slotId)
  1570. && SizePolicy::Assign(layout.HomeObj, homeObj))
  1571. {
  1572. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1573. return true;
  1574. }
  1575. return false;
  1576. }
  1577. template <typename SizePolicy>
  1578. bool ByteCodeWriter::TryWriteElementU(OpCode op, RegSlot instance, PropertyIdIndexType index)
  1579. {
  1580. OpLayoutT_ElementU<SizePolicy> layout;
  1581. if (SizePolicy::Assign(layout.Instance, instance) && SizePolicy::Assign(layout.PropertyIdIndex, index))
  1582. {
  1583. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1584. return true;
  1585. }
  1586. return false;
  1587. }
  1588. void ByteCodeWriter::ElementU(OpCode op, RegSlot instance, PropertyIdIndexType index)
  1589. {
  1590. CheckOpen();
  1591. CheckOp(op, OpLayoutType::ElementU);
  1592. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1593. instance = ConsumeReg(instance);
  1594. MULTISIZE_LAYOUT_WRITE(ElementU, op, instance, index);
  1595. }
  1596. template <typename SizePolicy>
  1597. bool ByteCodeWriter::TryWriteElementScopedU(OpCode op, PropertyIdIndexType index)
  1598. {
  1599. OpLayoutT_ElementScopedU<SizePolicy> layout;
  1600. if (SizePolicy::Assign(layout.PropertyIdIndex, index))
  1601. {
  1602. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1603. return true;
  1604. }
  1605. return false;
  1606. }
  1607. void ByteCodeWriter::ElementScopedU(OpCode op, PropertyIdIndexType index)
  1608. {
  1609. CheckOpen();
  1610. CheckOp(op, OpLayoutType::ElementScopedU);
  1611. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1612. MULTISIZE_LAYOUT_WRITE(ElementScopedU, op, index);
  1613. }
  1614. template <typename SizePolicy>
  1615. bool ByteCodeWriter::TryWriteElementRootU(OpCode op, PropertyIdIndexType index)
  1616. {
  1617. OpLayoutT_ElementRootU<SizePolicy> layout;
  1618. if (SizePolicy::Assign(layout.PropertyIdIndex, index))
  1619. {
  1620. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1621. return true;
  1622. }
  1623. return false;
  1624. }
  1625. void ByteCodeWriter::ElementRootU(OpCode op, PropertyIdIndexType index)
  1626. {
  1627. CheckOpen();
  1628. CheckOp(op, OpLayoutType::ElementRootU);
  1629. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1630. MULTISIZE_LAYOUT_WRITE(ElementRootU, op, index);
  1631. }
  1632. template <typename SizePolicy>
  1633. bool ByteCodeWriter::TryWriteElementRootCP(OpCode op, RegSlot value, uint cacheId, bool isLoadMethod, bool isStore)
  1634. {
  1635. Assert(!isLoadMethod || !isStore);
  1636. OpLayoutT_ElementRootCP<SizePolicy> layout;
  1637. if (SizePolicy::Assign(layout.Value, value) && SizePolicy::Assign(layout.inlineCacheIndex, cacheId))
  1638. {
  1639. size_t offset = m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1640. Assert(m_byteCodeData.GetCurrentOffset() == offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum) + sizeof(OpLayoutT_ElementRootCP<SizePolicy>));
  1641. size_t inlineCacheOffset = offset + OpCodeUtil::EncodedSize(op, SizePolicy::LayoutEnum)
  1642. + offsetof(OpLayoutT_ElementRootCP<SizePolicy>, inlineCacheIndex);
  1643. // Root object inline cache index are given out from 0, but it will be at index after
  1644. // all the plain inline cache. Store the offset of the inline cache index to patch it up later.
  1645. SListBase<size_t> * rootObjectInlineCacheOffsets = isStore ?
  1646. &rootObjectStoreInlineCacheOffsets : isLoadMethod ? &rootObjectLoadMethodInlineCacheOffsets : &rootObjectLoadInlineCacheOffsets;
  1647. rootObjectInlineCacheOffsets->Prepend(this->m_labelOffsets->GetAllocator(), inlineCacheOffset);
  1648. return true;
  1649. }
  1650. return false;
  1651. }
  1652. void ByteCodeWriter::PatchableRootProperty(OpCode op, RegSlot value, uint cacheId, bool isLoadMethod, bool isStore, bool registerCacheIdForCall)
  1653. {
  1654. CheckOpen();
  1655. CheckOp(op, OpLayoutType::ElementRootCP);
  1656. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1657. Assert(!isLoadMethod || !isStore);
  1658. value = ConsumeReg(value);
  1659. switch (op)
  1660. {
  1661. case OpCode::LdRootFld:
  1662. case OpCode::LdRootFldForTypeOf:
  1663. if (DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1664. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1665. DoDynamicProfileOpcode(ObjTypeSpecPhase) ||
  1666. DoDynamicProfileOpcode(InlinePhase) ||
  1667. DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase))
  1668. {
  1669. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1670. }
  1671. break;
  1672. case OpCode::LdRootMethodFld:
  1673. if (registerCacheIdForCall)
  1674. {
  1675. CacheIdUnit unit(cacheId, true);
  1676. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1677. callRegToLdFldCacheIndexMap->Add(value, unit);
  1678. }
  1679. case OpCode::StRootFld:
  1680. case OpCode::StRootFldStrict:
  1681. case OpCode::InitRootFld:
  1682. if (DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase) ||
  1683. DoDynamicProfileOpcode(InlinePhase) ||
  1684. DoDynamicProfileOpcode(ObjTypeSpecPhase))
  1685. {
  1686. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1687. }
  1688. break;
  1689. case OpCode::InitRootLetFld:
  1690. case OpCode::InitRootConstFld:
  1691. break;
  1692. default:
  1693. AssertMsg(false, "The specified OpCode is not intended for patchable root field-access");
  1694. break;
  1695. }
  1696. MULTISIZE_LAYOUT_WRITE(ElementRootCP, op, value, cacheId, isLoadMethod, isStore);
  1697. }
  1698. template <typename SizePolicy>
  1699. bool ByteCodeWriter::TryWriteElementP(OpCode op, RegSlot value, CacheId cacheId)
  1700. {
  1701. OpLayoutT_ElementP<SizePolicy> layout;
  1702. if (SizePolicy::Assign(layout.Value, value)
  1703. && SizePolicy::Assign(layout.inlineCacheIndex, cacheId))
  1704. {
  1705. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1706. return true;
  1707. }
  1708. return false;
  1709. }
  1710. void ByteCodeWriter::ElementP(OpCode op, RegSlot value, uint cacheId, bool isCtor, bool registerCacheIdForCall)
  1711. {
  1712. CheckOpen();
  1713. CheckOp(op, OpLayoutType::ElementP);
  1714. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1715. value = ConsumeReg(value);
  1716. switch (op)
  1717. {
  1718. case OpCode::ScopedLdFld:
  1719. case OpCode::ScopedLdFldForTypeOf:
  1720. case OpCode::ScopedStFld:
  1721. case OpCode::ConsoleScopedStFld:
  1722. case OpCode::ScopedStFldStrict:
  1723. case OpCode::ConsoleScopedStFldStrict:
  1724. break;
  1725. case OpCode::LdLocalFld:
  1726. case OpCode::LdLocalFld_ReuseLoc:
  1727. if (isCtor) // The symbol loaded by this LdFld will be used as a constructor
  1728. {
  1729. if (registerCacheIdForCall)
  1730. {
  1731. CacheIdUnit unit(cacheId);
  1732. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1733. callRegToLdFldCacheIndexMap->Add(value, unit);
  1734. }
  1735. }
  1736. if (DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1737. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1738. DoDynamicProfileOpcode(ObjTypeSpecPhase) ||
  1739. DoDynamicProfileOpcode(InlinePhase) ||
  1740. DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase))
  1741. {
  1742. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1743. }
  1744. break;
  1745. case OpCode::LdLocalMethodFld:
  1746. if (registerCacheIdForCall)
  1747. {
  1748. CacheIdUnit unit(cacheId);
  1749. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1750. callRegToLdFldCacheIndexMap->Add(value, unit);
  1751. }
  1752. // fall-through
  1753. case OpCode::StLocalFld:
  1754. case OpCode::InitLocalFld:
  1755. if (DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase) ||
  1756. DoDynamicProfileOpcode(InlinePhase) ||
  1757. DoDynamicProfileOpcode(ObjTypeSpecPhase))
  1758. {
  1759. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1760. }
  1761. break;
  1762. case OpCode::InitLocalLetFld:
  1763. case OpCode::InitUndeclLocalLetFld:
  1764. case OpCode::InitUndeclLocalConstFld:
  1765. break;
  1766. default:
  1767. AssertMsg(false, "The specified OpCode not intended for base-less patchable field access");
  1768. break;
  1769. }
  1770. MULTISIZE_LAYOUT_WRITE(ElementP, op, value, cacheId);
  1771. }
  1772. template <typename SizePolicy>
  1773. bool ByteCodeWriter::TryWriteElementPIndexed(OpCode op, RegSlot value, uint32 scopeIndex, CacheId cacheId)
  1774. {
  1775. OpLayoutT_ElementPIndexed<SizePolicy> layout;
  1776. if (SizePolicy::Assign(layout.Value, value)
  1777. && SizePolicy::Assign(layout.inlineCacheIndex, cacheId)
  1778. && SizePolicy::Assign(layout.scopeIndex, scopeIndex))
  1779. {
  1780. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1781. return true;
  1782. }
  1783. return false;
  1784. }
  1785. void ByteCodeWriter::ElementPIndexed(OpCode op, RegSlot value, uint32 scopeIndex, uint cacheId)
  1786. {
  1787. CheckOpen();
  1788. CheckOp(op, OpLayoutType::ElementPIndexed);
  1789. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1790. value = ConsumeReg(value);
  1791. switch (op)
  1792. {
  1793. case OpCode::InitInnerFld:
  1794. case OpCode::InitInnerLetFld:
  1795. case OpCode::InitUndeclLetFld:
  1796. case OpCode::InitUndeclConstFld:
  1797. break;
  1798. break;
  1799. default:
  1800. AssertMsg(false, "The specified OpCode not intended for base-less patchable inner field access");
  1801. break;
  1802. }
  1803. MULTISIZE_LAYOUT_WRITE(ElementPIndexed, op, value, scopeIndex, cacheId);
  1804. }
  1805. template <typename SizePolicy>
  1806. bool ByteCodeWriter::TryWriteElementCP(OpCode op, RegSlot value, RegSlot instance, CacheId cacheId)
  1807. {
  1808. OpLayoutT_ElementCP<SizePolicy> layout;
  1809. if (SizePolicy::Assign(layout.Value, value) && SizePolicy::Assign(layout.Instance, instance)
  1810. && SizePolicy::Assign(layout.inlineCacheIndex, cacheId))
  1811. {
  1812. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1813. return true;
  1814. }
  1815. return false;
  1816. }
  1817. void ByteCodeWriter::PatchableProperty(OpCode op, RegSlot value, RegSlot instance, uint cacheId, bool isCtor, bool registerCacheIdForCall)
  1818. {
  1819. CheckOpen();
  1820. CheckOp(op, OpLayoutType::ElementCP);
  1821. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1822. value = ConsumeReg(value);
  1823. instance = ConsumeReg(instance);
  1824. bool isProfiled = false;
  1825. Js::ProfileId profileId = Js::Constants::NoProfileId;
  1826. switch (op)
  1827. {
  1828. case OpCode::LdLen_A:
  1829. {
  1830. if ((DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1831. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1832. DoDynamicProfileOpcode(TypedArrayTypeSpecPhase) ||
  1833. DoDynamicProfileOpcode(ArrayCheckHoistPhase) ||
  1834. DoDynamicProfileOpcode(ObjTypeSpecPhase) ||
  1835. DoDynamicProfileOpcode(InlinePhase) ||
  1836. DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase))
  1837. && this->m_functionWrite->AllocProfiledLdLenId(&profileId))
  1838. {
  1839. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1840. isProfiled = true;
  1841. }
  1842. break;
  1843. }
  1844. case OpCode::LdFldForTypeOf:
  1845. case OpCode::LdFld:
  1846. case OpCode::LdFld_ReuseLoc:
  1847. if (isCtor) // The symbol loaded by this LdFld will be used as a constructor
  1848. {
  1849. if (registerCacheIdForCall)
  1850. {
  1851. CacheIdUnit unit(cacheId);
  1852. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1853. callRegToLdFldCacheIndexMap->Add(value, unit);
  1854. }
  1855. }
  1856. case OpCode::LdFldForCallApplyTarget:
  1857. if (DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1858. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1859. DoDynamicProfileOpcode(ObjTypeSpecPhase) ||
  1860. DoDynamicProfileOpcode(InlinePhase) ||
  1861. DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase))
  1862. {
  1863. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1864. }
  1865. break;
  1866. case OpCode::LdMethodFld:
  1867. if (registerCacheIdForCall)
  1868. {
  1869. CacheIdUnit unit(cacheId);
  1870. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1871. callRegToLdFldCacheIndexMap->Add(value, unit);
  1872. }
  1873. // fall-through
  1874. case OpCode::StFld:
  1875. case OpCode::StFldStrict:
  1876. case OpCode::InitFld:
  1877. if (DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase) ||
  1878. DoDynamicProfileOpcode(InlinePhase) ||
  1879. DoDynamicProfileOpcode(ObjTypeSpecPhase))
  1880. {
  1881. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1882. }
  1883. break;
  1884. case OpCode::InitLetFld:
  1885. case OpCode::InitConstFld:
  1886. case OpCode::InitClassMember:
  1887. case OpCode::ScopedLdMethodFld:
  1888. break;
  1889. default:
  1890. AssertMsg(false, "The specified OpCode is not intended for patchable field-access");
  1891. break;
  1892. }
  1893. MULTISIZE_LAYOUT_WRITE(ElementCP, op, value, instance, cacheId);
  1894. if (isProfiled)
  1895. {
  1896. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  1897. }
  1898. }
  1899. template <typename SizePolicy>
  1900. bool ByteCodeWriter::TryWriteElementC2(OpCode op, RegSlot value, RegSlot instance, PropertyIdIndexType propertyIdIndex, RegSlot value2)
  1901. {
  1902. OpLayoutT_ElementC2<SizePolicy> layout;
  1903. if (SizePolicy::Assign(layout.Value, value) && SizePolicy::Assign(layout.Instance, instance)
  1904. && SizePolicy::Assign(layout.PropertyIdIndex, propertyIdIndex) && SizePolicy::Assign(layout.Value2, value2))
  1905. {
  1906. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1907. return true;
  1908. }
  1909. return false;
  1910. }
  1911. void ByteCodeWriter::PatchablePropertyWithThisPtr(OpCode op, RegSlot value, RegSlot instance, RegSlot thisInstance, uint cacheId, bool isCtor, bool registerCacheIdForCall)
  1912. {
  1913. CheckOpen();
  1914. CheckOp(op, OpLayoutType::ElementC2);
  1915. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1916. value = ConsumeReg(value);
  1917. instance = ConsumeReg(instance);
  1918. thisInstance = ConsumeReg(thisInstance);
  1919. switch (op)
  1920. {
  1921. case OpCode::LdSuperFld:
  1922. if (isCtor) // The symbol loaded by this LdSuperFld will be used as a constructor
  1923. {
  1924. if (registerCacheIdForCall)
  1925. {
  1926. CacheIdUnit unit(cacheId);
  1927. Assert(!callRegToLdFldCacheIndexMap->TryGetValue(value, &unit));
  1928. callRegToLdFldCacheIndexMap->Add(value, unit);
  1929. }
  1930. }
  1931. if (DoDynamicProfileOpcode(AggressiveIntTypeSpecPhase) ||
  1932. DoDynamicProfileOpcode(FloatTypeSpecPhase) ||
  1933. DoDynamicProfileOpcode(ObjTypeSpecPhase) ||
  1934. DoDynamicProfileOpcode(InlinePhase) ||
  1935. DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase))
  1936. {
  1937. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1938. }
  1939. break;
  1940. case OpCode::StSuperFld:
  1941. case OpCode::StSuperFldStrict:
  1942. if (DoDynamicProfileOpcode(ProfileBasedFldFastPathPhase) ||
  1943. DoDynamicProfileOpcode(InlinePhase) ||
  1944. DoDynamicProfileOpcode(ObjTypeSpecPhase))
  1945. {
  1946. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  1947. }
  1948. break;
  1949. default:
  1950. AssertMsg(false, "The specified OpCode is not intended for patchable super field-access");
  1951. break;
  1952. }
  1953. MULTISIZE_LAYOUT_WRITE(ElementC2, op, value, instance, cacheId, thisInstance);
  1954. }
  1955. template <typename SizePolicy>
  1956. bool ByteCodeWriter::TryWriteElementScopedC2(OpCode op, RegSlot value, PropertyIdIndexType propertyIdIndex, RegSlot value2)
  1957. {
  1958. OpLayoutT_ElementScopedC2<SizePolicy> layout;
  1959. if (SizePolicy::Assign(layout.Value, value)
  1960. && SizePolicy::Assign(layout.PropertyIdIndex, propertyIdIndex) && SizePolicy::Assign(layout.Value2, value2))
  1961. {
  1962. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  1963. return true;
  1964. }
  1965. return false;
  1966. }
  1967. void ByteCodeWriter::ScopedProperty2(OpCode op, RegSlot value, PropertyIdIndexType propertyIdIndex, RegSlot value2)
  1968. {
  1969. CheckOpen();
  1970. CheckOp(op, OpLayoutType::ElementScopedC2);
  1971. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1972. value = ConsumeReg(value);
  1973. value2 = ConsumeReg(value2);
  1974. switch (op)
  1975. {
  1976. case OpCode::ScopedLdInst:
  1977. break;
  1978. default:
  1979. AssertMsg(false, "The specified OpCode is not intended for field-access with a second instance");
  1980. break;
  1981. }
  1982. MULTISIZE_LAYOUT_WRITE(ElementScopedC2, op, value, propertyIdIndex, value2);
  1983. }
  1984. void ByteCodeWriter::Reg2U(OpCode op, RegSlot R0, RegSlot R1, uint index)
  1985. {
  1986. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  1987. CheckOp(op, OpLayoutType::Reg2U);
  1988. CheckOpen();
  1989. R0 = ConsumeReg(R0);
  1990. R1 = ConsumeReg(R1);
  1991. MULTISIZE_LAYOUT_WRITE(Reg2U, op, R0, R1, index);
  1992. }
  1993. template <typename SizePolicy>
  1994. bool ByteCodeWriter::TryWriteReg3U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, uint index)
  1995. {
  1996. OpLayoutT_Reg3U<SizePolicy> layout;
  1997. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.R2, R2) && SizePolicy::Assign(layout.SlotIndex, index))
  1998. {
  1999. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  2000. return true;
  2001. }
  2002. return false;
  2003. }
  2004. void ByteCodeWriter::Reg3U(OpCode op, RegSlot R0, RegSlot R1, RegSlot R2, uint index)
  2005. {
  2006. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  2007. CheckOp(op, OpLayoutType::Reg3U);
  2008. CheckOpen();
  2009. R0 = ConsumeReg(R0);
  2010. R1 = ConsumeReg(R1);
  2011. R2 = ConsumeReg(R2);
  2012. MULTISIZE_LAYOUT_WRITE(Reg3U, op, R0, R1, R2, index);
  2013. }
  2014. void ByteCodeWriter::NewFunction(RegSlot destinationRegister, uint index, bool isGenerator, RegSlot homeObjLocation)
  2015. {
  2016. CheckOpen();
  2017. bool hasHomeObj = homeObjLocation != Js::Constants::NoRegister;
  2018. destinationRegister = ConsumeReg(destinationRegister);
  2019. OpCode opcode = OpCode::NewScFunc;
  2020. if (isGenerator)
  2021. {
  2022. opcode = hasHomeObj ? OpCode::NewScGenFuncHomeObj : OpCode::NewScGenFunc;
  2023. }
  2024. else if (this->m_functionWrite->DoStackNestedFunc())
  2025. {
  2026. Assert(!hasHomeObj);
  2027. opcode = OpCode::NewStackScFunc;
  2028. }
  2029. else if (hasHomeObj)
  2030. {
  2031. opcode = OpCode::NewScFuncHomeObj;
  2032. }
  2033. Assert(OpCodeAttr::HasMultiSizeLayout(opcode));
  2034. if (hasHomeObj)
  2035. {
  2036. homeObjLocation = ConsumeReg(homeObjLocation);
  2037. MULTISIZE_LAYOUT_WRITE(ElementSlot, opcode, destinationRegister, homeObjLocation, index);
  2038. }
  2039. else
  2040. {
  2041. MULTISIZE_LAYOUT_WRITE(ElementSlotI1, opcode, destinationRegister, index);
  2042. }
  2043. }
  2044. void ByteCodeWriter::NewInnerFunction(RegSlot destinationRegister, uint index, RegSlot environmentRegister, bool isGenerator, RegSlot homeObjLocation)
  2045. {
  2046. CheckOpen();
  2047. bool hasHomeObj = homeObjLocation != Js::Constants::NoRegister;
  2048. destinationRegister = ConsumeReg(destinationRegister);
  2049. environmentRegister = ConsumeReg(environmentRegister);
  2050. OpCode opcode = OpCode::NewInnerScFunc;
  2051. if (isGenerator)
  2052. {
  2053. opcode = hasHomeObj ? OpCode::NewInnerScGenFuncHomeObj : OpCode::NewInnerScGenFunc;
  2054. }
  2055. else if (this->m_functionWrite->DoStackNestedFunc())
  2056. {
  2057. Assert(!hasHomeObj);
  2058. opcode = OpCode::NewInnerStackScFunc;
  2059. }
  2060. else if (hasHomeObj)
  2061. {
  2062. opcode = OpCode::NewInnerScFuncHomeObj;
  2063. }
  2064. Assert(OpCodeAttr::HasMultiSizeLayout(opcode));
  2065. if (hasHomeObj)
  2066. {
  2067. homeObjLocation = ConsumeReg(homeObjLocation);
  2068. MULTISIZE_LAYOUT_WRITE(ElementSlotI3, opcode, destinationRegister, environmentRegister, index, homeObjLocation);
  2069. }
  2070. else
  2071. {
  2072. MULTISIZE_LAYOUT_WRITE(ElementSlot, opcode, destinationRegister, environmentRegister, index);
  2073. }
  2074. }
  2075. template <typename SizePolicy>
  2076. bool ByteCodeWriter::TryWriteReg1Unsigned1(OpCode op, RegSlot R0, uint C1)
  2077. {
  2078. OpLayoutT_Reg1Unsigned1<SizePolicy> layout;
  2079. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.C1, C1))
  2080. {
  2081. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  2082. return true;
  2083. }
  2084. return false;
  2085. }
  2086. void ByteCodeWriter::Reg1Unsigned1(OpCode op, RegSlot R0, uint C1)
  2087. {
  2088. CheckOpen();
  2089. CheckOp(op, OpLayoutType::Reg1Unsigned1);
  2090. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  2091. R0 = ConsumeReg(R0);
  2092. ProfileId profileId = Constants::NoProfileId;
  2093. bool isProfiled = (DoProfileNewScArrayOp(op) &&
  2094. DoDynamicProfileOpcode(NativeArrayPhase, true) &&
  2095. this->m_functionWrite->AllocProfiledArrayCallSiteId(&profileId))
  2096. || (op == OpCode::InitForInEnumerator &&
  2097. this->m_functionWrite->AllocProfiledForInLoopCount(&profileId));
  2098. if (isProfiled)
  2099. {
  2100. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  2101. }
  2102. MULTISIZE_LAYOUT_WRITE(Reg1Unsigned1, op, R0, C1);
  2103. if (isProfiled)
  2104. {
  2105. m_byteCodeData.Encode(&profileId, sizeof(Js::ProfileId));
  2106. }
  2107. }
  2108. void ByteCodeWriter::W1(OpCode op, ushort C1)
  2109. {
  2110. CheckOpen();
  2111. CheckOp(op, OpLayoutType::W1);
  2112. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  2113. OpLayoutW1 data;
  2114. data.C1 = C1;
  2115. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2116. }
  2117. template <typename SizePolicy>
  2118. bool ByteCodeWriter::TryWriteReg2Int1(OpCode op, RegSlot R0, RegSlot R1, int C1)
  2119. {
  2120. OpLayoutT_Reg2Int1<SizePolicy> layout;
  2121. if (SizePolicy::Assign(layout.R0, R0) && SizePolicy::Assign(layout.R1, R1) && SizePolicy::Assign(layout.C1, C1))
  2122. {
  2123. m_byteCodeData.EncodeT<SizePolicy::LayoutEnum>(op, &layout, sizeof(layout), this);
  2124. return true;
  2125. }
  2126. return false;
  2127. }
  2128. void ByteCodeWriter::Reg2Int1(OpCode op, RegSlot R0, RegSlot R1, int C1)
  2129. {
  2130. CheckOpen();
  2131. CheckOp(op, OpLayoutType::Reg2Int1);
  2132. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  2133. if (DoDynamicProfileOpcode(CheckThisPhase) ||
  2134. DoDynamicProfileOpcode(TypedArrayTypeSpecPhase) ||
  2135. DoDynamicProfileOpcode(ArrayCheckHoistPhase))
  2136. {
  2137. if (op == OpCode::LdThis)
  2138. {
  2139. op = OpCode::ProfiledLdThis;
  2140. }
  2141. }
  2142. R0 = ConsumeReg(R0);
  2143. R1 = ConsumeReg(R1);
  2144. MULTISIZE_LAYOUT_WRITE(Reg2Int1, op, R0, R1, C1);
  2145. }
  2146. void ByteCodeWriter::Num3(OpCode op, RegSlot C0, RegSlot C1, RegSlot C2)
  2147. {
  2148. CheckOpen();
  2149. CheckOp(op, OpLayoutType::Reg3);
  2150. Assert(OpCodeAttr::HasMultiSizeLayout(op));
  2151. MULTISIZE_LAYOUT_WRITE(Reg3, op, C0, C1, C2);
  2152. }
  2153. int ByteCodeWriter::AuxNoReg(OpCode op, const void* buffer, int byteCount, int C1)
  2154. {
  2155. CheckOpen();
  2156. //
  2157. // Write the buffer's contents
  2158. //
  2159. int currentOffset = InsertAuxiliaryData(buffer, byteCount);
  2160. //
  2161. // Write OpCode to create new auxiliary data
  2162. //
  2163. OpLayoutAuxNoReg data;
  2164. data.Offset = currentOffset;
  2165. data.C1 = C1;
  2166. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2167. return currentOffset;
  2168. }
  2169. void ByteCodeWriter::AuxNoReg(OpCode op, uint byteOffset, int C1)
  2170. {
  2171. CheckOpen();
  2172. //
  2173. // Write the buffer's contents
  2174. //
  2175. Assert(byteOffset < m_auxiliaryData.GetCurrentOffset());
  2176. OpLayoutAuxNoReg data;
  2177. data.Offset = byteOffset;
  2178. data.C1 = C1;
  2179. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2180. }
  2181. int ByteCodeWriter::Auxiliary(OpCode op, RegSlot destinationRegister, const void* buffer, int byteCount, int C1)
  2182. {
  2183. CheckOpen();
  2184. destinationRegister = ConsumeReg(destinationRegister);
  2185. //
  2186. // Write the buffer's contents
  2187. //
  2188. int currentOffset = InsertAuxiliaryData(buffer, byteCount);
  2189. //
  2190. // Write OpCode to create new auxiliary data
  2191. //
  2192. ProfileId profileId = Constants::NoProfileId;
  2193. if (DoProfileNewScArrayOp(op) &&
  2194. DoDynamicProfileOpcode(NativeArrayPhase, true) &&
  2195. this->m_functionWrite->AllocProfiledArrayCallSiteId(&profileId))
  2196. {
  2197. OpCodeUtil::ConvertNonCallOpToProfiled(op);
  2198. OpLayoutDynamicProfile<OpLayoutAuxiliary> data;
  2199. data.R0 = destinationRegister;
  2200. data.Offset = currentOffset;
  2201. data.C1 = C1;
  2202. data.profileId = profileId;
  2203. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2204. }
  2205. else
  2206. {
  2207. OpLayoutAuxiliary data;
  2208. data.R0 = destinationRegister;
  2209. data.Offset = currentOffset;
  2210. data.C1 = C1;
  2211. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2212. }
  2213. return currentOffset;
  2214. }
  2215. void ByteCodeWriter::Auxiliary(OpCode op, RegSlot destinationRegister, uint byteOffset, int C1)
  2216. {
  2217. CheckOpen();
  2218. destinationRegister = ConsumeReg(destinationRegister);
  2219. //
  2220. // Write the buffer's contents
  2221. //
  2222. Assert(byteOffset < m_auxiliaryData.GetCurrentOffset());
  2223. OpLayoutAuxiliary data;
  2224. data.R0 = destinationRegister;
  2225. data.Offset = byteOffset;
  2226. data.C1 = C1;
  2227. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2228. }
  2229. int ByteCodeWriter::Reg2Aux(OpCode op, RegSlot R0, RegSlot R1, const void* buffer, int byteCount, int C1)
  2230. {
  2231. CheckOpen();
  2232. R0 = ConsumeReg(R0);
  2233. R1 = ConsumeReg(R1);
  2234. //
  2235. // Write the buffer's contents
  2236. //
  2237. int currentOffset = InsertAuxiliaryData(buffer, byteCount);
  2238. //
  2239. // Write OpCode to create new auxiliary data
  2240. //
  2241. OpLayoutReg2Aux data;
  2242. data.R0 = R0;
  2243. data.R1 = R1;
  2244. data.Offset = currentOffset;
  2245. data.C1 = C1;
  2246. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2247. return currentOffset;
  2248. }
  2249. void ByteCodeWriter::Reg2Aux(OpCode op, RegSlot R0, RegSlot R1, uint byteOffset, int C1)
  2250. {
  2251. CheckOpen();
  2252. R0 = ConsumeReg(R0);
  2253. R1 = ConsumeReg(R1);
  2254. //
  2255. // Write the buffer's contents
  2256. //
  2257. Assert(byteOffset < m_auxiliaryData.GetCurrentOffset());
  2258. OpLayoutReg2Aux data;
  2259. data.R0 = R0;
  2260. data.R1 = R1;
  2261. data.Offset = byteOffset;
  2262. data.C1 = C1;
  2263. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2264. }
  2265. void ByteCodeWriter::AuxiliaryContext(OpCode op, RegSlot destinationRegister, const void* buffer, int byteCount, Js::RegSlot C1)
  2266. {
  2267. CheckOpen();
  2268. destinationRegister = ConsumeReg(destinationRegister);
  2269. C1 = ConsumeReg(C1);
  2270. //
  2271. // Write the buffer's contents
  2272. //
  2273. int currentOffset = m_auxContextData.GetCurrentOffset();
  2274. if (byteCount > 0)
  2275. {
  2276. m_auxContextData.Encode(buffer, byteCount);
  2277. }
  2278. //
  2279. // Write OpCode to create new auxiliary data
  2280. //
  2281. OpLayoutAuxiliary data;
  2282. data.R0 = destinationRegister;
  2283. data.Offset = currentOffset;
  2284. data.C1 = C1;
  2285. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2286. }
  2287. uint ByteCodeWriter::InsertAuxiliaryData(const void* buffer, uint byteCount)
  2288. {
  2289. uint offset = m_auxiliaryData.GetCurrentOffset();
  2290. if (byteCount > 0)
  2291. {
  2292. m_auxiliaryData.Encode(buffer, byteCount);
  2293. }
  2294. return offset;
  2295. }
  2296. ByteCodeLabel ByteCodeWriter::DefineLabel()
  2297. {
  2298. #if defined(TARGET_64)
  2299. if (m_labelOffsets->Count() == INT_MAX)
  2300. {
  2301. // Reach our limit
  2302. Js::Throw::OutOfMemory();
  2303. }
  2304. #else
  2305. // 32-bit machine don't have enough address space to get to INT_MAX
  2306. Assert(m_labelOffsets->Count() < INT_MAX);
  2307. #endif
  2308. //
  2309. // Allocate a new label:
  2310. // - All label locations start as "undefined: -1". Once the label's location is marked in
  2311. // the byte-code, this will be updated.
  2312. //
  2313. return (ByteCodeLabel)m_labelOffsets->Add(UINT_MAX);
  2314. }
  2315. void ByteCodeWriter::MarkLabel(ByteCodeLabel labelID)
  2316. {
  2317. CheckOpen();
  2318. CheckLabel(labelID);
  2319. #ifdef BYTECODE_BRANCH_ISLAND
  2320. if (useBranchIsland)
  2321. {
  2322. // If we are going to emit a branch island, it should be before the label.
  2323. EnsureLongBranch(Js::OpCode::Label);
  2324. }
  2325. #endif
  2326. //
  2327. // Define the label as the current offset within the byte-code.
  2328. //
  2329. AssertMsg(m_labelOffsets->Item(labelID) == UINT_MAX, "A label may only be defined at one location");
  2330. m_labelOffsets->SetExistingItem(labelID, m_byteCodeData.GetCurrentOffset());
  2331. }
  2332. void ByteCodeWriter::AddJumpOffset(Js::OpCode op, ByteCodeLabel labelId, uint fieldByteOffsetFromEnd) // Offset of "Offset" field in OpLayout, in bytes
  2333. {
  2334. AssertMsg(fieldByteOffsetFromEnd < 100, "Ensure valid field offset");
  2335. CheckOpen();
  2336. CheckLabel(labelId);
  2337. uint jumpByteOffset = m_byteCodeData.GetCurrentOffset() - fieldByteOffsetFromEnd;
  2338. #ifdef BYTECODE_BRANCH_ISLAND
  2339. if (useBranchIsland)
  2340. {
  2341. // Any Jump might need a long jump, account for that emit the branch island earlier.
  2342. // Even if it is a back edge and we are going to emit a long jump, we will still
  2343. // emit a branch around any way.
  2344. this->nextBranchIslandOffset -= LongBranchSize;
  2345. uint labelOffset = m_labelOffsets->Item(labelId);
  2346. if (labelOffset != UINT_MAX)
  2347. {
  2348. // Back branch, see if it needs to be long
  2349. Assert(labelOffset < m_byteCodeData.GetCurrentOffset());
  2350. LongJumpOffset jumpOffset = labelOffset - m_byteCodeData.GetCurrentOffset();
  2351. if (jumpOffset < -GetBranchLimit())
  2352. {
  2353. // Create the long jump label and add the original jump offset to the list first
  2354. ByteCodeLabel longJumpLabel = this->DefineLabel();
  2355. JumpInfo jumpInfo = { longJumpLabel, jumpByteOffset };
  2356. m_jumpOffsets->Add(jumpInfo);
  2357. // Emit the jump around (if necessary)
  2358. ByteCodeLabel jumpAroundLabel = (ByteCodeLabel)-1;
  2359. if (OpCodeAttr::HasFallThrough(op))
  2360. {
  2361. // emit jump around.
  2362. jumpAroundLabel = this->DefineLabel();
  2363. this->Br(jumpAroundLabel);
  2364. }
  2365. // emit the long jump
  2366. this->MarkLabel(longJumpLabel);
  2367. this->BrLong(Js::OpCode::BrLong, labelId);
  2368. if (jumpAroundLabel != (ByteCodeLabel)-1)
  2369. {
  2370. this->MarkLabel(jumpAroundLabel);
  2371. }
  2372. return;
  2373. }
  2374. }
  2375. }
  2376. #endif
  2377. //
  2378. // Branch targets are created in two passes:
  2379. // - In the instruction stream, write "labelID" into "OpLayoutBrC.Offset". Record this
  2380. // location in "m_jumpOffsets" to be patched later.
  2381. // - When the byte-code is closed, update all "OpLayoutBrC.Offset"'s with their actual
  2382. // destinations.
  2383. //
  2384. JumpInfo jumpInfo = { labelId, jumpByteOffset };
  2385. m_jumpOffsets->Add(jumpInfo);
  2386. }
  2387. #ifdef BYTECODE_BRANCH_ISLAND
  2388. int32 ByteCodeWriter::GetBranchLimit()
  2389. {
  2390. #ifdef BYTECODE_TESTING
  2391. if (Js::Configuration::Global.flags.IsEnabled(Js::ByteCodeBranchLimitFlag))
  2392. {
  2393. // minimum 64
  2394. return min(max(Js::Configuration::Global.flags.ByteCodeBranchLimit, 64), SHRT_MAX + 1);
  2395. }
  2396. #endif
  2397. return SHRT_MAX + 1;
  2398. }
  2399. void ByteCodeWriter::AddLongJumpOffset(ByteCodeLabel labelId, uint fieldByteOffsetFromEnd) // Offset of "Offset" field in OpLayout, in bytes
  2400. {
  2401. Assert(useBranchIsland);
  2402. AssertMsg(fieldByteOffsetFromEnd < 100, "Ensure valid field offset");
  2403. //
  2404. // Branch targets are created in two passes:
  2405. // - In the instruction stream, write "labelID" into "OpLayoutBrC.Offset". Record this
  2406. // location in "m_jumpOffsets" to be patched later.
  2407. // - When the byte-code is closed, update all "OpLayoutBrC.Offset"'s with their actual
  2408. // destinations.
  2409. //
  2410. uint jumpByteOffset = m_byteCodeData.GetCurrentOffset() - fieldByteOffsetFromEnd;
  2411. JumpInfo jumpInfo = { labelId, jumpByteOffset };
  2412. m_longJumpOffsets->Add(jumpInfo);
  2413. }
  2414. void ByteCodeWriter::BrLong(OpCode op, ByteCodeLabel labelID)
  2415. {
  2416. Assert(useBranchIsland);
  2417. CheckOpen();
  2418. CheckOp(op, OpLayoutType::BrLong);
  2419. CheckLabel(labelID);
  2420. Assert(!OpCodeAttr::HasMultiSizeLayout(op));
  2421. size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutBrLong) - offsetof(OpLayoutBrLong, RelativeJumpOffset);
  2422. OpLayoutBrLong data;
  2423. data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;
  2424. m_byteCodeData.Encode(op, &data, sizeof(data), this);
  2425. AddLongJumpOffset(labelID, offsetOfRelativeJumpOffsetFromEnd);
  2426. }
  2427. void ByteCodeWriter::UpdateNextBranchIslandOffset(uint firstUnknownJumpInfo, uint firstUnknownJumpOffset)
  2428. {
  2429. this->firstUnknownJumpInfo = firstUnknownJumpInfo;
  2430. // We will need to emit the next branch from the first branch + branch limit.
  2431. // But leave room for the jump around and one extra byte code instruction.
  2432. // Also account for all the long branches we may have to emit as well.
  2433. this->nextBranchIslandOffset = firstUnknownJumpOffset + GetBranchLimit()
  2434. - JumpAroundSize - MaxLayoutSize - MaxOpCodeSize - LongBranchSize * (m_jumpOffsets->Count() - firstUnknownJumpInfo);
  2435. }
  2436. void ByteCodeWriter::EnsureLongBranch(Js::OpCode op)
  2437. {
  2438. Assert(useBranchIsland);
  2439. int currentOffset = this->m_byteCodeData.GetCurrentOffset();
  2440. // See if we need to emit branch island yet, and avoid recursion.
  2441. if (currentOffset < this->nextBranchIslandOffset || this->inEnsureLongBranch)
  2442. {
  2443. lastOpcode = op;
  2444. return;
  2445. }
  2446. // Leave actually may continue right after, it is only no fall through in the JIT.
  2447. bool needBranchAround = OpCodeAttr::HasFallThrough(lastOpcode) || lastOpcode == Js::OpCode::Leave;
  2448. lastOpcode = op;
  2449. // If we are about to emit a no fall through op and the last was has fall through
  2450. // then just emit the no fall through op, and then we can skip the branch around.
  2451. // Except at label or StatementBoundary, we always want to emit before them.
  2452. if ((needBranchAround && !OpCodeAttr::HasFallThrough(op))
  2453. && op != Js::OpCode::StatementBoundary && op != Js::OpCode::Label)
  2454. {
  2455. return;
  2456. }
  2457. ByteCodeLabel branchAroundLabel = (Js::ByteCodeLabel)-1;
  2458. bool foundUnknown = m_jumpOffsets->MapUntilFrom(firstUnknownJumpInfo,
  2459. [=, &branchAroundLabel, &currentOffset](int index, JumpInfo& jumpInfo)
  2460. {
  2461. //
  2462. // Read "labelID" stored at the offset within the byte-code.
  2463. //
  2464. uint jumpByteOffset = jumpInfo.patchOffset;
  2465. AssertMsg(jumpByteOffset <= this->m_byteCodeData.GetCurrentOffset() - sizeof(JumpOffset),
  2466. "Must have valid jump site within byte-code to back-patch");
  2467. ByteCodeLabel labelID = jumpInfo.labelId;
  2468. CheckLabel(labelID);
  2469. // See if the label has bee marked yet.
  2470. uint const labelByteOffset = m_labelOffsets->Item(labelID);
  2471. if (labelByteOffset != UINT_MAX)
  2472. {
  2473. // If a label is already defined, then it should be short
  2474. // (otherwise we should have emitted a branch island for it already).
  2475. Assert((int)labelByteOffset - (int)jumpByteOffset < GetBranchLimit()
  2476. && (int)labelByteOffset - (int)jumpByteOffset >= -GetBranchLimit());
  2477. return false;
  2478. }
  2479. this->UpdateNextBranchIslandOffset(index, jumpByteOffset);
  2480. // Flush all the jump that are half of the way to the limit as well so we don't have
  2481. // as many jump around of branch island.
  2482. int flushNextBranchIslandOffset = this->nextBranchIslandOffset - GetBranchLimit() / 2;
  2483. if (currentOffset < flushNextBranchIslandOffset)
  2484. {
  2485. // No need to for long branch yet. Terminate the loop.
  2486. return true;
  2487. }
  2488. if (labelID == branchAroundLabel)
  2489. {
  2490. // Let's not flush the branchAroundLabel.
  2491. // Should happen very rarely and mostly when the branch limit is very small.
  2492. // This should be the last short jump we have just emitted (below).
  2493. Assert(index == m_jumpOffsets->Count() - 1);
  2494. Assert(currentOffset < this->nextBranchIslandOffset);
  2495. return true;
  2496. }
  2497. // Emit long branch
  2498. // Prevent recursion when we emit byte code here
  2499. this->inEnsureLongBranch = true;
  2500. // Create the branch label and update the jumpInfo.
  2501. // Need to update the jumpInfo before we add the branch island as that might resize the m_jumpOffsets list.
  2502. ByteCodeLabel longBranchLabel = this->DefineLabel();
  2503. jumpInfo.labelId = longBranchLabel;
  2504. // Emit the branch around if it hasn't been emitted already
  2505. if (branchAroundLabel == (Js::ByteCodeLabel)-1 && needBranchAround)
  2506. {
  2507. branchAroundLabel = this->DefineLabel();
  2508. this->Br(Js::OpCode::Br, branchAroundLabel);
  2509. Assert(this->m_byteCodeData.GetCurrentOffset() - currentOffset == JumpAroundSize);
  2510. currentOffset += JumpAroundSize;
  2511. // Continue to count he jumpAroundSize, because we may have to emit
  2512. // yet another branch island right after if the jumpAroundSize is included.
  2513. }
  2514. // Emit the long branch
  2515. this->MarkLabel(longBranchLabel);
  2516. this->BrLong(Js::OpCode::BrLong, labelID);
  2517. this->inEnsureLongBranch = false;
  2518. Assert(this->m_byteCodeData.GetCurrentOffset() - currentOffset == LongBranchSize);
  2519. currentOffset += LongBranchSize;
  2520. return false;
  2521. });
  2522. if (!foundUnknown)
  2523. {
  2524. // Nothing is found, just set the next branch island from the current offset
  2525. this->UpdateNextBranchIslandOffset(this->m_jumpOffsets->Count(), currentOffset);
  2526. }
  2527. if (branchAroundLabel != (Js::ByteCodeLabel)-1)
  2528. {
  2529. // Make the branch around label if we needed one
  2530. this->MarkLabel(branchAroundLabel);
  2531. }
  2532. }
  2533. #endif
  2534. void ByteCodeWriter::StartStatement(ParseNode* node, uint32 tmpRegCount)
  2535. {
  2536. if (m_pMatchingNode)
  2537. {
  2538. if (m_pMatchingNode == node)
  2539. {
  2540. m_matchingNodeRefCount++;
  2541. }
  2542. return;
  2543. }
  2544. #ifdef BYTECODE_BRANCH_ISLAND
  2545. if (useBranchIsland)
  2546. {
  2547. // If we are going to emit a branch island, it should be before the statement start
  2548. this->EnsureLongBranch(Js::OpCode::StatementBoundary);
  2549. }
  2550. #endif
  2551. m_pMatchingNode = node;
  2552. m_beginCodeSpan = m_byteCodeData.GetCurrentOffset();
  2553. if (m_isInDebugMode && m_tmpRegCount != tmpRegCount)
  2554. {
  2555. Unsigned1(OpCode::EmitTmpRegCount, tmpRegCount);
  2556. m_tmpRegCount = tmpRegCount;
  2557. }
  2558. }
  2559. void ByteCodeWriter::EndStatement(ParseNode* node)
  2560. {
  2561. AssertMsg(m_pMatchingNode, "EndStatement unmatched to StartStatement");
  2562. if (m_pMatchingNode != node)
  2563. {
  2564. return;
  2565. }
  2566. else if (m_matchingNodeRefCount > 0)
  2567. {
  2568. m_matchingNodeRefCount--;
  2569. return;
  2570. }
  2571. if (m_byteCodeData.GetCurrentOffset() != m_beginCodeSpan)
  2572. {
  2573. if (m_isInDebugMode)
  2574. {
  2575. FunctionBody::StatementMap* pCurrentStatement = FunctionBody::StatementMap::New(this->m_functionWrite->GetScriptContext()->GetRecycler());
  2576. if (pCurrentStatement)
  2577. {
  2578. pCurrentStatement->sourceSpan.begin = node->ichMin;
  2579. pCurrentStatement->sourceSpan.end = node->ichLim;
  2580. pCurrentStatement->byteCodeSpan.begin = m_beginCodeSpan;
  2581. pCurrentStatement->byteCodeSpan.end = m_byteCodeData.GetCurrentOffset() - 1;
  2582. m_functionWrite->RecordStatementMap(pCurrentStatement);
  2583. }
  2584. }
  2585. else
  2586. {
  2587. StatementData currentStatement;
  2588. currentStatement.sourceBegin = node->ichMin;
  2589. currentStatement.bytecodeBegin = m_beginCodeSpan;
  2590. m_functionWrite->RecordStatementMap(spanIter, &currentStatement);
  2591. }
  2592. }
  2593. m_pMatchingNode = nullptr;
  2594. }
  2595. void ByteCodeWriter::StartSubexpression(ParseNode* node)
  2596. {
  2597. if (!m_isInDebugMode || !m_pMatchingNode) // Subexpression not in debug mode or not enclosed in regular statement
  2598. {
  2599. return;
  2600. }
  2601. #ifdef BYTECODE_BRANCH_ISLAND
  2602. // If we are going to emit a branch island, it should be before the statement start
  2603. this->EnsureLongBranch(Js::OpCode::StatementBoundary);
  2604. #endif
  2605. m_subexpressionNodesStack->Push(SubexpressionNode(node, m_byteCodeData.GetCurrentOffset()));
  2606. }
  2607. void ByteCodeWriter::EndSubexpression(ParseNode* node)
  2608. {
  2609. if (!m_isInDebugMode || m_subexpressionNodesStack->Empty() || m_subexpressionNodesStack->Peek().node != node)
  2610. {
  2611. return;
  2612. }
  2613. if (m_byteCodeData.GetCurrentOffset() != m_beginCodeSpan)
  2614. {
  2615. FunctionBody::StatementMap* pCurrentStatement = FunctionBody::StatementMap::New(this->m_functionWrite->GetScriptContext()->GetRecycler());
  2616. if (pCurrentStatement)
  2617. {
  2618. pCurrentStatement->sourceSpan.begin = node->ichMin;
  2619. pCurrentStatement->sourceSpan.end = node->ichLim;
  2620. SubexpressionNode subexpressionNode = m_subexpressionNodesStack->Pop();
  2621. pCurrentStatement->byteCodeSpan.begin = subexpressionNode.beginCodeSpan;
  2622. pCurrentStatement->byteCodeSpan.end = m_byteCodeData.GetCurrentOffset() - 1;
  2623. pCurrentStatement->isSubexpression = true;
  2624. m_functionWrite->RecordStatementMap(pCurrentStatement);
  2625. }
  2626. }
  2627. }
  2628. // Pushes a new debugger scope onto the stack. This information is used when determining
  2629. // what the current scope is for tracking of let/const initialization offsets (for detecting
  2630. // dead zones).
  2631. void ByteCodeWriter::PushDebuggerScope(Js::DebuggerScope* debuggerScope)
  2632. {
  2633. Assert(debuggerScope);
  2634. debuggerScope->SetParentScope(m_currentDebuggerScope);
  2635. m_currentDebuggerScope = debuggerScope;
  2636. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("PushDebuggerScope() - Pushed scope 0x%p of type %d.\n"), m_currentDebuggerScope, m_currentDebuggerScope->scopeType);
  2637. }
  2638. // Pops the current debugger scope from the stack.
  2639. void ByteCodeWriter::PopDebuggerScope()
  2640. {
  2641. Assert(m_currentDebuggerScope);
  2642. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("PopDebuggerScope() - Popped scope 0x%p of type %d.\n"), m_currentDebuggerScope, m_currentDebuggerScope->scopeType);
  2643. if (m_currentDebuggerScope != nullptr)
  2644. {
  2645. m_currentDebuggerScope = m_currentDebuggerScope->GetParentScope();
  2646. }
  2647. }
  2648. DebuggerScope* ByteCodeWriter::RecordStartScopeObject(DiagExtraScopesType scopeType, RegSlot scopeLocation, int* index)
  2649. {
  2650. if (scopeLocation != Js::Constants::NoRegister)
  2651. {
  2652. scopeLocation = ConsumeReg(scopeLocation);
  2653. }
  2654. DebuggerScope* debuggerScope = m_functionWrite->RecordStartScopeObject(scopeType, m_byteCodeData.GetCurrentOffset(), scopeLocation, index);
  2655. PushDebuggerScope(debuggerScope);
  2656. return debuggerScope;
  2657. }
  2658. void ByteCodeWriter::AddPropertyToDebuggerScope(
  2659. DebuggerScope* debuggerScope,
  2660. RegSlot location,
  2661. Js::PropertyId propertyId,
  2662. bool shouldConsumeRegister /*= true*/,
  2663. DebuggerScopePropertyFlags flags /*= DebuggerScopePropertyFlags_None*/,
  2664. bool isFunctionDeclaration /*= false*/)
  2665. {
  2666. Assert(debuggerScope);
  2667. // Activation object doesn't use register and slot array location represents the
  2668. // index in the array. Only need to consume for register slots.
  2669. if (shouldConsumeRegister)
  2670. {
  2671. Assert(location != Js::Constants::NoRegister);
  2672. location = ConsumeReg(location);
  2673. }
  2674. debuggerScope->AddProperty(location, propertyId, flags);
  2675. // Only need to update properties in debug mode (even for slot array, which is tracked in non-debug mode,
  2676. // since the offset is only used for debugging).
  2677. if (this->m_isInDebugMode && isFunctionDeclaration)
  2678. {
  2679. AssertMsg(this->m_currentDebuggerScope, "Function declarations can only be added in a block scope.");
  2680. AssertMsg(debuggerScope == this->m_currentDebuggerScope
  2681. || debuggerScope == this->m_currentDebuggerScope->siblingScope,
  2682. "Function declarations should always be added to the current scope.");
  2683. // If this is a function declaration, it doesn't have a dead zone region so
  2684. // we just update its byte code initialization offset to the start of the block.
  2685. this->UpdateDebuggerPropertyInitializationOffset(
  2686. debuggerScope,
  2687. location,
  2688. propertyId,
  2689. false /*shouldConsumeRegister*/, // Register would have already been consumed above, if needed.
  2690. debuggerScope->GetStart(),
  2691. isFunctionDeclaration);
  2692. }
  2693. }
  2694. void ByteCodeWriter::RecordEndScopeObject()
  2695. {
  2696. Assert(this->m_currentDebuggerScope);
  2697. m_functionWrite->RecordEndScopeObject(this->m_currentDebuggerScope, m_byteCodeData.GetCurrentOffset() - 1);
  2698. PopDebuggerScope();
  2699. }
  2700. void ByteCodeWriter::UpdateDebuggerPropertyInitializationOffset(
  2701. Js::DebuggerScope* currentDebuggerScope,
  2702. Js::RegSlot location,
  2703. Js::PropertyId propertyId,
  2704. bool shouldConsumeRegister/* = true*/,
  2705. int byteCodeOffset/* = Constants::InvalidOffset*/,
  2706. bool isFunctionDeclaration /*= false*/)
  2707. {
  2708. #if DBG
  2709. bool isInDebugMode = m_isInDebugMode
  2710. #if DBG_DUMP
  2711. || Js::Configuration::Global.flags.Debug
  2712. #endif // DBG_DUMP
  2713. ;
  2714. AssertMsg(isInDebugMode, "Property offsets should only ever be updated in debug mode (not used in non-debug).");
  2715. #endif // DBG
  2716. Assert(currentDebuggerScope);
  2717. if (shouldConsumeRegister)
  2718. {
  2719. Assert(location != Js::Constants::NoRegister);
  2720. location = ConsumeReg(location);
  2721. }
  2722. if (byteCodeOffset == Constants::InvalidOffset)
  2723. {
  2724. // Use the current offset if no offset is passed in.
  2725. byteCodeOffset = this->m_byteCodeData.GetCurrentOffset();
  2726. }
  2727. // Search through the scope chain starting with the current up through the parents to see if the
  2728. // property can be found and updated.
  2729. while (currentDebuggerScope != nullptr)
  2730. {
  2731. if (currentDebuggerScope->UpdatePropertyInitializationOffset(location, propertyId, byteCodeOffset, isFunctionDeclaration))
  2732. {
  2733. break;
  2734. }
  2735. currentDebuggerScope = currentDebuggerScope->GetParentScope();
  2736. }
  2737. }
  2738. void ByteCodeWriter::RecordFrameDisplayRegister(RegSlot slot)
  2739. {
  2740. slot = ConsumeReg(slot);
  2741. m_functionWrite->RecordFrameDisplayRegister(slot);
  2742. }
  2743. void ByteCodeWriter::RecordObjectRegister(RegSlot slot)
  2744. {
  2745. slot = ConsumeReg(slot);
  2746. m_functionWrite->RecordObjectRegister(slot);
  2747. }
  2748. void ByteCodeWriter::RecordStatementAdjustment(FunctionBody::StatementAdjustmentType type)
  2749. {
  2750. if (m_isInDebugMode)
  2751. {
  2752. m_functionWrite->RecordStatementAdjustment(m_byteCodeData.GetCurrentOffset(), type);
  2753. }
  2754. }
  2755. void ByteCodeWriter::RecordCrossFrameEntryExitRecord(bool isEnterBlock)
  2756. {
  2757. if (m_isInDebugMode)
  2758. {
  2759. m_functionWrite->RecordCrossFrameEntryExitRecord(m_byteCodeData.GetCurrentOffset(), isEnterBlock);
  2760. }
  2761. }
  2762. void ByteCodeWriter::RecordForInOrOfCollectionScope()
  2763. {
  2764. if (m_isInDebugMode && this->m_currentDebuggerScope != nullptr)
  2765. {
  2766. this->m_currentDebuggerScope->UpdatePropertiesInForInOrOfCollectionScope();
  2767. }
  2768. }
  2769. uint ByteCodeWriter::EnterLoop(Js::ByteCodeLabel loopEntrance)
  2770. {
  2771. #ifdef BYTECODE_BRANCH_ISLAND
  2772. if (useBranchIsland)
  2773. {
  2774. // If we are going to emit a branch island, it should be before the loop header
  2775. this->EnsureLongBranch(Js::OpCode::StatementBoundary);
  2776. }
  2777. #endif
  2778. uint loopId = m_functionWrite->IncrLoopCount();
  2779. Assert((uint)m_loopHeaders->Count() == loopId);
  2780. m_loopHeaders->Add(LoopHeaderData(m_byteCodeData.GetCurrentOffset(), 0, m_loopNest > 0));
  2781. m_loopNest++;
  2782. m_functionWrite->SetHasNestedLoop(m_loopNest > 1);
  2783. Js::OpCode loopBodyOpcode = Js::OpCode::LoopBodyStart;
  2784. #if ENABLE_PROFILE_INFO
  2785. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionWrite()))
  2786. {
  2787. this->Unsigned1(Js::OpCode::ProfiledLoopStart, loopId);
  2788. loopBodyOpcode = Js::OpCode::ProfiledLoopBodyStart;
  2789. }
  2790. #endif
  2791. this->MarkLabel(loopEntrance);
  2792. if (this->DoJitLoopBodies() || this->DoInterruptProbes())
  2793. {
  2794. this->Unsigned1(loopBodyOpcode, loopId);
  2795. }
  2796. return loopId;
  2797. }
  2798. void ByteCodeWriter::ExitLoop(uint loopId)
  2799. {
  2800. #if ENABLE_PROFILE_INFO
  2801. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionWrite()))
  2802. {
  2803. this->Unsigned1(Js::OpCode::ProfiledLoopEnd, loopId);
  2804. }
  2805. #endif
  2806. Assert(m_loopNest > 0);
  2807. m_loopNest--;
  2808. m_loopHeaders->Item(loopId).endOffset = m_byteCodeData.GetCurrentOffset();
  2809. }
  2810. void ByteCodeWriter::IncreaseByteCodeCount()
  2811. {
  2812. m_byteCodeCount++;
  2813. if (m_loopNest > 0)
  2814. {
  2815. m_byteCodeInLoopCount++;
  2816. }
  2817. }
  2818. void ByteCodeWriter::Data::Create(uint initSize, ArenaAllocator* tmpAlloc)
  2819. {
  2820. //
  2821. // Allocate the initial byte-code block to write into.
  2822. //
  2823. tempAllocator = tmpAlloc;
  2824. AssertMsg(head == nullptr, "Missing dispose?");
  2825. currentOffset = 0;
  2826. head = Anew(tempAllocator, DataChunk, tempAllocator, initSize);
  2827. current = head;
  2828. }
  2829. void ByteCodeWriter::Data::Reset()
  2830. {
  2831. currentOffset = 0;
  2832. DataChunk* currentChunk = head;
  2833. while (currentChunk)
  2834. {
  2835. // reset to the starting point
  2836. currentChunk->Reset();
  2837. currentChunk = currentChunk->nextChunk;
  2838. }
  2839. current = head;
  2840. }
  2841. void ByteCodeWriter::Data::SetCurrent(uint offset, DataChunk* currChunk)
  2842. {
  2843. this->current = currChunk;
  2844. this->currentOffset = offset;
  2845. }
  2846. /// Copies its contents to a final contiguous section of memory.
  2847. void ByteCodeWriter::Data::Copy(Recycler* alloc, ByteBlock ** finalBlock)
  2848. {
  2849. AssertMsg(finalBlock != nullptr, "Must have valid storage");
  2850. uint cbFinalData = GetCurrentOffset();
  2851. if (cbFinalData == 0)
  2852. {
  2853. *finalBlock = nullptr;
  2854. }
  2855. else
  2856. {
  2857. ByteBlock* finalByteCodeBlock = ByteBlock::New(alloc, /*initialContent*/nullptr, cbFinalData);
  2858. DataChunk* currentChunk = head;
  2859. size_t bytesLeftToCopy = cbFinalData;
  2860. byte* currentDest = finalByteCodeBlock->GetBuffer();
  2861. while (true)
  2862. {
  2863. if (bytesLeftToCopy <= currentChunk->GetSize())
  2864. {
  2865. js_memcpy_s(currentDest, bytesLeftToCopy, currentChunk->GetBuffer(), bytesLeftToCopy);
  2866. break;
  2867. }
  2868. js_memcpy_s(currentDest, bytesLeftToCopy, currentChunk->GetBuffer(), currentChunk->GetSize());
  2869. bytesLeftToCopy -= currentChunk->GetSize();
  2870. currentDest += currentChunk->GetSize();
  2871. currentChunk = currentChunk->nextChunk;
  2872. AssertMsg(currentChunk, "We are copying more data than we have!");
  2873. }
  2874. *finalBlock = finalByteCodeBlock;
  2875. }
  2876. }
  2877. template <>
  2878. void ByteCodeWriter::Data::EncodeOpCode<SmallLayout>(
  2879. uint16 op,
  2880. ByteCodeWriter* writer)
  2881. {
  2882. DebugOnly(const uint offset = currentOffset);
  2883. if (op <= (uint16)Js::OpCode::MaxByteSizedOpcodes)
  2884. {
  2885. byte byteop = (byte)op;
  2886. Write(&byteop, sizeof(byte));
  2887. }
  2888. else
  2889. {
  2890. byte byteop = (byte)Js::OpCode::ExtendedOpcodePrefix;
  2891. Write(&byteop, sizeof(byte));
  2892. Write(&op, sizeof(uint16));
  2893. }
  2894. Assert(OpCodeUtil::EncodedSize((Js::OpCode)op, SmallLayout)
  2895. == (currentOffset - offset));
  2896. }
  2897. template <LayoutSize layoutSize>
  2898. void ByteCodeWriter::Data::EncodeOpCode(uint16 op, ByteCodeWriter* writer)
  2899. {
  2900. CompileAssert(layoutSize != SmallLayout);
  2901. DebugOnly(const uint offset = currentOffset);
  2902. if (op <= (uint16)Js::OpCode::MaxByteSizedOpcodes)
  2903. {
  2904. const byte exop = (byte)(layoutSize == LargeLayout ? Js::OpCode::LargeLayoutPrefix : Js::OpCode::MediumLayoutPrefix);
  2905. Write(&exop, sizeof(byte));
  2906. byte byteop = (byte)op;
  2907. Write(&byteop, sizeof(byte));
  2908. }
  2909. else
  2910. {
  2911. const byte exop = (byte)(layoutSize == LargeLayout ? Js::OpCode::ExtendedLargeLayoutPrefix : Js::OpCode::ExtendedMediumLayoutPrefix);
  2912. Write(&exop, sizeof(byte));
  2913. Write(&op, sizeof(uint16));
  2914. }
  2915. Assert(OpCodeUtil::EncodedSize((Js::OpCode)op, layoutSize) == (currentOffset - offset));
  2916. }
  2917. template <LayoutSize layoutSize>
  2918. uint ByteCodeWriter::Data::EncodeT(OpCode op, ByteCodeWriter* writer)
  2919. {
  2920. #ifdef BYTECODE_BRANCH_ISLAND
  2921. if (writer->useBranchIsland)
  2922. {
  2923. writer->EnsureLongBranch(op);
  2924. }
  2925. #endif
  2926. Assert(op < Js::OpCode::ByteCodeLast);
  2927. Assert(!OpCodeAttr::BackEndOnly(op));
  2928. Assert(layoutSize == SmallLayout || OpCodeAttr::HasMultiSizeLayout(op));
  2929. // Capture offset before encoding the opcode
  2930. uint offset = GetCurrentOffset();
  2931. EncodeOpCode<layoutSize>((uint16)op, writer);
  2932. if (op != Js::OpCode::Ld_A)
  2933. {
  2934. writer->m_byteCodeWithoutLDACount++;
  2935. }
  2936. writer->IncreaseByteCodeCount();
  2937. return offset;
  2938. }
  2939. template <LayoutSize layoutSize>
  2940. uint ByteCodeWriter::Data::EncodeT(OpCode op, const void* rawData, int byteSize, ByteCodeWriter* writer)
  2941. {
  2942. AssertMsg((rawData != nullptr) && (byteSize < 100), "Ensure valid data for opcode");
  2943. uint offset = EncodeT<layoutSize>(op, writer);
  2944. Write(rawData, byteSize);
  2945. return offset;
  2946. }
  2947. void ByteCodeWriter::Data::Encode(const void* rawData, int byteSize)
  2948. {
  2949. AssertMsg(rawData != nullptr, "Ensure valid data for opcode");
  2950. Write(rawData, byteSize);
  2951. }
  2952. void ByteCodeWriter::Data::Write(__in_bcount(byteSize) const void* data, __in uint byteSize)
  2953. {
  2954. // Simple case where the current chunk has enough space.
  2955. uint bytesFree = current->RemainingBytes();
  2956. if (bytesFree >= byteSize)
  2957. {
  2958. current->WriteUnsafe(data, byteSize);
  2959. }
  2960. else
  2961. {
  2962. SlowWrite(data, byteSize);
  2963. }
  2964. currentOffset += byteSize;
  2965. }
  2966. /// Requires buffer extension.
  2967. _NOINLINE void ByteCodeWriter::Data::SlowWrite(__in_bcount(byteSize) const void* data, __in uint byteSize)
  2968. {
  2969. AssertMsg(byteSize > current->RemainingBytes(), "We should not need an extension if there is enough space in the current chunk");
  2970. uint bytesLeftToWrite = byteSize;
  2971. byte* dataToBeWritten = (byte*)data;
  2972. // the next chunk may already be created in the case that we are patching bytecode.
  2973. // If so, we want to move the pointer to the beginning of the buffer
  2974. if (current->nextChunk)
  2975. {
  2976. current->nextChunk->SetCurrentOffset(0);
  2977. }
  2978. while (true)
  2979. {
  2980. uint bytesFree = current->RemainingBytes();
  2981. if (bytesFree >= bytesLeftToWrite)
  2982. {
  2983. current->WriteUnsafe(dataToBeWritten, bytesLeftToWrite);
  2984. break;
  2985. }
  2986. current->WriteUnsafe(dataToBeWritten, bytesFree);
  2987. bytesLeftToWrite -= bytesFree;
  2988. dataToBeWritten += bytesFree;
  2989. // Create a new chunk when needed
  2990. if (!current->nextChunk)
  2991. {
  2992. AddChunk(bytesLeftToWrite);
  2993. }
  2994. current = current->nextChunk;
  2995. }
  2996. }
  2997. void ByteCodeWriter::Data::AddChunk(uint byteSize)
  2998. {
  2999. AssertMsg(current->nextChunk == nullptr, "Do we really need to grow?");
  3000. // For some data elements i.e. bytecode we have a good initial size and
  3001. // therefore, we use a conservative growth strategy - and grow by a fixed size.
  3002. uint newSize = fixedGrowthPolicy ? max(byteSize, static_cast<uint>(3 * AutoSystemInfo::PageSize)) : max(byteSize, static_cast<uint>(current->GetSize() * 2));
  3003. DataChunk* newChunk = Anew(tempAllocator, DataChunk, tempAllocator, newSize);
  3004. current->nextChunk = newChunk;
  3005. }
  3006. #if DBG_DUMP
  3007. uint ByteCodeWriter::ByteCodeDataSize()
  3008. {
  3009. return m_byteCodeData.GetCurrentOffset();
  3010. }
  3011. uint ByteCodeWriter::AuxiliaryDataSize()
  3012. {
  3013. return m_auxiliaryData.GetCurrentOffset();
  3014. }
  3015. uint ByteCodeWriter::AuxiliaryContextDataSize()
  3016. {
  3017. return m_auxContextData.GetCurrentOffset();
  3018. }
  3019. #endif
  3020. } // namespace Js