WasmByteCodeGenerator.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "WasmReaderPch.h"
  6. #ifdef ENABLE_WASM
  7. #include "Language/WebAssemblySource.h"
  8. #include "ByteCode/WasmByteCodeWriter.h"
  9. #include "EmptyWasmByteCodeWriter.h"
  10. #include "ByteCode/ByteCodeDumper.h"
  11. #include "AsmJsByteCodeDumper.h"
  12. #include "Language/InterpreterStackFrame.h"
  13. #if DBG_DUMP
  14. #define DebugPrintOp(op) if (DO_WASM_TRACE_BYTECODE) { PrintOpBegin(op); }
  15. #define DebugPrintOpEnd() if (DO_WASM_TRACE_BYTECODE) { PrintOpEnd(); }
  16. #else
  17. #define DebugPrintOp(op)
  18. #define DebugPrintOpEnd()
  19. #endif
  20. namespace Wasm
  21. {
  22. #define WASM_SIGNATURE(id, nTypes, ...) const WasmTypes::WasmType WasmOpCodeSignatures::id[] = {__VA_ARGS__};
  23. #include "WasmBinaryOpCodes.h"
  24. template<typename WriteFn>
  25. void WasmBytecodeGenerator::WriteTypeStack(WriteFn writefn) const
  26. {
  27. writefn(_u("["));
  28. int i = 0;
  29. while (m_evalStack.Peek(i).type != WasmTypes::Limit)
  30. {
  31. ++i;
  32. }
  33. --i;
  34. bool isFirst = true;
  35. while (i >= 0)
  36. {
  37. EmitInfo info = m_evalStack.Peek(i--);
  38. if (!isFirst)
  39. {
  40. writefn(_u(", "));
  41. }
  42. isFirst = false;
  43. writefn(GetTypeName(info.type));
  44. }
  45. writefn(_u("]"));
  46. }
  47. uint32 WasmBytecodeGenerator::WriteTypeStackToString(_Out_writes_(maxlen) char16* out, uint32 maxlen) const
  48. {
  49. AssertOrFailFast(out != nullptr);
  50. uint32 numwritten = 0;
  51. WriteTypeStack([&] (const char16* msg)
  52. {
  53. numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, msg);
  54. });
  55. if (numwritten >= maxlen - 5)
  56. {
  57. // null out the last 5 characters so we can properly end it
  58. for (int i = 1; i <= 5; i++)
  59. {
  60. *(out + maxlen - i) = 0;
  61. }
  62. numwritten -= 5;
  63. numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, _u("...]"));
  64. }
  65. return numwritten;
  66. }
  67. #if DBG_DUMP
  68. void WasmBytecodeGenerator::PrintTypeStack() const
  69. {
  70. WriteTypeStack([](const char16* msg) { Output::Print(msg); });
  71. }
  72. void WasmBytecodeGenerator::PrintOpBegin(WasmOp op)
  73. {
  74. if (lastOpId == opId) Output::Print(_u("\r\n"));
  75. lastOpId = ++opId;
  76. const int depth = m_blockInfos.Count() - 1;
  77. if (depth > 0)
  78. {
  79. Output::SkipToColumn(depth);
  80. }
  81. const auto PrintSignature = [this](uint32 sigId)
  82. {
  83. if (sigId < m_module->GetSignatureCount())
  84. {
  85. Output::Print(_u(" "));
  86. WasmSignature* sig = m_module->GetSignature(sigId);
  87. sig->Dump(64);
  88. }
  89. else
  90. {
  91. Output::Print(_u(" invalid signature id %u"), sigId);
  92. }
  93. };
  94. switch (op)
  95. {
  96. #define WASM_OPCODE(opname, ...) \
  97. case wb##opname: \
  98. Output::Print(_u(#opname)); \
  99. break;
  100. #include "WasmBinaryOpCodes.h"
  101. }
  102. switch (op)
  103. {
  104. case wbIf:
  105. case wbLoop:
  106. case wbBlock:
  107. if (GetReader()->m_currentNode.block.IsSingleResult())
  108. {
  109. Output::Print(_u(" () -> %s"), GetTypeName(GetReader()->m_currentNode.block.GetSingleResult()));
  110. }
  111. else
  112. {
  113. PrintSignature(GetReader()->m_currentNode.block.GetSignatureId()); break;
  114. }
  115. break;
  116. case wbBr:
  117. case wbBrIf: Output::Print(_u(" depth: %u"), GetReader()->m_currentNode.br.depth); break;
  118. case wbBrTable: Output::Print(_u(" %u cases, default: %u"), GetReader()->m_currentNode.brTable.numTargets, GetReader()->m_currentNode.brTable.defaultTarget); break;
  119. case wbCallIndirect: PrintSignature(GetReader()->m_currentNode.call.num); break;
  120. case wbCall:
  121. {
  122. uint32 id = GetReader()->m_currentNode.call.num;
  123. if (id < m_module->GetWasmFunctionCount())
  124. {
  125. FunctionIndexTypes::Type funcType = GetReader()->m_currentNode.call.funcType;
  126. switch (funcType)
  127. {
  128. case Wasm::FunctionIndexTypes::Invalid: Output::Print(_u(" (invalid) ")); break;
  129. case Wasm::FunctionIndexTypes::ImportThunk: Output::Print(_u(" (thunk) ")); break;
  130. case Wasm::FunctionIndexTypes::Function: Output::Print(_u(" (func) ")); break;
  131. case Wasm::FunctionIndexTypes::Import: Output::Print(_u(" (import) ")); break;
  132. default: Output::Print(_u(" (unknown)")); break;
  133. }
  134. auto func = this->m_module->GetWasmFunctionInfo(id);
  135. func->GetBody()->DumpFullFunctionName();
  136. }
  137. else
  138. {
  139. Output::Print(_u(" invalid id %u"), id);
  140. }
  141. break;
  142. }
  143. case wbSetLocal:
  144. case wbGetLocal:
  145. case wbTeeLocal:
  146. case wbGetGlobal:
  147. case wbSetGlobal: Output::Print(_u(" (%d)"), GetReader()->m_currentNode.var.num); break;
  148. case wbI32Const: Output::Print(_u(" (%d, 0x%x)"), GetReader()->m_currentNode.cnst.i32, GetReader()->m_currentNode.cnst.i32); break;
  149. case wbI64Const: Output::Print(_u(" (%lld, 0x%llx)"), GetReader()->m_currentNode.cnst.i64, GetReader()->m_currentNode.cnst.i64); break;
  150. case wbF32Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f32); break;
  151. case wbF64Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f64); break;
  152. #define WASM_MEM_OPCODE(opname, ...) case wb##opname: // FallThrough
  153. #include "WasmBinaryOpCodes.h"
  154. {
  155. const uint8 alignment = GetReader()->m_currentNode.mem.alignment;
  156. const uint32 offset = GetReader()->m_currentNode.mem.offset;
  157. switch (((!!alignment) << 1) | (!!offset))
  158. {
  159. case 0: // no alignment, no offset
  160. Output::Print(_u(" [i]")); break;
  161. case 1: // no alignment, offset
  162. Output::Print(_u(" [i + %u (0x%x)]"), offset, offset); break;
  163. case 2: // alignment, no offset
  164. Output::Print(_u(" [i & ~0x%x]"), (1 << alignment) - 1); break;
  165. case 3: // alignment, offset
  166. Output::Print(_u(" [i + %u (0x%x) & ~0x%x]"), offset, offset, (1 << alignment) - 1); break;
  167. }
  168. break;
  169. }
  170. }
  171. Output::SkipToColumn(40);
  172. PrintTypeStack();
  173. }
  174. void WasmBytecodeGenerator::PrintOpEnd()
  175. {
  176. if (lastOpId == opId)
  177. {
  178. ++opId;
  179. Output::Print(_u(" -> "));
  180. PrintTypeStack();
  181. Output::Print(_u("\r\n"));
  182. }
  183. }
  184. #endif
  185. /* static */
  186. Js::AsmJsRetType WasmToAsmJs::GetAsmJsReturnType(WasmTypes::WasmType wasmType)
  187. {
  188. switch (wasmType)
  189. {
  190. case WasmTypes::I32: return Js::AsmJsRetType::Signed;
  191. case WasmTypes::I64: return Js::AsmJsRetType::Int64;
  192. case WasmTypes::F32: return Js::AsmJsRetType::Float;
  193. case WasmTypes::F64: return Js::AsmJsRetType::Double;
  194. case WasmTypes::Void: return Js::AsmJsRetType::Void;
  195. #ifdef ENABLE_WASM_SIMD
  196. case WasmTypes::M128:
  197. Simd::EnsureSimdIsEnabled();
  198. return Js::AsmJsRetType::Float32x4;
  199. #endif
  200. default:
  201. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  202. throw WasmCompilationException(_u("Unknown return type %u"), wasmType);
  203. }
  204. }
  205. /* static */
  206. Js::AsmJsVarType WasmToAsmJs::GetAsmJsVarType(WasmTypes::WasmType wasmType)
  207. {
  208. Js::AsmJsVarType asmType = Js::AsmJsVarType::Int;
  209. switch (wasmType)
  210. {
  211. case WasmTypes::I32: return Js::AsmJsVarType::Int;
  212. case WasmTypes::I64: return Js::AsmJsVarType::Int64;
  213. case WasmTypes::F32: return Js::AsmJsVarType::Float;
  214. case WasmTypes::F64: return Js::AsmJsVarType::Double;
  215. #ifdef ENABLE_WASM_SIMD
  216. case WasmTypes::M128:
  217. Simd::EnsureSimdIsEnabled();
  218. return Js::AsmJsVarType::Float32x4;
  219. #endif
  220. default:
  221. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  222. throw WasmCompilationException(_u("Unknown var type %u"), wasmType);
  223. }
  224. }
  225. typedef bool(*SectionProcessFunc)(WasmModuleGenerator*);
  226. typedef void(*AfterSectionCallback)(WasmModuleGenerator*);
  227. WasmModuleGenerator::WasmModuleGenerator(Js::ScriptContext* scriptContext, Js::WebAssemblySource* src) :
  228. m_sourceInfo(src->GetSourceInfo()),
  229. m_scriptContext(scriptContext),
  230. m_recycler(scriptContext->GetRecycler())
  231. {
  232. m_module = RecyclerNewFinalized(m_recycler, Js::WebAssemblyModule, scriptContext, src->GetBuffer(), src->GetBufferLength(), scriptContext->GetLibrary()->GetWebAssemblyModuleType());
  233. m_sourceInfo->EnsureInitialized(0);
  234. m_sourceInfo->GetSrcInfo()->sourceContextInfo->EnsureInitialized();
  235. }
  236. Js::WebAssemblyModule* WasmModuleGenerator::GenerateModule()
  237. {
  238. Js::AutoProfilingPhase wasmPhase(m_scriptContext, Js::WasmReaderPhase);
  239. Unused(wasmPhase);
  240. m_module->GetReader()->InitializeReader();
  241. BVStatic<bSectLimit + 1> visitedSections;
  242. SectionCode nextExpectedSection = bSectCustom;
  243. while (true)
  244. {
  245. SectionHeader sectionHeader = GetReader()->ReadNextSection();
  246. SectionCode sectionCode = sectionHeader.code;
  247. if (sectionCode == bSectLimit)
  248. {
  249. TRACE_WASM(PHASE_TRACE1(Js::WasmSectionPhase), _u("Done reading module's sections"));
  250. break;
  251. }
  252. // Make sure dependency for this section has been seen
  253. SectionCode precedent = SectionInfo::All[sectionCode].precedent;
  254. if (precedent != bSectLimit && !visitedSections.Test(precedent))
  255. {
  256. throw WasmCompilationException(_u("%s section missing before %s"),
  257. SectionInfo::All[precedent].name,
  258. sectionHeader.name);
  259. }
  260. visitedSections.Set(sectionCode);
  261. // Custom section are allowed in any order
  262. if (sectionCode != bSectCustom)
  263. {
  264. if (sectionCode < nextExpectedSection)
  265. {
  266. throw WasmCompilationException(_u("Invalid Section %s"), sectionHeader.name);
  267. }
  268. nextExpectedSection = SectionCode(sectionCode + 1);
  269. }
  270. if (!GetReader()->ProcessCurrentSection())
  271. {
  272. throw WasmCompilationException(_u("Error while reading section %s"), sectionHeader.name);
  273. }
  274. }
  275. uint32 funcCount = m_module->GetWasmFunctionCount();
  276. SourceContextInfo * sourceContextInfo = m_sourceInfo->GetSrcInfo()->sourceContextInfo;
  277. m_sourceInfo->EnsureInitialized(funcCount);
  278. sourceContextInfo->nextLocalFunctionId += funcCount;
  279. sourceContextInfo->EnsureInitialized();
  280. for (uint32 i = 0; i < funcCount; ++i)
  281. {
  282. GenerateFunctionHeader(i);
  283. }
  284. #if ENABLE_DEBUG_CONFIG_OPTIONS
  285. WasmFunctionInfo* firstThunk = nullptr, *lastThunk = nullptr;
  286. for (uint32 i = 0; i < funcCount; ++i)
  287. {
  288. WasmFunctionInfo* info = m_module->GetWasmFunctionInfo(i);
  289. Assert(info->GetBody());
  290. if (PHASE_TRACE(Js::WasmInOutPhase, info->GetBody()))
  291. {
  292. uint32 index = m_module->GetWasmFunctionCount();
  293. WasmFunctionInfo* newInfo = m_module->AddWasmFunctionInfo(info->GetSignature());
  294. if (!firstThunk)
  295. {
  296. firstThunk = newInfo;
  297. }
  298. lastThunk = newInfo;
  299. GenerateFunctionHeader(index);
  300. m_module->SwapWasmFunctionInfo(i, index);
  301. m_module->AttachCustomInOutTracingReader(newInfo, index);
  302. }
  303. }
  304. if (firstThunk)
  305. {
  306. int sourceId = (int)firstThunk->GetBody()->GetSourceContextId();
  307. char16 range[64];
  308. swprintf_s(range, 64, _u("%d.%d-%d.%d"),
  309. sourceId, firstThunk->GetBody()->GetLocalFunctionId(),
  310. sourceId, lastThunk->GetBody()->GetLocalFunctionId());
  311. char16 offFullJit[128];
  312. swprintf_s(offFullJit, 128, _u("-off:fulljit:%s"), range);
  313. char16 offSimpleJit[128];
  314. swprintf_s(offSimpleJit, 128, _u("-off:simplejit:%s"), range);
  315. char16 offLoopJit[128];
  316. swprintf_s(offLoopJit, 128, _u("-off:jitloopbody:%s"), range);
  317. char16* argv[] = { nullptr, offFullJit, offSimpleJit, offLoopJit };
  318. CmdLineArgsParser parser(nullptr);
  319. parser.Parse(ARRAYSIZE(argv), argv);
  320. }
  321. #endif
  322. // If we see a FunctionSignatures section we need to see a FunctionBodies section
  323. if (visitedSections.Test(bSectFunction) && !visitedSections.Test(bSectFunctionBodies))
  324. {
  325. throw WasmCompilationException(_u("Missing required section: %s"), SectionInfo::All[bSectFunctionBodies].name);
  326. }
  327. return m_module;
  328. }
  329. WasmBinaryReader* WasmModuleGenerator::GetReader() const
  330. {
  331. return m_module->GetReader();
  332. }
  333. void WasmModuleGenerator::GenerateFunctionHeader(uint32 index)
  334. {
  335. WasmFunctionInfo* wasmInfo = m_module->GetWasmFunctionInfo(index);
  336. if (!wasmInfo)
  337. {
  338. throw WasmCompilationException(_u("Invalid function index %u"), index);
  339. }
  340. const char16* functionName = nullptr;
  341. int nameLength = 0;
  342. if (wasmInfo->GetNameLength() > 0)
  343. {
  344. functionName = wasmInfo->GetName();
  345. nameLength = wasmInfo->GetNameLength();
  346. }
  347. else
  348. {
  349. for (uint32 iExport = 0; iExport < m_module->GetExportCount(); ++iExport)
  350. {
  351. Wasm::WasmExport* wasmExport = m_module->GetExport(iExport);
  352. if (wasmExport &&
  353. wasmExport->kind == ExternalKinds::Function &&
  354. wasmExport->nameLength > 0 &&
  355. m_module->GetFunctionIndexType(wasmExport->index) == FunctionIndexTypes::Function &&
  356. wasmExport->index == wasmInfo->GetNumber())
  357. {
  358. nameLength = wasmExport->nameLength + 16;
  359. char16 * autoName = RecyclerNewArrayLeafZ(m_recycler, char16, nameLength);
  360. nameLength = swprintf_s(autoName, nameLength, _u("%s[%u]"), wasmExport->name, wasmInfo->GetNumber());
  361. functionName = autoName;
  362. break;
  363. }
  364. }
  365. }
  366. if (!functionName)
  367. {
  368. char16* autoName = RecyclerNewArrayLeafZ(m_recycler, char16, 32);
  369. nameLength = swprintf_s(autoName, 32, _u("wasm-function[%u]"), wasmInfo->GetNumber());
  370. functionName = autoName;
  371. }
  372. Js::FunctionBody* body = Js::FunctionBody::NewFromRecycler(
  373. m_scriptContext,
  374. functionName,
  375. nameLength,
  376. 0,
  377. 0,
  378. m_sourceInfo,
  379. m_sourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId,
  380. wasmInfo->GetNumber(),
  381. Js::FunctionInfo::Attributes::ErrorOnNew,
  382. Js::FunctionBody::Flags_None
  383. #ifdef PERF_COUNTERS
  384. , false /* is function from deferred deserialized proxy */
  385. #endif
  386. );
  387. wasmInfo->SetBody(body);
  388. // TODO (michhol): numbering
  389. body->SetSourceInfo(0);
  390. body->AllocateAsmJsFunctionInfo();
  391. body->SetIsAsmJsFunction(true);
  392. body->SetIsAsmjsMode(true);
  393. body->SetIsWasmFunction(true);
  394. WasmReaderInfo* readerInfo = RecyclerNew(m_recycler, WasmReaderInfo);
  395. readerInfo->m_funcInfo = wasmInfo;
  396. readerInfo->m_module = m_module;
  397. Js::WasmLibrary::ResetFunctionBodyDefaultEntryPoint(body);
  398. Js::AsmJsFunctionInfo* info = body->GetAsmJsFunctionInfo();
  399. info->SetWasmReaderInfo(readerInfo);
  400. info->SetWebAssemblyModule(m_module);
  401. Js::ArgSlot paramCount = wasmInfo->GetParamCount();
  402. info->SetArgCount(paramCount);
  403. info->SetWasmSignature(wasmInfo->GetSignature());
  404. Js::ArgSlot argSizeLength = max(paramCount, 3ui16);
  405. info->SetArgSizeArrayLength(argSizeLength);
  406. uint32* argSizeArray = RecyclerNewArrayLeafZ(m_recycler, uint32, argSizeLength);
  407. info->SetArgsSizesArray(argSizeArray);
  408. if (paramCount > 0)
  409. {
  410. // +1 here because asm.js includes the this pointer
  411. body->SetInParamsCount(paramCount + 1);
  412. body->SetReportedInParamsCount(paramCount + 1);
  413. info->SetArgTypeArray(RecyclerNewArrayLeaf(m_recycler, Js::AsmJsVarType::Which, paramCount));
  414. }
  415. else
  416. {
  417. // overwrite default value in this case
  418. body->SetHasImplicitArgIns(false);
  419. }
  420. for (Js::ArgSlot i = 0; i < paramCount; ++i)
  421. {
  422. WasmTypes::WasmType type = wasmInfo->GetSignature()->GetParam(i);
  423. info->SetArgType(WasmToAsmJs::GetAsmJsVarType(type), i);
  424. argSizeArray[i] = wasmInfo->GetSignature()->GetParamSize(i);
  425. }
  426. info->SetArgByteSize(wasmInfo->GetSignature()->GetParamsSize());
  427. if (wasmInfo->GetSignature()->GetResultCount() <= 1)
  428. {
  429. WasmTypes::WasmType returnType = wasmInfo->GetSignature()->GetResultCount() == 1 ? wasmInfo->GetSignature()->GetResult(0) : WasmTypes::Void;
  430. info->SetReturnType(WasmToAsmJs::GetAsmJsReturnType(returnType));
  431. }
  432. else
  433. {
  434. throw WasmCompilationException(_u("Multi return values not supported"));
  435. }
  436. }
  437. WAsmJs::RegisterSpace* AllocateRegisterSpace(ArenaAllocator* alloc, WAsmJs::Types)
  438. {
  439. return Anew(alloc, WAsmJs::RegisterSpace, 1);
  440. }
  441. void WasmBytecodeGenerator::GenerateFunctionBytecode(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo, bool validateOnly /*= false*/)
  442. {
  443. WasmBytecodeGenerator generator(scriptContext, readerinfo, validateOnly);
  444. generator.GenerateFunction();
  445. if (!generator.GetReader()->IsCurrentFunctionCompleted())
  446. {
  447. throw WasmCompilationException(_u("Invalid function format"));
  448. }
  449. }
  450. void WasmBytecodeGenerator::ValidateFunction(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo)
  451. {
  452. GenerateFunctionBytecode(scriptContext, readerinfo, true);
  453. }
  454. WasmBytecodeGenerator::WasmBytecodeGenerator(Js::ScriptContext* scriptContext, WasmReaderInfo* readerInfo, bool validateOnly) :
  455. m_scriptContext(scriptContext),
  456. m_alloc(_u("WasmBytecodeGen"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory),
  457. m_evalStack(&m_alloc),
  458. mTypedRegisterAllocator(&m_alloc, AllocateRegisterSpace, Simd::IsEnabled() ? 0 : 1 << WAsmJs::SIMD),
  459. m_blockInfos(&m_alloc),
  460. currentProfileId(0),
  461. isUnreachable(false)
  462. {
  463. m_emptyWriter = Anew(&m_alloc, Js::EmptyWasmByteCodeWriter);
  464. m_writer = m_originalWriter = validateOnly ? m_emptyWriter : Anew(&m_alloc, Js::WasmByteCodeWriter);
  465. m_writer->Create();
  466. m_funcInfo = readerInfo->m_funcInfo;
  467. m_module = readerInfo->m_module;
  468. // Init reader to current func offset
  469. GetReader()->SeekToFunctionBody(m_funcInfo);
  470. const uint32 estimated = GetReader()->EstimateCurrentFunctionBytecodeSize();
  471. m_writer->InitData(&m_alloc, estimated);
  472. }
  473. void WasmBytecodeGenerator::GenerateFunction()
  474. {
  475. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  476. if (DO_WASM_TRACE_BYTECODE)
  477. {
  478. Output::Print(_u("Generate WebAssembly Bytecode: "));
  479. GetFunctionBody()->DumpFullFunctionName();
  480. Output::Print(_u("\n"));
  481. }
  482. #endif
  483. if (PHASE_OFF(Js::WasmBytecodePhase, GetFunctionBody()))
  484. {
  485. throw WasmCompilationException(_u("Compilation skipped"));
  486. }
  487. Js::AutoProfilingPhase functionProfiler(m_scriptContext, Js::WasmBytecodePhase);
  488. Unused(functionProfiler);
  489. m_maxArgOutDepth = 0;
  490. m_writer->Begin(GetFunctionBody(), &m_alloc);
  491. struct AutoCleanupGeneratorState
  492. {
  493. WasmBytecodeGenerator* gen;
  494. AutoCleanupGeneratorState(WasmBytecodeGenerator* gen) : gen(gen) {}
  495. ~AutoCleanupGeneratorState()
  496. {
  497. if (gen)
  498. {
  499. TRACE_WASM(PHASE_TRACE(Js::WasmBytecodePhase, gen->GetFunctionBody()), _u("\nHad Compilation error!"));
  500. gen->GetReader()->FunctionEnd();
  501. gen->m_originalWriter->Reset();
  502. }
  503. }
  504. void Complete() { gen = nullptr; }
  505. };
  506. AutoCleanupGeneratorState autoCleanupGeneratorState(this);
  507. Js::ByteCodeLabel exitLabel = m_writer->DefineLabel();
  508. m_funcInfo->SetExitLabel(exitLabel);
  509. EnregisterLocals();
  510. // The function's yield type is the return type
  511. Js::ByteCodeLabel blockLabel = m_writer->DefineLabel();
  512. WasmBlock funcBlockData;
  513. funcBlockData.SetSignatureId(m_funcInfo->GetSignature()->GetSignatureId());
  514. m_funcBlock = PushLabel(funcBlockData, blockLabel, true, false);
  515. EnterEvalStackScope(m_funcBlock);
  516. EmitBlockCommon(m_funcBlock);
  517. m_writer->MarkAsmJsLabel(blockLabel);
  518. PolymorphicEmitInfo yieldInfo = PopLabel(blockLabel);
  519. if (yieldInfo.Count() > 0 || m_funcInfo->GetResultCount() == 0)
  520. {
  521. EmitReturnExpr(&yieldInfo);
  522. }
  523. DebugPrintOpEnd();
  524. ExitEvalStackScope(m_funcBlock);
  525. SetUnreachableState(false);
  526. m_writer->MarkAsmJsLabel(exitLabel);
  527. m_writer->EmptyAsm(Js::OpCodeAsmJs::Ret);
  528. m_writer->SetCallSiteCount(this->currentProfileId);
  529. m_writer->End();
  530. GetReader()->FunctionEnd();
  531. autoCleanupGeneratorState.Complete();
  532. // Make sure we don't have any unforeseen exceptions as we finalize the body
  533. AutoDisableInterrupt autoDisableInterrupt(m_scriptContext->GetThreadContext(), true);
  534. #if DBG_DUMP
  535. if ((
  536. PHASE_DUMP(Js::WasmBytecodePhase, GetFunctionBody()) ||
  537. PHASE_DUMP(Js::ByteCodePhase, GetFunctionBody())
  538. ) && !IsValidating())
  539. {
  540. Js::AsmJsByteCodeDumper::Dump(GetFunctionBody(), &mTypedRegisterAllocator, nullptr);
  541. }
  542. if (PHASE_DUMP(Js::WasmOpCodeDistributionPhase, GetFunctionBody()))
  543. {
  544. m_module->GetReader()->PrintOps();
  545. }
  546. #endif
  547. Js::AsmJsFunctionInfo* info = GetFunctionBody()->GetAsmJsFunctionInfo();
  548. mTypedRegisterAllocator.CommitToFunctionBody(GetFunctionBody());
  549. mTypedRegisterAllocator.CommitToFunctionInfo(info, GetFunctionBody());
  550. GetFunctionBody()->CheckAndSetOutParamMaxDepth(m_maxArgOutDepth);
  551. autoDisableInterrupt.Completed();
  552. }
  553. void WasmBytecodeGenerator::EnregisterLocals()
  554. {
  555. uint32 nLocals = m_funcInfo->GetLocalCount();
  556. m_locals = AnewArray(&m_alloc, WasmLocal, nLocals);
  557. m_funcInfo->GetBody()->SetFirstTmpReg(nLocals);
  558. for (uint32 i = 0; i < nLocals; ++i)
  559. {
  560. WasmTypes::WasmType type = m_funcInfo->GetLocal(i);
  561. WasmRegisterSpace* regSpace = GetRegisterSpace(type);
  562. m_locals[i] = WasmLocal(regSpace->AcquireRegister(), type);
  563. // Zero only the locals not corresponding to formal parameters.
  564. if (i >= m_funcInfo->GetParamCount()) {
  565. switch (type)
  566. {
  567. case WasmTypes::F32:
  568. m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, m_locals[i].location, 0.0f);
  569. break;
  570. case WasmTypes::F64:
  571. m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, m_locals[i].location, 0.0);
  572. break;
  573. case WasmTypes::I32:
  574. m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, m_locals[i].location, 0);
  575. break;
  576. case WasmTypes::I64:
  577. m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, m_locals[i].location, 0);
  578. break;
  579. #ifdef ENABLE_WASM_SIMD
  580. case WasmTypes::M128:
  581. {
  582. Simd::EnsureSimdIsEnabled();
  583. m_writer->WasmSimdConst(Js::OpCodeAsmJs::Simd128_LdC, m_locals[i].location, 0, 0, 0, 0);
  584. break;
  585. }
  586. #endif
  587. default:
  588. Assume(UNREACHED);
  589. }
  590. }
  591. }
  592. }
  593. template <size_t lanes>
  594. EmitInfo WasmBytecodeGenerator::EmitSimdBuildExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  595. {
  596. const WasmTypes::WasmType resultType = signature[0];
  597. const WasmTypes::WasmType type = signature[1];
  598. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  599. EmitInfo args[lanes];
  600. for (uint i = 0; i < lanes; i++)
  601. {
  602. args[i] = PopEvalStack(type);
  603. }
  604. switch (lanes)
  605. {
  606. case 4:
  607. m_writer->AsmReg5(op, resultReg, args[3].location, args[2].location, args[1].location, args[0].location);
  608. break;
  609. case 8:
  610. m_writer->AsmReg9(op, resultReg, args[7].location, args[6].location, args[5].location, args[4].location, args[3].location, args[2].location, args[1].location, args[0].location);
  611. break;
  612. case 16:
  613. m_writer->AsmReg17(op, resultReg, args[15].location, args[14].location, args[13].location, args[12].location, args[11].location, args[10].location, args[9].location, args[8].location, args[7].location, args[6].location, args[5].location, args[4].location, args[3].location, args[2].location, args[1].location, args[0].location);
  614. break;
  615. default:
  616. Assert(UNREACHED);
  617. }
  618. for (uint i = 0; i < lanes; i++)
  619. {
  620. ReleaseLocation(&args[i]);
  621. }
  622. return EmitInfo(resultReg, resultType);
  623. }
  624. void WasmBytecodeGenerator::EmitExpr(WasmOp op)
  625. {
  626. DebugPrintOp(op);
  627. switch (op)
  628. {
  629. #define WASM_OPCODE(opname, opcode, sig, imp, wat) \
  630. case opcode: \
  631. if (!imp) throw WasmCompilationException(_u("Operator %s is Not Yet Implemented"), _u(wat)); break;
  632. #include "WasmBinaryOpCodes.h"
  633. default:
  634. break;
  635. }
  636. PolymorphicEmitInfo info;
  637. switch (op)
  638. {
  639. case wbGetGlobal:
  640. info = EmitGetGlobal();
  641. break;
  642. case wbSetGlobal:
  643. info = EmitSetGlobal();
  644. break;
  645. case wbGetLocal:
  646. info = EmitGetLocal();
  647. break;
  648. case wbSetLocal:
  649. info = EmitSetLocal(false);
  650. break;
  651. case wbTeeLocal:
  652. info = EmitSetLocal(true);
  653. break;
  654. case wbReturn:
  655. EmitReturnExpr();
  656. info = EmitInfo(WasmTypes::Any);
  657. break;
  658. case wbF32Const:
  659. info = EmitConst(WasmTypes::F32, GetReader()->m_currentNode.cnst);
  660. break;
  661. case wbF64Const:
  662. info = EmitConst(WasmTypes::F64, GetReader()->m_currentNode.cnst);
  663. break;
  664. case wbI32Const:
  665. info = EmitConst(WasmTypes::I32, GetReader()->m_currentNode.cnst);
  666. break;
  667. case wbI64Const:
  668. info = EmitConst(WasmTypes::I64, GetReader()->m_currentNode.cnst);
  669. break;
  670. #ifdef ENABLE_WASM_SIMD
  671. case wbM128Const:
  672. Simd::EnsureSimdIsEnabled();
  673. info = EmitConst(WasmTypes::M128, GetReader()->m_currentNode.cnst);
  674. break;
  675. #endif
  676. case wbBlock:
  677. info = EmitBlock();
  678. break;
  679. case wbLoop:
  680. info = EmitLoop();
  681. break;
  682. case wbCall:
  683. info = EmitCall<wbCall>();
  684. break;
  685. case wbCallIndirect:
  686. info = EmitCall<wbCallIndirect>();
  687. break;
  688. case wbIf:
  689. info = EmitIfElseExpr();
  690. break;
  691. case wbElse:
  692. throw WasmCompilationException(_u("Unexpected else opcode"));
  693. case wbEnd:
  694. throw WasmCompilationException(_u("Unexpected end opcode"));
  695. case wbBr:
  696. EmitBr();
  697. info = EmitInfo(WasmTypes::Any);
  698. break;
  699. case wbBrIf:
  700. info = EmitBrIf();
  701. break;
  702. case wbSelect:
  703. info = EmitSelect();
  704. break;
  705. case wbBrTable:
  706. EmitBrTable();
  707. info = EmitInfo(WasmTypes::Any);
  708. break;
  709. case wbDrop:
  710. info = EmitDrop();
  711. break;
  712. case wbNop:
  713. return;
  714. case wbMemorySize:
  715. {
  716. SetUsesMemory(0);
  717. Js::RegSlot tempReg = GetRegisterSpace(WasmTypes::I32)->AcquireTmpRegister();
  718. info = EmitInfo(tempReg, WasmTypes::I32);
  719. m_writer->AsmReg1(Js::OpCodeAsmJs::MemorySize_Int, tempReg);
  720. break;
  721. }
  722. case wbMemoryGrow:
  723. {
  724. info = EmitGrowMemory();
  725. break;
  726. }
  727. case wbUnreachable:
  728. m_writer->EmptyAsm(Js::OpCodeAsmJs::Unreachable_Void);
  729. SetUnreachableState(true);
  730. info = EmitInfo(WasmTypes::Any);
  731. break;
  732. #ifdef ENABLE_WASM_SIMD
  733. case wbM128Bitselect:
  734. Simd::EnsureSimdIsEnabled();
  735. info = EmitM128BitSelect();
  736. break;
  737. case wbV8X16Shuffle:
  738. Simd::EnsureSimdIsEnabled();
  739. info = EmitV8X16Shuffle();
  740. break;
  741. #define WASM_EXTRACTLANE_OPCODE(opname, opcode, sig, asmjsop, ...) \
  742. case wb##opname: \
  743. Simd::EnsureSimdIsEnabled();\
  744. info = EmitExtractLaneExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  745. break;
  746. #define WASM_REPLACELANE_OPCODE(opname, opcode, sig, asmjsop, ...) \
  747. case wb##opname: \
  748. Simd::EnsureSimdIsEnabled();\
  749. info = EmitReplaceLaneExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  750. break;
  751. #endif
  752. #define WASM_MEMREAD_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  753. case wb##opname: \
  754. Assert(WasmOpCodeSignatures::n##sig > 0);\
  755. info = EmitMemAccess<false, false>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  756. break;
  757. #define WASM_ATOMICREAD_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  758. case wb##opname: \
  759. Assert(WasmOpCodeSignatures::n##sig > 0);\
  760. info = EmitMemAccess<false, true>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  761. break;
  762. #define WASM_MEMSTORE_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  763. case wb##opname: \
  764. Assert(WasmOpCodeSignatures::n##sig > 0);\
  765. info = EmitMemAccess<true, false>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  766. break;
  767. #define WASM_ATOMICSTORE_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  768. case wb##opname: \
  769. Assert(WasmOpCodeSignatures::n##sig > 0);\
  770. info = EmitMemAccess<true, true>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  771. break;
  772. #define WASM_SIMD_MEMREAD_OPCODE(opname, opcode, sig, asmjsop, viewtype, dataWidth, ...) \
  773. case wb##opname: \
  774. Assert(WasmOpCodeSignatures::n##sig > 0);\
  775. info = EmitSimdMemAccess(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig, viewtype, dataWidth, false); \
  776. break;
  777. #define WASM_SIMD_MEMSTORE_OPCODE(opname, opcode, sig, asmjsop, viewtype, dataWidth, ...) \
  778. case wb##opname: \
  779. Assert(WasmOpCodeSignatures::n##sig > 0);\
  780. info = EmitSimdMemAccess(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig, viewtype, dataWidth, true); \
  781. break;
  782. #define WASM_BINARY_OPCODE(opname, opcode, sig, asmjsop, imp, wat) \
  783. case wb##opname: \
  784. Assert(WasmOpCodeSignatures::n##sig == 3);\
  785. info = EmitBinExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  786. break;
  787. #define WASM_UNARY__OPCODE(opname, opcode, sig, asmjsop, imp, wat) \
  788. case wb##opname: \
  789. Assert(WasmOpCodeSignatures::n##sig == 2);\
  790. info = EmitUnaryExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  791. break;
  792. #define WASM_SIMD_BUILD_OPCODE(opname, opcode, sig, asmjop, lanes, ...) \
  793. case wb##opname: \
  794. Assert(WasmOpCodeSignatures::n##sig == 2);\
  795. info = EmitSimdBuildExpr<lanes>(Js::OpCodeAsmJs::##asmjop, WasmOpCodeSignatures::sig); \
  796. break;
  797. #define WASM_EMPTY__OPCODE(opname, opcode, asmjsop, imp, wat) \
  798. case wb##opname: \
  799. m_writer->EmptyAsm(Js::OpCodeAsmJs::##asmjsop);\
  800. break;
  801. #include "WasmBinaryOpCodes.h"
  802. default:
  803. throw WasmCompilationException(_u("Unknown expression's op 0x%X"), op);
  804. }
  805. PushEvalStack(info);
  806. DebugPrintOpEnd();
  807. }
  808. EmitInfo WasmBytecodeGenerator::EmitGetGlobal()
  809. {
  810. uint32 globalIndex = GetReader()->m_currentNode.var.num;
  811. WasmGlobal* global = m_module->GetGlobal(globalIndex);
  812. WasmTypes::WasmType type = global->GetType();
  813. Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
  814. CompileAssert(WasmTypes::I32 == 1);
  815. CompileAssert(WasmTypes::I64 == 2);
  816. CompileAssert(WasmTypes::F32 == 3);
  817. CompileAssert(WasmTypes::F64 == 4);
  818. static const Js::OpCodeAsmJs globalOpcodes[] = {
  819. Js::OpCodeAsmJs::LdSlot_Int,
  820. Js::OpCodeAsmJs::LdSlot_Long,
  821. Js::OpCodeAsmJs::LdSlot_Flt,
  822. Js::OpCodeAsmJs::LdSlot_Db
  823. };
  824. WasmRegisterSpace* regSpace = GetRegisterSpace(type);
  825. Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
  826. EmitInfo info(tmpReg, type);
  827. m_writer->AsmSlot(globalOpcodes[type - 1], tmpReg, WasmBytecodeGenerator::ModuleEnvRegister, slot);
  828. return info;
  829. }
  830. EmitInfo WasmBytecodeGenerator::EmitSetGlobal()
  831. {
  832. uint32 globalIndex = GetReader()->m_currentNode.var.num;
  833. WasmGlobal* global = m_module->GetGlobal(globalIndex);
  834. Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
  835. WasmTypes::WasmType type = global->GetType();
  836. EmitInfo info = PopEvalStack(type);
  837. CompileAssert(WasmTypes::I32 == 1);
  838. CompileAssert(WasmTypes::I64 == 2);
  839. CompileAssert(WasmTypes::F32 == 3);
  840. CompileAssert(WasmTypes::F64 == 4);
  841. static const Js::OpCodeAsmJs globalOpcodes[] = {
  842. Js::OpCodeAsmJs::StSlot_Int,
  843. Js::OpCodeAsmJs::StSlot_Long,
  844. Js::OpCodeAsmJs::StSlot_Flt,
  845. Js::OpCodeAsmJs::StSlot_Db
  846. };
  847. m_writer->AsmSlot(globalOpcodes[type - 1], info.location, WasmBytecodeGenerator::ModuleEnvRegister, slot);
  848. ReleaseLocation(&info);
  849. return EmitInfo();
  850. }
  851. EmitInfo WasmBytecodeGenerator::EmitGetLocal()
  852. {
  853. uint32 localIndex = GetReader()->m_currentNode.var.num;
  854. if (m_funcInfo->GetLocalCount() <= localIndex)
  855. {
  856. throw WasmCompilationException(_u("%u is not a valid local"), localIndex);
  857. }
  858. WasmLocal local = m_locals[localIndex];
  859. Js::OpCodeAsmJs op = GetLoadOp(local.type);
  860. WasmRegisterSpace* regSpace = GetRegisterSpace(local.type);
  861. Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
  862. m_writer->AsmReg2(op, tmpReg, local.location);
  863. return EmitInfo(tmpReg, local.type);
  864. }
  865. EmitInfo WasmBytecodeGenerator::EmitSetLocal(bool tee)
  866. {
  867. uint32 localNum = GetReader()->m_currentNode.var.num;
  868. if (localNum >= m_funcInfo->GetLocalCount())
  869. {
  870. throw WasmCompilationException(_u("%u is not a valid local"), localNum);
  871. }
  872. WasmLocal local = m_locals[localNum];
  873. EmitInfo info = PopEvalStack(local.type);
  874. m_writer->AsmReg2(GetLoadOp(local.type), local.location, info.location);
  875. if (tee)
  876. {
  877. if (info.type == WasmTypes::Any)
  878. {
  879. throw WasmCompilationException(_u("Can't tee_local unreachable values"));
  880. }
  881. return info;
  882. }
  883. else
  884. {
  885. ReleaseLocation(&info);
  886. return EmitInfo();
  887. }
  888. }
  889. EmitInfo WasmBytecodeGenerator::EmitConst(WasmTypes::WasmType type, WasmConstLitNode cnst)
  890. {
  891. Js::RegSlot tmpReg = GetRegisterSpace(type)->AcquireTmpRegister();
  892. EmitInfo dst(tmpReg, type);
  893. EmitLoadConst(dst, cnst);
  894. return dst;
  895. }
  896. void WasmBytecodeGenerator::EmitLoadConst(EmitInfo dst, WasmConstLitNode cnst)
  897. {
  898. switch (dst.type)
  899. {
  900. case WasmTypes::F32:
  901. m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, dst.location, cnst.f32);
  902. break;
  903. case WasmTypes::F64:
  904. m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, dst.location, cnst.f64);
  905. break;
  906. case WasmTypes::I32:
  907. m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, dst.location, cnst.i32);
  908. break;
  909. case WasmTypes::I64:
  910. m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, dst.location, cnst.i64);
  911. break;
  912. #ifdef ENABLE_WASM_SIMD
  913. case WasmTypes::M128:
  914. {
  915. Simd::EnsureSimdIsEnabled();
  916. m_writer->WasmSimdConst(Js::OpCodeAsmJs::Simd128_LdC, dst.location, cnst.v128[0], cnst.v128[1], cnst.v128[2], cnst.v128[3]);
  917. break;
  918. }
  919. #endif
  920. default:
  921. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  922. throw WasmCompilationException(_u("Unknown type %u"), dst.type);
  923. }
  924. }
  925. WasmConstLitNode WasmBytecodeGenerator::GetZeroCnst()
  926. {
  927. WasmConstLitNode cnst = {0};
  928. return cnst;
  929. }
  930. void WasmBytecodeGenerator::EnsureStackAvailable()
  931. {
  932. if (!ThreadContext::IsCurrentStackAvailable(Js::Constants::MinStackCompile))
  933. {
  934. throw WasmCompilationException(_u("Maximum supported nested blocks reached"));
  935. }
  936. }
  937. void WasmBytecodeGenerator::EmitBlockCommon(BlockInfo* blockInfo, bool* endOnElse /*= nullptr*/)
  938. {
  939. EnsureStackAvailable();
  940. bool canResetUnreachable = !IsUnreachable();
  941. WasmOp op;
  942. EnterEvalStackScope(blockInfo);
  943. if(endOnElse) *endOnElse = false;
  944. do {
  945. op = GetReader()->ReadExpr();
  946. if (op == wbEnd)
  947. {
  948. break;
  949. }
  950. if (endOnElse && op == wbElse)
  951. {
  952. *endOnElse = true;
  953. break;
  954. }
  955. EmitExpr(op);
  956. } while (true);
  957. DebugPrintOp(op);
  958. if (blockInfo->HasYield())
  959. {
  960. PolymorphicEmitInfo info = PopStackPolymorphic(blockInfo);
  961. YieldToBlock(blockInfo, info);
  962. ReleaseLocation(&info);
  963. }
  964. ExitEvalStackScope(blockInfo);
  965. if (canResetUnreachable)
  966. {
  967. SetUnreachableState(false);
  968. }
  969. }
  970. PolymorphicEmitInfo WasmBytecodeGenerator::EmitBlock()
  971. {
  972. Js::ByteCodeLabel blockLabel = m_writer->DefineLabel();
  973. BlockInfo* blockInfo = PushLabel(GetReader()->m_currentNode.block, blockLabel);
  974. EmitBlockCommon(blockInfo);
  975. m_writer->MarkAsmJsLabel(blockLabel);
  976. PolymorphicEmitInfo yieldInfo = PopLabel(blockLabel);
  977. // block yields last value
  978. return yieldInfo;
  979. }
  980. PolymorphicEmitInfo WasmBytecodeGenerator::EmitLoop()
  981. {
  982. Js::ByteCodeLabel loopTailLabel = m_writer->DefineLabel();
  983. Js::ByteCodeLabel loopHeadLabel = m_writer->DefineLabel();
  984. Js::ByteCodeLabel loopLandingPadLabel = m_writer->DefineLabel();
  985. // Push possibly yielding loop label before capturing all the yielding registers
  986. BlockInfo* implicitBlockInfo = PushLabel(GetReader()->m_currentNode.block, loopTailLabel);
  987. // Save the first tmp (per type) of this loop to discern a yield outside the loop in jitloopbody scenario
  988. Js::RegSlot curRegs[WAsmJs::LIMIT];
  989. for (WAsmJs::Types type = WAsmJs::Types(0); type != WAsmJs::LIMIT; type = WAsmJs::Types(type + 1))
  990. {
  991. uint32 minYield = 0;
  992. if (!mTypedRegisterAllocator.IsTypeExcluded(type))
  993. {
  994. CompileAssert(sizeof(minYield) == sizeof(Js::RegSlot));
  995. minYield = static_cast<uint32>(mTypedRegisterAllocator.GetRegisterSpace(type)->PeekNextTmpRegister());
  996. }
  997. curRegs[type] = minYield;
  998. }
  999. uint32 loopId = m_writer->WasmLoopStart(loopHeadLabel, curRegs);
  1000. // Internally we create a block for loop to exit, but semantically, they don't exist so pop it
  1001. m_blockInfos.Pop();
  1002. // We don't want nested block to jump directly to the loop header
  1003. // instead, jump to the landing pad and let it jump back to the loop header
  1004. PushLabel(GetReader()->m_currentNode.block, loopLandingPadLabel, false);
  1005. EmitBlockCommon(implicitBlockInfo);
  1006. PopLabel(loopLandingPadLabel);
  1007. // By default we don't loop, jump over the landing pad
  1008. m_writer->AsmBr(loopTailLabel);
  1009. m_writer->MarkAsmJsLabel(loopLandingPadLabel);
  1010. m_writer->AsmBr(loopHeadLabel);
  1011. // Put the implicit block back on the stack and yield the last expression to it
  1012. m_blockInfos.Push(implicitBlockInfo);
  1013. m_writer->MarkAsmJsLabel(loopTailLabel);
  1014. // Pop the implicit block to resolve the yield correctly
  1015. PolymorphicEmitInfo loopInfo = PopLabel(loopTailLabel);
  1016. m_writer->ExitLoop(loopId);
  1017. return loopInfo;
  1018. }
  1019. template<WasmOp wasmOp>
  1020. PolymorphicEmitInfo WasmBytecodeGenerator::EmitCall()
  1021. {
  1022. uint32 funcNum = Js::Constants::UninitializedValue;
  1023. uint32 signatureId = Js::Constants::UninitializedValue;
  1024. WasmSignature* calleeSignature = nullptr;
  1025. Js::ProfileId profileId = Js::Constants::NoProfileId;
  1026. EmitInfo indirectIndexInfo;
  1027. const bool isImportCall = GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Import;
  1028. Assert(isImportCall || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Function || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::ImportThunk);
  1029. switch (wasmOp)
  1030. {
  1031. case wbCall:
  1032. {
  1033. funcNum = GetReader()->m_currentNode.call.num;
  1034. WasmFunctionInfo* calleeInfo = m_module->GetWasmFunctionInfo(funcNum);
  1035. calleeSignature = calleeInfo->GetSignature();
  1036. // currently only handle inlining internal function calls
  1037. // in future we can expand to all calls by adding checks in inliner and falling back to call in case ScriptFunction doesn't match
  1038. if (GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Function && !PHASE_TRACE1(Js::WasmInOutPhase))
  1039. {
  1040. profileId = GetNextProfileId();
  1041. }
  1042. break;
  1043. }
  1044. case wbCallIndirect:
  1045. indirectIndexInfo = PopEvalStack(WasmTypes::I32, _u("Indirect call index must be int type"));
  1046. signatureId = GetReader()->m_currentNode.call.num;
  1047. calleeSignature = m_module->GetSignature(signatureId);
  1048. break;
  1049. default:
  1050. Assume(UNREACHED);
  1051. }
  1052. const auto argOverflow = []
  1053. {
  1054. throw WasmCompilationException(_u("Argument size too big"));
  1055. };
  1056. // emit start call
  1057. Js::ArgSlot argSize;
  1058. Js::OpCodeAsmJs startCallOp;
  1059. if (isImportCall)
  1060. {
  1061. argSize = ArgSlotMath::Mul(calleeSignature->GetParamCount(), sizeof(Js::Var), argOverflow);
  1062. startCallOp = Js::OpCodeAsmJs::StartCall;
  1063. }
  1064. else
  1065. {
  1066. startCallOp = Js::OpCodeAsmJs::I_StartCall;
  1067. argSize = calleeSignature->GetParamsSize();
  1068. }
  1069. // Add return value
  1070. argSize = ArgSlotMath::Add(argSize, sizeof(Js::Var), argOverflow);
  1071. if (!Math::IsAligned<Js::ArgSlot>(argSize, sizeof(Js::Var)))
  1072. {
  1073. AssertMsg(UNREACHED, "Wasm argument size should always be Var aligned");
  1074. throw WasmCompilationException(_u("Internal Error"));
  1075. }
  1076. m_writer->AsmStartCall(startCallOp, argSize);
  1077. Js::ArgSlot nArgs = calleeSignature->GetParamCount();
  1078. // copy args into a list so they could be generated in the right order (FIFO)
  1079. EmitInfo* argsList = AnewArray(&m_alloc, EmitInfo, nArgs);
  1080. for (int i = int(nArgs) - 1; i >= 0; --i)
  1081. {
  1082. EmitInfo info = PopEvalStack(calleeSignature->GetParam((Js::ArgSlot)i), _u("Call argument does not match formal type"));
  1083. // We can release the location of the arguments now, because we won't create new temps between start/call
  1084. argsList[i] = info;
  1085. }
  1086. // Skip the this pointer (aka undefined)
  1087. uint32 argLoc = 1;
  1088. for (Js::ArgSlot i = 0; i < nArgs; ++i)
  1089. {
  1090. EmitInfo info = argsList[i];
  1091. Js::OpCodeAsmJs argOp = Js::OpCodeAsmJs::Nop;
  1092. switch (info.type)
  1093. {
  1094. case WasmTypes::F32:
  1095. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Flt : Js::OpCodeAsmJs::I_ArgOut_Flt;
  1096. break;
  1097. case WasmTypes::F64:
  1098. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Db : Js::OpCodeAsmJs::I_ArgOut_Db;
  1099. break;
  1100. case WasmTypes::I32:
  1101. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Int : Js::OpCodeAsmJs::I_ArgOut_Int;
  1102. break;
  1103. case WasmTypes::I64:
  1104. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Long : Js::OpCodeAsmJs::I_ArgOut_Long;
  1105. break;
  1106. #ifdef ENABLE_WASM_SIMD
  1107. case WasmTypes::M128:
  1108. Simd::EnsureSimdIsEnabled();
  1109. argOp = isImportCall ? Js::OpCodeAsmJs::Simd128_ArgOut_F4 : Js::OpCodeAsmJs::Simd128_I_ArgOut_F4;
  1110. break;
  1111. #endif
  1112. case WasmTypes::Any:
  1113. // In unreachable mode allow any type as argument since we won't actually emit the call
  1114. Assert(IsUnreachable());
  1115. if (IsUnreachable())
  1116. {
  1117. argOp = Js::OpCodeAsmJs::ArgOut_Int;
  1118. break;
  1119. }
  1120. // Fall through
  1121. default:
  1122. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  1123. throw WasmCompilationException(_u("Unknown argument type %u"), info.type);
  1124. }
  1125. m_writer->AsmReg2(argOp, argLoc, info.location);
  1126. // Calculated next argument Js::Var location
  1127. if (isImportCall)
  1128. {
  1129. ++argLoc;
  1130. }
  1131. else
  1132. {
  1133. const Js::ArgSlot currentArgSize = calleeSignature->GetParamSize(i);
  1134. Assert(Math::IsAligned<Js::ArgSlot>(currentArgSize, sizeof(Js::Var)));
  1135. argLoc += currentArgSize / sizeof(Js::Var);
  1136. }
  1137. }
  1138. Js::RegSlot funcReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1139. // emit call
  1140. switch (wasmOp)
  1141. {
  1142. case wbCall:
  1143. {
  1144. uint32 offset = isImportCall ? m_module->GetImportFuncOffset() : m_module->GetFuncOffset();
  1145. uint32 index = UInt32Math::Add(offset, funcNum);
  1146. m_writer->AsmSlot(Js::OpCodeAsmJs::LdSlot, funcReg, Js::AsmJsFunctionMemory::ModuleEnvRegister, index);
  1147. break;
  1148. }
  1149. case wbCallIndirect:
  1150. {
  1151. Js::RegSlot slotReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1152. m_writer->AsmSlot(Js::OpCodeAsmJs::LdSlotArr, slotReg, Js::AsmJsFunctionMemory::ModuleEnvRegister, m_module->GetTableEnvironmentOffset());
  1153. m_writer->AsmSlot(Js::OpCodeAsmJs::LdArr_WasmFunc, funcReg, slotReg, indirectIndexInfo.location);
  1154. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(slotReg);
  1155. m_writer->AsmReg1IntConst1(Js::OpCodeAsmJs::CheckSignature, funcReg, calleeSignature->GetSignatureId());
  1156. break;
  1157. }
  1158. default:
  1159. Assume(UNREACHED);
  1160. }
  1161. // calculate number of RegSlots(Js::Var) the call consumes
  1162. PolymorphicEmitInfo retInfo;
  1163. retInfo.Init(calleeSignature->GetResultCount(), &m_alloc);
  1164. for (uint32 i = 0; i < calleeSignature->GetResultCount(); ++i)
  1165. {
  1166. retInfo.SetInfo(EmitInfo(calleeSignature->GetResult(i)), i);
  1167. }
  1168. Js::ArgSlot args;
  1169. if (isImportCall)
  1170. {
  1171. args = calleeSignature->GetParamCount();
  1172. ArgSlotMath::Inc(args, argOverflow);
  1173. Js::RegSlot varRetReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1174. AssertOrFailFastMsg(calleeSignature->GetResultCount() <= 1, "Multiple results from function imports not supported");
  1175. WasmTypes::WasmType singleResType = calleeSignature->GetResultCount() > 0 ? calleeSignature->GetResult(0) : WasmTypes::Void;
  1176. m_writer->AsmCall(Js::OpCodeAsmJs::Call, varRetReg, funcReg, args, WasmToAsmJs::GetAsmJsReturnType(singleResType), profileId);
  1177. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(varRetReg);
  1178. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(funcReg);
  1179. ReleaseLocation(&indirectIndexInfo);
  1180. //registers need to be released from higher ordinals to lower
  1181. for (uint32 i = nArgs; i > 0; --i)
  1182. {
  1183. ReleaseLocation(&(argsList[i - 1]));
  1184. }
  1185. // emit result coercion
  1186. if (calleeSignature->GetResultCount() > 0)
  1187. {
  1188. Js::OpCodeAsmJs convertOp = Js::OpCodeAsmJs::Nop;
  1189. switch (singleResType)
  1190. {
  1191. case WasmTypes::F32:
  1192. convertOp = Js::OpCodeAsmJs::Conv_VTF;
  1193. break;
  1194. case WasmTypes::F64:
  1195. convertOp = Js::OpCodeAsmJs::Conv_VTD;
  1196. break;
  1197. case WasmTypes::I32:
  1198. convertOp = Js::OpCodeAsmJs::Conv_VTI;
  1199. break;
  1200. case WasmTypes::I64:
  1201. convertOp = Js::OpCodeAsmJs::Conv_VTL;
  1202. break;
  1203. #ifdef ENABLE_WASM_SIMD
  1204. case WasmTypes::M128:
  1205. throw WasmCompilationException(_u("Return type: m128 not supported in import calls"));
  1206. #endif
  1207. default:
  1208. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  1209. throw WasmCompilationException(_u("Unknown call return type %u"), singleResType);
  1210. }
  1211. Js::RegSlot location = GetRegisterSpace(singleResType)->AcquireTmpRegister();
  1212. retInfo.SetInfo(EmitInfo(location, singleResType), 0);
  1213. m_writer->AsmReg2(convertOp, location, varRetReg);
  1214. }
  1215. }
  1216. else
  1217. {
  1218. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(funcReg);
  1219. ReleaseLocation(&indirectIndexInfo);
  1220. //registers need to be released from higher ordinals to lower
  1221. for (uint32 i = nArgs; i > 0; --i)
  1222. {
  1223. ReleaseLocation(&(argsList[i - 1]));
  1224. }
  1225. for (uint32 i = 0; i < calleeSignature->GetResultCount(); ++i)
  1226. {
  1227. EmitInfo info(calleeSignature->GetResult(i));
  1228. info.location = GetRegisterSpace(info.type)->AcquireTmpRegister();
  1229. retInfo.SetInfo(info, i);
  1230. }
  1231. EmitInfo singleResultInfo = retInfo.Count() > 0 ? retInfo.GetInfo(0) : EmitInfo(WasmTypes::Void);
  1232. args = (Js::ArgSlot)(::ceil((double)(argSize / sizeof(Js::Var))));
  1233. // todo:: add bytecode to call and set aside multi results
  1234. m_writer->AsmCall(Js::OpCodeAsmJs::I_Call, singleResultInfo.location, funcReg, args, WasmToAsmJs::GetAsmJsReturnType(singleResultInfo.type), profileId);
  1235. }
  1236. AdeleteArray(&m_alloc, nArgs, argsList);
  1237. // WebAssemblyArrayBuffer is not detachable, no need to check for detached state here
  1238. // track stack requirements for out params
  1239. // + 1 for return address
  1240. uint32 maxDepthForLevel = args + 1;
  1241. if (maxDepthForLevel > m_maxArgOutDepth)
  1242. {
  1243. m_maxArgOutDepth = maxDepthForLevel;
  1244. }
  1245. return retInfo;
  1246. }
  1247. PolymorphicEmitInfo WasmBytecodeGenerator::EmitIfElseExpr()
  1248. {
  1249. Js::ByteCodeLabel falseLabel = m_writer->DefineLabel();
  1250. Js::ByteCodeLabel endLabel = m_writer->DefineLabel();
  1251. EmitInfo checkExpr = PopEvalStack(WasmTypes::I32, _u("If expression must have type i32"));
  1252. ReleaseLocation(&checkExpr);
  1253. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrFalse_Int, falseLabel, checkExpr.location);
  1254. BlockInfo* blockInfo = PushLabel(GetReader()->m_currentNode.block, endLabel);
  1255. bool endOnElse = false;
  1256. EmitBlockCommon(blockInfo, &endOnElse);
  1257. EnsureYield(blockInfo);
  1258. m_writer->AsmBr(endLabel);
  1259. m_writer->MarkAsmJsLabel(falseLabel);
  1260. EmitInfo retInfo;
  1261. EmitInfo falseExpr;
  1262. if (endOnElse)
  1263. {
  1264. if (blockInfo->HasYield())
  1265. {
  1266. // Indicate that we need this block to yield a value
  1267. blockInfo->didYield = false;
  1268. }
  1269. EmitBlockCommon(blockInfo);
  1270. EnsureYield(blockInfo);
  1271. }
  1272. else if (blockInfo->HasYield())
  1273. {
  1274. throw WasmCompilationException(_u("Expected an else block when 'if' returns a value"));
  1275. }
  1276. m_writer->MarkAsmJsLabel(endLabel);
  1277. return PopLabel(endLabel);
  1278. }
  1279. void WasmBytecodeGenerator::EmitBrTable()
  1280. {
  1281. const uint32 numTargets = GetReader()->m_currentNode.brTable.numTargets;
  1282. const uint32* targetTable = GetReader()->m_currentNode.brTable.targetTable;
  1283. const uint32 defaultEntry = GetReader()->m_currentNode.brTable.defaultTarget;
  1284. // Compile scrutinee
  1285. EmitInfo scrutineeInfo = PopStackPolymorphic(EmitInfo(WasmTypes::I32), _u("br_table expression must be of type i32")).GetInfo(0);
  1286. m_writer->AsmReg2(Js::OpCodeAsmJs::BeginSwitch_Int, scrutineeInfo.location, scrutineeInfo.location);
  1287. PolymorphicEmitInfo yieldValue;
  1288. BlockInfo* defaultBlockInfo = GetBlockInfo(defaultEntry);
  1289. if (defaultBlockInfo->HasYield())
  1290. {
  1291. yieldValue = PopStackPolymorphic(defaultBlockInfo);
  1292. }
  1293. // Compile cases
  1294. for (uint32 i = 0; i < numTargets; i++)
  1295. {
  1296. uint32 target = targetTable[i];
  1297. BlockInfo* blockInfo = GetBlockInfo(target);
  1298. if (!defaultBlockInfo->IsEquivalent(blockInfo))
  1299. {
  1300. throw WasmCompilationException(_u("br_table target %u signature mismatch"));
  1301. }
  1302. YieldToBlock(blockInfo, yieldValue);
  1303. m_writer->AsmBrReg1Const1(Js::OpCodeAsmJs::Case_IntConst, blockInfo->label, scrutineeInfo.location, i);
  1304. }
  1305. YieldToBlock(defaultBlockInfo, yieldValue);
  1306. m_writer->AsmBr(defaultBlockInfo->label, Js::OpCodeAsmJs::EndSwitch_Int);
  1307. ReleaseLocation(&scrutineeInfo);
  1308. ReleaseLocation(&yieldValue);
  1309. SetUnreachableState(true);
  1310. }
  1311. EmitInfo WasmBytecodeGenerator::EmitGrowMemory()
  1312. {
  1313. SetUsesMemory(0);
  1314. EmitInfo info = PopEvalStack(WasmTypes::I32, _u("Invalid type for GrowMemory"));
  1315. m_writer->AsmReg2(Js::OpCodeAsmJs::GrowMemory, info.location, info.location);
  1316. return info;
  1317. }
  1318. EmitInfo WasmBytecodeGenerator::EmitDrop()
  1319. {
  1320. EmitInfo info = PopValuePolymorphic();
  1321. ReleaseLocation(&info);
  1322. return EmitInfo();
  1323. }
  1324. EmitInfo WasmBytecodeGenerator::EmitBinExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1325. {
  1326. WasmTypes::WasmType resultType = signature[0];
  1327. WasmTypes::WasmType lhsType = signature[1];
  1328. WasmTypes::WasmType rhsType = signature[2];
  1329. EmitInfo rhs = PopEvalStack(rhsType);
  1330. EmitInfo lhs = PopEvalStack(lhsType);
  1331. ReleaseLocation(&rhs);
  1332. ReleaseLocation(&lhs);
  1333. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1334. m_writer->AsmReg3(op, resultReg, lhs.location, rhs.location);
  1335. return EmitInfo(resultReg, resultType);
  1336. }
  1337. EmitInfo WasmBytecodeGenerator::EmitUnaryExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1338. {
  1339. WasmTypes::WasmType resultType = signature[0];
  1340. WasmTypes::WasmType inputType = signature[1];
  1341. EmitInfo info = PopEvalStack(inputType);
  1342. ReleaseLocation(&info);
  1343. if (resultType == WasmTypes::Void)
  1344. {
  1345. m_writer->AsmReg2(op, 0, info.location);
  1346. return EmitInfo();
  1347. }
  1348. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1349. m_writer->AsmReg2(op, resultReg, info.location);
  1350. return EmitInfo(resultReg, resultType);
  1351. }
  1352. #ifdef ENABLE_WASM_SIMD
  1353. void WasmBytecodeGenerator::CheckLaneIndex(Js::OpCodeAsmJs op, const uint index)
  1354. {
  1355. uint numLanes;
  1356. switch (op)
  1357. {
  1358. case Js::OpCodeAsmJs::Simd128_ExtractLane_I2:
  1359. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I2:
  1360. case Js::OpCodeAsmJs::Simd128_ExtractLane_D2:
  1361. case Js::OpCodeAsmJs::Simd128_ReplaceLane_D2:
  1362. numLanes = 2;
  1363. break;
  1364. case Js::OpCodeAsmJs::Simd128_ExtractLane_I4:
  1365. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I4:
  1366. case Js::OpCodeAsmJs::Simd128_ExtractLane_F4:
  1367. case Js::OpCodeAsmJs::Simd128_ReplaceLane_F4:
  1368. numLanes = 4;
  1369. break;
  1370. case Js::OpCodeAsmJs::Simd128_ExtractLane_I8:
  1371. case Js::OpCodeAsmJs::Simd128_ExtractLane_U8:
  1372. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I8:
  1373. case Js::OpCodeAsmJs::Simd128_ReplaceLane_U8:
  1374. numLanes = 8;
  1375. break;
  1376. case Js::OpCodeAsmJs::Simd128_ExtractLane_I16:
  1377. case Js::OpCodeAsmJs::Simd128_ExtractLane_U16:
  1378. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I16:
  1379. case Js::OpCodeAsmJs::Simd128_ReplaceLane_U16:
  1380. numLanes = 16;
  1381. break;
  1382. default:
  1383. Assert(UNREACHED);
  1384. numLanes = 0;
  1385. }
  1386. if (index >= numLanes)
  1387. {
  1388. throw WasmCompilationException(_u("index is out of range"));
  1389. }
  1390. }
  1391. EmitInfo WasmBytecodeGenerator::EmitLaneIndex(Js::OpCodeAsmJs op)
  1392. {
  1393. const uint index = GetReader()->m_currentNode.lane.index;
  1394. CheckLaneIndex(op, index);
  1395. WasmConstLitNode dummy;
  1396. dummy.i32 = index;
  1397. return EmitConst(WasmTypes::I32, dummy);
  1398. }
  1399. EmitInfo WasmBytecodeGenerator::EmitReplaceLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature) {
  1400. const WasmTypes::WasmType resultType = signature[0];
  1401. const WasmTypes::WasmType valueType = signature[1];
  1402. EmitInfo valueArg = PopEvalStack(valueType, _u("lane argument type mismatch"));
  1403. EmitInfo simdArg = PopEvalStack(WasmTypes::M128, _u("simd argument type mismatch"));
  1404. Assert(resultType == WasmTypes::M128);
  1405. EmitInfo indexInfo = EmitLaneIndex(op);
  1406. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1407. EmitInfo result(resultReg, resultType);
  1408. m_writer->AsmReg4(op, resultReg, simdArg.location, indexInfo.location, valueArg.location);
  1409. ReleaseLocation(&indexInfo);
  1410. return result;
  1411. }
  1412. EmitInfo WasmBytecodeGenerator::EmitM128BitSelect()
  1413. {
  1414. EmitInfo mask = PopEvalStack(WasmTypes::M128);
  1415. EmitInfo arg2Info = PopEvalStack(WasmTypes::M128);
  1416. EmitInfo arg1Info = PopEvalStack(WasmTypes::M128);
  1417. Js::RegSlot resultReg = GetRegisterSpace(WasmTypes::M128)->AcquireTmpRegister();
  1418. EmitInfo resultInfo(resultReg, WasmTypes::M128);
  1419. m_writer->AsmReg4(Js::OpCodeAsmJs::Simd128_BitSelect_I4, resultReg, arg1Info.location, arg2Info.location, mask.location);
  1420. return resultInfo;
  1421. }
  1422. EmitInfo WasmBytecodeGenerator::EmitV8X16Shuffle()
  1423. {
  1424. EmitInfo arg2Info = PopEvalStack(WasmTypes::M128);
  1425. EmitInfo arg1Info = PopEvalStack(WasmTypes::M128);
  1426. Js::RegSlot resultReg = GetRegisterSpace(WasmTypes::M128)->AcquireTmpRegister();
  1427. EmitInfo resultInfo(resultReg, WasmTypes::M128);
  1428. uint8* indices = GetReader()->m_currentNode.shuffle.indices;
  1429. for (uint i = 0; i < Simd::MAX_LANES; i++)
  1430. {
  1431. if (indices[i] >= Simd::MAX_LANES * 2)
  1432. {
  1433. throw WasmCompilationException(_u("%u-th shuffle lane index is larger than %u"), i, (Simd::MAX_LANES * 2 -1));
  1434. }
  1435. }
  1436. m_writer->AsmShuffle(Js::OpCodeAsmJs::Simd128_Shuffle_V8X16, resultReg, arg1Info.location, arg2Info.location, indices);
  1437. return resultInfo;
  1438. }
  1439. EmitInfo WasmBytecodeGenerator::EmitExtractLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1440. {
  1441. WasmTypes::WasmType resultType = signature[0];
  1442. WasmTypes::WasmType simdArgType = signature[1];
  1443. EmitInfo simdArgInfo = PopEvalStack(simdArgType, _u("Argument should be of type M128"));
  1444. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1445. EmitInfo resultInfo(resultReg, resultType);
  1446. //put index into a register to reuse the existing infra in Interpreter and Compiler
  1447. EmitInfo indexInfo = EmitLaneIndex(op);
  1448. m_writer->AsmReg3(op, resultReg, simdArgInfo.location, indexInfo.location);
  1449. ReleaseLocation(&indexInfo);
  1450. ReleaseLocation(&simdArgInfo);
  1451. return resultInfo;
  1452. }
  1453. EmitInfo WasmBytecodeGenerator::EmitSimdMemAccess(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType, uint8 dataWidth, bool isStore)
  1454. {
  1455. WasmTypes::WasmType type = signature[0];
  1456. SetUsesMemory(0);
  1457. const uint32 mask = Js::ArrayBufferView::ViewMask[viewType];
  1458. const uint alignment = GetReader()->m_currentNode.mem.alignment;
  1459. const uint offset = GetReader()->m_currentNode.mem.offset;
  1460. if ((mask << 1) & (1 << alignment))
  1461. {
  1462. throw WasmCompilationException(_u("alignment must not be larger than natural"));
  1463. }
  1464. EmitInfo rhsInfo;
  1465. if (isStore)
  1466. {
  1467. rhsInfo = PopEvalStack(type, _u("Invalid type for store op"));
  1468. }
  1469. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1470. if (isStore)
  1471. {
  1472. m_writer->AsmSimdTypedArr(op, rhsInfo.location, exprInfo.location, dataWidth, viewType, offset);
  1473. ReleaseLocation(&rhsInfo);
  1474. ReleaseLocation(&exprInfo);
  1475. return EmitInfo();
  1476. }
  1477. Js::RegSlot resultReg = GetRegisterSpace(type)->AcquireTmpRegister();
  1478. m_writer->AsmSimdTypedArr(op, resultReg, exprInfo.location, dataWidth, viewType, offset);
  1479. EmitInfo yieldInfo = EmitInfo(resultReg, type);
  1480. ReleaseLocation(&exprInfo);
  1481. return yieldInfo;
  1482. }
  1483. #endif
  1484. template<bool isStore, bool isAtomic>
  1485. EmitInfo WasmBytecodeGenerator::EmitMemAccess(WasmOp wasmOp, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType)
  1486. {
  1487. Assert(!isAtomic || Wasm::Threads::IsEnabled());
  1488. WasmTypes::WasmType type = signature[0];
  1489. SetUsesMemory(0);
  1490. const uint32 naturalAlignment = Js::ArrayBufferView::NaturalAlignment[viewType];
  1491. const uint32 alignment = GetReader()->m_currentNode.mem.alignment;
  1492. const uint32 offset = GetReader()->m_currentNode.mem.offset;
  1493. if (alignment > naturalAlignment)
  1494. {
  1495. throw WasmCompilationException(_u("alignment must not be larger than natural"));
  1496. }
  1497. if (isAtomic && alignment != naturalAlignment)
  1498. {
  1499. throw WasmCompilationException(_u("invalid alignment for atomic RW. Expected %u, got %u"), naturalAlignment, alignment);
  1500. }
  1501. // Stores
  1502. if (isStore)
  1503. {
  1504. EmitInfo rhsInfo = PopEvalStack(type, _u("Invalid type for store op"));
  1505. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1506. Js::OpCodeAsmJs op = isAtomic ? Js::OpCodeAsmJs::StArrAtomic : Js::OpCodeAsmJs::StArrWasm;
  1507. m_writer->WasmMemAccess(op, rhsInfo.location, exprInfo.location, offset, viewType);
  1508. ReleaseLocation(&rhsInfo);
  1509. ReleaseLocation(&exprInfo);
  1510. return EmitInfo();
  1511. }
  1512. // Loads
  1513. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1514. ReleaseLocation(&exprInfo);
  1515. Js::RegSlot resultReg = GetRegisterSpace(type)->AcquireTmpRegister();
  1516. Js::OpCodeAsmJs op = isAtomic ? Js::OpCodeAsmJs::LdArrAtomic : Js::OpCodeAsmJs::LdArrWasm;
  1517. m_writer->WasmMemAccess(op, resultReg, exprInfo.location, offset, viewType);
  1518. return EmitInfo(resultReg, type);
  1519. }
  1520. void WasmBytecodeGenerator::EmitReturnExpr(PolymorphicEmitInfo* explicitRetInfo)
  1521. {
  1522. PolymorphicEmitInfo retExprInfo = explicitRetInfo ? *explicitRetInfo : PopStackPolymorphic(m_funcBlock);
  1523. for (uint32 i = 0; i < retExprInfo.Count(); ++i)
  1524. {
  1525. EmitInfo info = retExprInfo.GetInfo(i);
  1526. Js::OpCodeAsmJs retOp = GetReturnOp(info.type);
  1527. m_writer->Conv(retOp, 0, info.location);
  1528. ReleaseLocation(&info);
  1529. }
  1530. m_writer->AsmBr(m_funcInfo->GetExitLabel());
  1531. SetUnreachableState(true);
  1532. }
  1533. EmitInfo WasmBytecodeGenerator::EmitSelect()
  1534. {
  1535. EmitInfo conditionInfo = PopEvalStack(WasmTypes::I32, _u("select condition must have i32 type"));
  1536. EmitInfo falseInfo = PopValuePolymorphic();
  1537. EmitInfo trueInfo = PopEvalStack(falseInfo.type, _u("select operands must both have same type"));
  1538. ReleaseLocation(&conditionInfo);
  1539. ReleaseLocation(&falseInfo);
  1540. ReleaseLocation(&trueInfo);
  1541. if (IsUnreachable())
  1542. {
  1543. if (trueInfo.type == WasmTypes::Any)
  1544. {
  1545. // Report the type of falseInfo for type checking
  1546. return EmitInfo(falseInfo.type);
  1547. }
  1548. // Otherwise report the type of trueInfo for type checking
  1549. return EmitInfo(trueInfo.type);
  1550. }
  1551. WasmTypes::WasmType selectType = trueInfo.type;
  1552. EmitInfo resultInfo = EmitInfo(GetRegisterSpace(selectType)->AcquireTmpRegister(), selectType);
  1553. Js::ByteCodeLabel falseLabel = m_writer->DefineLabel();
  1554. Js::ByteCodeLabel doneLabel = m_writer->DefineLabel();
  1555. Js::OpCodeAsmJs loadOp = GetLoadOp(resultInfo.type);
  1556. // var result;
  1557. // if (!condition) goto:condFalse
  1558. // result = trueRes;
  1559. // goto:done;
  1560. //:condFalse
  1561. // result = falseRes;
  1562. //:done
  1563. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrFalse_Int, falseLabel, conditionInfo.location);
  1564. m_writer->AsmReg2(loadOp, resultInfo.location, trueInfo.location);
  1565. m_writer->AsmBr(doneLabel);
  1566. m_writer->MarkAsmJsLabel(falseLabel);
  1567. m_writer->AsmReg2(loadOp, resultInfo.location, falseInfo.location);
  1568. m_writer->MarkAsmJsLabel(doneLabel);
  1569. return resultInfo;
  1570. }
  1571. void WasmBytecodeGenerator::EmitBr()
  1572. {
  1573. uint32 depth = GetReader()->m_currentNode.br.depth;
  1574. BlockInfo* blockInfo = GetBlockInfo(depth);
  1575. if (blockInfo->HasYield())
  1576. {
  1577. PolymorphicEmitInfo info = PopStackPolymorphic(blockInfo);
  1578. YieldToBlock(blockInfo, info);
  1579. ReleaseLocation(&info);
  1580. }
  1581. m_writer->AsmBr(blockInfo->label);
  1582. SetUnreachableState(true);
  1583. }
  1584. PolymorphicEmitInfo WasmBytecodeGenerator::EmitBrIf()
  1585. {
  1586. uint32 depth = GetReader()->m_currentNode.br.depth;
  1587. EmitInfo conditionInfo = PopEvalStack(WasmTypes::I32, _u("br_if condition must have i32 type"));
  1588. ReleaseLocation(&conditionInfo);
  1589. PolymorphicEmitInfo info;
  1590. BlockInfo* blockInfo = GetBlockInfo(depth);
  1591. if (blockInfo->HasYield())
  1592. {
  1593. info = PopStackPolymorphic(blockInfo);
  1594. YieldToBlock(blockInfo, info);
  1595. if (info.IsUnreachable())
  1596. {
  1597. Assert(IsUnreachable());
  1598. Assert(info.Count() == blockInfo->yieldInfo.Count());
  1599. // Use the block's yield type to continue type check
  1600. for (uint32 i = 0; i < info.Count(); ++i)
  1601. {
  1602. info.SetInfo(EmitInfo(blockInfo->yieldInfo.GetInfo(i).type), i);
  1603. }
  1604. }
  1605. }
  1606. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrTrue_Int, blockInfo->label, conditionInfo.location);
  1607. return info;
  1608. }
  1609. Js::OpCodeAsmJs WasmBytecodeGenerator::GetLoadOp(WasmTypes::WasmType wasmType)
  1610. {
  1611. switch (wasmType)
  1612. {
  1613. case WasmTypes::F32:
  1614. return Js::OpCodeAsmJs::Ld_Flt;
  1615. case WasmTypes::F64:
  1616. return Js::OpCodeAsmJs::Ld_Db;
  1617. case WasmTypes::I32:
  1618. return Js::OpCodeAsmJs::Ld_Int;
  1619. case WasmTypes::I64:
  1620. return Js::OpCodeAsmJs::Ld_Long;
  1621. #ifdef ENABLE_WASM_SIMD
  1622. case WasmTypes::M128:
  1623. Simd::EnsureSimdIsEnabled();
  1624. return Js::OpCodeAsmJs::Simd128_Ld_F4;
  1625. #endif
  1626. case WasmTypes::Any:
  1627. // In unreachable mode load the any type like an int since we won't actually emit the load
  1628. Assert(IsUnreachable());
  1629. if (IsUnreachable())
  1630. {
  1631. return Js::OpCodeAsmJs::Ld_Int;
  1632. }
  1633. default:
  1634. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  1635. throw WasmCompilationException(_u("Unknown load operator %u"), wasmType);
  1636. }
  1637. }
  1638. Js::OpCodeAsmJs WasmBytecodeGenerator::GetReturnOp(WasmTypes::WasmType type)
  1639. {
  1640. Js::OpCodeAsmJs retOp = Js::OpCodeAsmJs::Nop;
  1641. switch (type)
  1642. {
  1643. case WasmTypes::F32:
  1644. retOp = Js::OpCodeAsmJs::Return_Flt;
  1645. break;
  1646. case WasmTypes::F64:
  1647. retOp = Js::OpCodeAsmJs::Return_Db;
  1648. break;
  1649. case WasmTypes::I32:
  1650. retOp = Js::OpCodeAsmJs::Return_Int;
  1651. break;
  1652. case WasmTypes::I64:
  1653. retOp = Js::OpCodeAsmJs::Return_Long;
  1654. break;
  1655. #ifdef ENABLE_WASM_SIMD
  1656. case WasmTypes::M128:
  1657. Simd::EnsureSimdIsEnabled();
  1658. retOp = Js::OpCodeAsmJs::Simd128_Return_F4;
  1659. break;
  1660. #endif
  1661. case WasmTypes::Any:
  1662. // In unreachable mode load the any type like an int since we won't actually emit the load
  1663. Assert(IsUnreachable());
  1664. if (IsUnreachable())
  1665. {
  1666. return Js::OpCodeAsmJs::Return_Int;
  1667. }
  1668. default:
  1669. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  1670. throw WasmCompilationException(_u("Unknown return type %u"), type);
  1671. }
  1672. return retOp;
  1673. }
  1674. void WasmBytecodeGenerator::ReleaseLocation(EmitInfo* info)
  1675. {
  1676. if (WasmTypes::IsLocalType(info->type))
  1677. {
  1678. GetRegisterSpace(info->type)->ReleaseLocation(info);
  1679. }
  1680. }
  1681. void WasmBytecodeGenerator::ReleaseLocation(PolymorphicEmitInfo* info)
  1682. {
  1683. for (uint32 i = 0; i < info->Count(); ++i)
  1684. {
  1685. ReleaseLocation(&info->GetInfo(i));
  1686. }
  1687. }
  1688. PolymorphicEmitInfo WasmBytecodeGenerator::EnsureYield(BlockInfo* blockInfo)
  1689. {
  1690. PolymorphicEmitInfo yieldEmitInfo;
  1691. if (blockInfo->HasYield())
  1692. {
  1693. yieldEmitInfo = blockInfo->yieldInfo;
  1694. if (!blockInfo->DidYield())
  1695. {
  1696. // Emit a load to the yield location to make sure we have a dest there
  1697. // Most likely we can't reach this code so the value doesn't matter
  1698. blockInfo->didYield = true;
  1699. for (uint32 i = 0; i < yieldEmitInfo.Count(); ++i)
  1700. {
  1701. EmitLoadConst(yieldEmitInfo.GetInfo(i), GetZeroCnst());
  1702. }
  1703. }
  1704. }
  1705. return yieldEmitInfo;
  1706. }
  1707. PolymorphicEmitInfo WasmBytecodeGenerator::PopLabel(Js::ByteCodeLabel labelValidation)
  1708. {
  1709. Assert(m_blockInfos.Count() > 0);
  1710. BlockInfo* blockInfo = m_blockInfos.Pop();
  1711. UNREFERENCED_PARAMETER(labelValidation);
  1712. Assert(blockInfo->label == labelValidation);
  1713. return EnsureYield(blockInfo);
  1714. }
  1715. BlockInfo* WasmBytecodeGenerator::PushLabel(WasmBlock blockData, Js::ByteCodeLabel label, bool addBlockYieldInfo, bool checkInParams)
  1716. {
  1717. BlockInfo* blockInfo = Anew(&m_alloc, BlockInfo);
  1718. blockInfo->label = label;
  1719. if (addBlockYieldInfo)
  1720. {
  1721. if (blockData.IsSingleResult())
  1722. {
  1723. if (blockData.GetSingleResult() != WasmTypes::Void)
  1724. {
  1725. blockInfo->yieldInfo.Init(EmitInfo(GetRegisterSpace(blockData.GetSingleResult())->AcquireTmpRegister(), blockData.GetSingleResult()));
  1726. }
  1727. }
  1728. else
  1729. {
  1730. uint32 sigId = blockData.GetSignatureId();
  1731. WasmSignature* signature = m_module->GetSignature(sigId);
  1732. Js::ArgSlot paramCount = signature->GetParamCount();
  1733. checkInParams = checkInParams && paramCount > 0;
  1734. PolymorphicEmitInfo inParams;
  1735. if (checkInParams)
  1736. {
  1737. inParams.Init(paramCount, &m_alloc);
  1738. // Pop the params in reverse order
  1739. for (int i = paramCount - 1; i >= 0; --i)
  1740. {
  1741. Js::ArgSlot iArg = (Js::ArgSlot)i;
  1742. EmitInfo param = PopEvalStack(signature->GetParam(iArg));
  1743. ReleaseLocation(&param);
  1744. inParams.SetInfo(param, iArg);
  1745. }
  1746. }
  1747. uint32 resultCount = signature->GetResultCount();
  1748. if (resultCount > 0)
  1749. {
  1750. blockInfo->yieldInfo.Init(resultCount, &m_alloc);
  1751. for (uint32 i = 0; i < resultCount; ++i)
  1752. {
  1753. WasmTypes::WasmType type = signature->GetResult(i);
  1754. blockInfo->yieldInfo.SetInfo(EmitInfo(GetRegisterSpace(type)->AcquireTmpRegister(), type), i);
  1755. }
  1756. }
  1757. if (checkInParams)
  1758. {
  1759. blockInfo->paramInfo.Init(paramCount, &m_alloc);
  1760. // Acquire tmp registers in order
  1761. for (uint32 i = 0; i < paramCount; ++i)
  1762. {
  1763. EmitInfo info = inParams.GetInfo(i);
  1764. EmitInfo newInfo = info;
  1765. newInfo.location = GetRegisterSpace(info.type)->AcquireTmpRegister();
  1766. blockInfo->paramInfo.SetInfo(newInfo, i);
  1767. }
  1768. // Todo:: Instead of moving inparams to new location,
  1769. // Treat inparams as local and bypass ReleaseLocation until we exit the scope
  1770. // Move in params to new location in reverse order
  1771. for (int i = paramCount - 1; i >= 0; --i)
  1772. {
  1773. Js::ArgSlot iArg = (Js::ArgSlot)i;
  1774. EmitInfo info = inParams.GetInfo(iArg);
  1775. EmitInfo newInfo = blockInfo->paramInfo.GetInfo(iArg);
  1776. m_writer->AsmReg2(GetLoadOp(newInfo.type), newInfo.location, info.location);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. m_blockInfos.Push(blockInfo);
  1782. return blockInfo;
  1783. }
  1784. void WasmBytecodeGenerator::YieldToBlock(BlockInfo* blockInfo, PolymorphicEmitInfo polyExpr)
  1785. {
  1786. if (blockInfo->HasYield() && !polyExpr.IsUnreachable())
  1787. {
  1788. PolymorphicEmitInfo polyYieldInfo = blockInfo->yieldInfo;
  1789. if (!polyYieldInfo.IsEquivalent(polyExpr))
  1790. {
  1791. throw WasmCompilationException(_u("Invalid yield type"));
  1792. }
  1793. if (!IsUnreachable())
  1794. {
  1795. blockInfo->didYield = true;
  1796. for (uint32 i = 0; i < polyExpr.Count(); ++i)
  1797. {
  1798. EmitInfo expr = polyExpr.GetInfo(i);
  1799. EmitInfo yieldInfo = polyYieldInfo.GetInfo(i);
  1800. m_writer->AsmReg2(GetReturnOp(expr.type), yieldInfo.location, expr.location);
  1801. }
  1802. }
  1803. }
  1804. }
  1805. BlockInfo* WasmBytecodeGenerator::GetBlockInfo(uint32 relativeDepth) const
  1806. {
  1807. if (relativeDepth >= (uint32)m_blockInfos.Count())
  1808. {
  1809. throw WasmCompilationException(_u("Invalid branch target"));
  1810. }
  1811. return m_blockInfos.Peek(relativeDepth);
  1812. }
  1813. Js::ProfileId
  1814. WasmBytecodeGenerator::GetNextProfileId()
  1815. {
  1816. Js::ProfileId nextProfileId = this->currentProfileId;
  1817. UInt16Math::Inc(this->currentProfileId);
  1818. return nextProfileId;
  1819. }
  1820. WasmRegisterSpace* WasmBytecodeGenerator::GetRegisterSpace(WasmTypes::WasmType type)
  1821. {
  1822. switch (type)
  1823. {
  1824. #if TARGET_32
  1825. case WasmTypes::Ptr:
  1826. #endif
  1827. case WasmTypes::I32: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::INT32);
  1828. #if TARGET_64
  1829. case WasmTypes::Ptr:
  1830. #endif
  1831. case WasmTypes::I64: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::INT64);
  1832. case WasmTypes::F32: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::FLOAT32);
  1833. case WasmTypes::F64: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::FLOAT64);
  1834. #ifdef ENABLE_WASM_SIMD
  1835. case WasmTypes::M128:
  1836. Simd::EnsureSimdIsEnabled();
  1837. return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::SIMD);
  1838. #endif
  1839. default:
  1840. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_M128_CHECK_TYPE>();
  1841. throw WasmCompilationException(_u("Unknown type %u"), type);
  1842. }
  1843. }
  1844. PolymorphicEmitInfo WasmBytecodeGenerator::PopStackPolymorphic(PolymorphicEmitInfo expectedTypes, const char16* mismatchMessage /*= nullptr*/)
  1845. {
  1846. PolymorphicEmitInfo info;
  1847. uint32 count = expectedTypes.Count();
  1848. info.Init(count, &m_alloc);
  1849. for (uint32 i = 0; i < count; ++i)
  1850. {
  1851. // Check the stack before popping, it is valid to yield nothing if we are Unreachable
  1852. if (IsUnreachable() && m_evalStack.Peek().type == WasmTypes::Limit)
  1853. {
  1854. info.SetInfo(EmitInfo(WasmTypes::Any), i);
  1855. }
  1856. else
  1857. {
  1858. info.SetInfo(PopEvalStack(expectedTypes.GetInfo(i).type, mismatchMessage), i);
  1859. }
  1860. }
  1861. return info;
  1862. }
  1863. PolymorphicEmitInfo WasmBytecodeGenerator::PopStackPolymorphic(const BlockInfo* blockInfo, const char16* mismatchMessage)
  1864. {
  1865. return PopStackPolymorphic(blockInfo->yieldInfo, mismatchMessage);
  1866. }
  1867. EmitInfo WasmBytecodeGenerator::PopEvalStack(WasmTypes::WasmType expectedType, const char16* mismatchMessage)
  1868. {
  1869. // The scope marker should at least be there
  1870. Assert(!m_evalStack.Empty());
  1871. EmitInfo info = m_evalStack.Pop();
  1872. if (info.type == WasmTypes::Limit)
  1873. {
  1874. throw WasmCompilationException(_u("Reached end of stack"));
  1875. }
  1876. if (expectedType != WasmTypes::Any &&
  1877. info.type != WasmTypes::Any &&
  1878. info.type != expectedType)
  1879. {
  1880. if (!mismatchMessage)
  1881. {
  1882. throw WasmCompilationException(_u("Type mismatch. Expected %s, got %s"), GetTypeName(expectedType), GetTypeName(info.type));
  1883. }
  1884. throw WasmCompilationException(mismatchMessage);
  1885. }
  1886. Assert(info.type != WasmTypes::Any || IsUnreachable());
  1887. return info;
  1888. }
  1889. void WasmBytecodeGenerator::PushEvalStack(PolymorphicEmitInfo info)
  1890. {
  1891. Assert(!m_evalStack.Empty());
  1892. for (uint32 i = 0; i < info.Count(); ++i)
  1893. {
  1894. m_evalStack.Push(info.GetInfo(i));
  1895. }
  1896. }
  1897. void WasmBytecodeGenerator::EnterEvalStackScope(const BlockInfo* blockInfo)
  1898. {
  1899. m_evalStack.Push(EmitInfo(WasmTypes::Limit));
  1900. // Push the in-params of the block upon entering the scope
  1901. for (uint32 i = 0; i < blockInfo->paramInfo.Count(); ++i)
  1902. {
  1903. m_evalStack.Push(blockInfo->paramInfo.GetInfo(i));
  1904. }
  1905. }
  1906. void WasmBytecodeGenerator::ExitEvalStackScope(const BlockInfo* blockInfo)
  1907. {
  1908. Assert(!m_evalStack.Empty());
  1909. EmitInfo info = m_evalStack.Pop();
  1910. // It is possible to have unconsumed Any type left on the stack, simply remove them
  1911. while (info.type == WasmTypes::Any)
  1912. {
  1913. Assert(!m_evalStack.Empty());
  1914. info = m_evalStack.Pop();
  1915. }
  1916. if (info.type != WasmTypes::Limit)
  1917. {
  1918. // Put info back on stack so we can write it to string
  1919. m_evalStack.Push(info);
  1920. char16 buf[512] = { 0 };
  1921. WriteTypeStackToString(buf, 512);
  1922. throw WasmCompilationException(_u("Expected stack to be empty, but has %s"), buf);
  1923. }
  1924. }
  1925. void WasmBytecodeGenerator::SetUnreachableState(bool isUnreachable)
  1926. {
  1927. m_writer = isUnreachable ? m_emptyWriter : m_originalWriter;
  1928. if (isUnreachable)
  1929. {
  1930. // Replace the current stack with the any type
  1931. Assert(!m_evalStack.Empty());
  1932. uint32 popped = 0;
  1933. while (m_evalStack.Top().type != WasmTypes::Limit)
  1934. {
  1935. EmitInfo info = m_evalStack.Pop();
  1936. ReleaseLocation(&info);
  1937. ++popped;
  1938. }
  1939. while (popped-- > 0)
  1940. {
  1941. m_evalStack.Push(EmitInfo(WasmTypes::Any));
  1942. }
  1943. }
  1944. this->isUnreachable = isUnreachable;
  1945. }
  1946. void WasmBytecodeGenerator::SetUsesMemory(uint32 memoryIndex)
  1947. {
  1948. // Only support one memory at this time
  1949. Assert(memoryIndex == 0);
  1950. if (!m_module->HasMemory() && !m_module->HasMemoryImport())
  1951. {
  1952. throw WasmCompilationException(_u("unknown memory"));
  1953. }
  1954. GetFunctionBody()->GetAsmJsFunctionInfo()->SetUsesHeapBuffer(true);
  1955. }
  1956. Wasm::WasmReaderBase* WasmBytecodeGenerator::GetReader() const
  1957. {
  1958. if (m_funcInfo->GetCustomReader())
  1959. {
  1960. return m_funcInfo->GetCustomReader();
  1961. }
  1962. return m_module->GetReader();
  1963. }
  1964. void WasmCompilationException::FormatError(const char16* _msg, va_list arglist)
  1965. {
  1966. char16 buf[2048];
  1967. _vsnwprintf_s(buf, _countof(buf), _TRUNCATE, _msg, arglist);
  1968. errorMsg = SysAllocString(buf);
  1969. }
  1970. WasmCompilationException::WasmCompilationException(const char16* _msg, ...) : errorMsg(nullptr)
  1971. {
  1972. va_list arglist;
  1973. va_start(arglist, _msg);
  1974. FormatError(_msg, arglist);
  1975. }
  1976. WasmCompilationException::WasmCompilationException(const char16* _msg, va_list arglist) : errorMsg(nullptr)
  1977. {
  1978. FormatError(_msg, arglist);
  1979. }
  1980. void PolymorphicEmitInfo::Init(EmitInfo info)
  1981. {
  1982. if (info.type != WasmTypes::Void)
  1983. {
  1984. count = 1;
  1985. singleInfo = info;
  1986. }
  1987. else
  1988. {
  1989. Assert(info.location == Js::Constants::NoRegister);
  1990. count = 0;
  1991. infos = nullptr;
  1992. }
  1993. }
  1994. void PolymorphicEmitInfo::Init(uint32 count, ArenaAllocator* alloc)
  1995. {
  1996. infos = nullptr;
  1997. if (count > 1)
  1998. {
  1999. infos = AnewArray(alloc, EmitInfo, count);
  2000. }
  2001. this->count = count;
  2002. }
  2003. void PolymorphicEmitInfo::SetInfo(EmitInfo info, uint32 index)
  2004. {
  2005. AssertOrFailFast(index < count);
  2006. if (count == 1)
  2007. {
  2008. singleInfo = info;
  2009. }
  2010. else
  2011. {
  2012. infos[index] = info;
  2013. }
  2014. }
  2015. Wasm::EmitInfo PolymorphicEmitInfo::GetInfo(uint32 index) const
  2016. {
  2017. AssertOrFailFast(index < count);
  2018. if (count == 1)
  2019. {
  2020. return singleInfo;
  2021. }
  2022. return infos[index];
  2023. }
  2024. bool PolymorphicEmitInfo::IsUnreachable() const
  2025. {
  2026. if (count == 0)
  2027. {
  2028. return false;
  2029. }
  2030. if (count == 1)
  2031. {
  2032. return singleInfo.type == WasmTypes::Any;
  2033. }
  2034. for (uint32 i = 0; i < count; ++i)
  2035. {
  2036. if (infos[i].type == WasmTypes::Any)
  2037. {
  2038. return true;
  2039. }
  2040. }
  2041. return false;
  2042. }
  2043. bool PolymorphicEmitInfo::IsEquivalent(PolymorphicEmitInfo other) const
  2044. {
  2045. if (Count() != other.Count())
  2046. {
  2047. return false;
  2048. }
  2049. for (uint32 i = 0; i < Count(); ++i)
  2050. {
  2051. if (GetInfo(i).type != other.GetInfo(i).type)
  2052. {
  2053. return false;
  2054. }
  2055. }
  2056. return true;
  2057. }
  2058. } // namespace Wasm
  2059. #endif // ENABLE_WASM