WasmByteCodeGenerator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. #pragma once
  6. namespace Js
  7. {
  8. class WebAssemblySource;
  9. struct IWasmByteCodeWriter;
  10. }
  11. namespace Wasm
  12. {
  13. struct EmitInfo : WAsmJs::EmitInfoBase
  14. {
  15. EmitInfo(Js::RegSlot location_, const WasmTypes::WasmType& type_) :
  16. WAsmJs::EmitInfoBase(location_), type(type_)
  17. {
  18. }
  19. EmitInfo(const WasmTypes::WasmType& type_) : type(type_) {}
  20. EmitInfo() : type(WasmTypes::Void) {}
  21. WasmTypes::WasmType type;
  22. };
  23. struct PolymorphicEmitInfo
  24. {
  25. private:
  26. uint32 count = 0;
  27. union
  28. {
  29. EmitInfo singleInfo;
  30. EmitInfo* infos;
  31. };
  32. public:
  33. PolymorphicEmitInfo(): count(0), infos(nullptr) {}
  34. PolymorphicEmitInfo(EmitInfo info)
  35. {
  36. Init(info);
  37. }
  38. uint32 Count() const { return count; }
  39. void Init(EmitInfo info);
  40. void Init(uint32 count, ArenaAllocator* alloc);
  41. void SetInfo(EmitInfo info, uint32 index);
  42. EmitInfo GetInfo(uint32 index) const;
  43. bool IsUnreachable() const;
  44. bool IsEquivalent(PolymorphicEmitInfo other) const;
  45. };
  46. typedef WAsmJs::RegisterSpace WasmRegisterSpace;
  47. struct WasmLocal
  48. {
  49. WasmLocal() :
  50. location(Js::Constants::NoRegister), type(WasmTypes::Limit)
  51. {
  52. }
  53. WasmLocal(Js::RegSlot loc, WasmTypes::WasmType tp) :
  54. location(loc), type(tp)
  55. {
  56. }
  57. Js::RegSlot location;
  58. WasmTypes::WasmType type;
  59. };
  60. class WasmToAsmJs
  61. {
  62. public:
  63. static Js::AsmJsRetType GetAsmJsReturnType(WasmTypes::WasmType wasmType);
  64. static Js::AsmJsVarType GetAsmJsVarType(WasmTypes::WasmType wasmType);
  65. };
  66. class WasmCompilationException
  67. {
  68. void FormatError(const char16* _msg, va_list arglist);
  69. BSTR errorMsg;
  70. // We need to explicitly delete these; simply not including them makes compilers do
  71. // generation of simple copy-construct and copy-assign functions, which incorrectly
  72. // copy around the errorMsg pointer, making it harder to work with the lifetime. If
  73. // we just use the PREVENT_COPY macro (which defines the functions as private) then
  74. // we get linker errors, since MSVC doesn't check the accessibility of the function
  75. // references when templating, and tries to link to the undefined functions. Explit
  76. // deletion of the functions is therefore required here.
  77. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  78. private:
  79. WasmCompilationException(const WasmCompilationException&) = delete;
  80. WasmCompilationException& operator=(const WasmCompilationException& other) = delete;
  81. #else //if defined(_MSC_VER) && _MSC_VER < 1900
  82. // For older versions of VS, we need to provide copy construct/assign operators due
  83. // to the lack of the ability to throw-by-move.
  84. public:
  85. WasmCompilationException(const WasmCompilationException& other)
  86. {
  87. errorMsg = SysAllocString(other.errorMsg);
  88. }
  89. WasmCompilationException& operator=(const WasmCompilationException& other)
  90. {
  91. if(this != &other)
  92. {
  93. SysFreeString(errorMsg);
  94. errorMsg = SysAllocString(other.errorMsg);
  95. }
  96. return *this;
  97. }
  98. #endif
  99. public:
  100. WasmCompilationException(const char16* _msg, ...);
  101. WasmCompilationException(const char16* _msg, va_list arglist);
  102. WasmCompilationException(WasmCompilationException&& other)
  103. {
  104. errorMsg = other.errorMsg;
  105. other.errorMsg = nullptr;
  106. }
  107. ~WasmCompilationException()
  108. {
  109. SysFreeString(errorMsg);
  110. }
  111. BSTR ReleaseErrorMessage()
  112. {
  113. Assert(errorMsg);
  114. BSTR msg = errorMsg;
  115. errorMsg = nullptr;
  116. return msg;
  117. }
  118. WasmCompilationException& operator=(WasmCompilationException&& other)
  119. {
  120. if (this != &other)
  121. {
  122. SysFreeString(errorMsg);
  123. errorMsg = other.errorMsg;
  124. other.errorMsg = nullptr;
  125. }
  126. return *this;
  127. }
  128. BSTR GetTempErrorMessageRef()
  129. {
  130. // This is basically a work-around for some odd lifetime scoping with throw
  131. return errorMsg;
  132. }
  133. };
  134. struct BlockInfo
  135. {
  136. PolymorphicEmitInfo paramInfo;
  137. PolymorphicEmitInfo yieldInfo;
  138. bool didYield = false;
  139. Js::ByteCodeLabel label;
  140. bool DidYield() const { return didYield; }
  141. bool HasYield() const
  142. {
  143. return yieldInfo.Count() > 0;
  144. }
  145. bool IsEquivalent(const BlockInfo* other) const
  146. {
  147. if (HasYield() != other->HasYield())
  148. {
  149. return false;
  150. }
  151. if (HasYield())
  152. {
  153. return yieldInfo.IsEquivalent(other->yieldInfo);
  154. }
  155. return true;
  156. }
  157. };
  158. typedef JsUtil::BaseDictionary<uint32, LPCUTF8, ArenaAllocator> WasmExportDictionary;
  159. class WasmModuleGenerator
  160. {
  161. public:
  162. WasmModuleGenerator(Js::ScriptContext* scriptContext, Js::WebAssemblySource* src);
  163. Js::WebAssemblyModule* GenerateModule();
  164. void GenerateFunctionHeader(uint32 index);
  165. private:
  166. WasmBinaryReader* GetReader() const;
  167. Memory::Recycler* m_recycler;
  168. Js::Utf8SourceInfo* m_sourceInfo;
  169. Js::ScriptContext* m_scriptContext;
  170. Js::WebAssemblyModule* m_module;
  171. };
  172. class WasmBytecodeGenerator
  173. {
  174. public:
  175. static const Js::RegSlot ModuleSlotRegister = 0;
  176. static const Js::RegSlot ReturnRegister = 0;
  177. static const Js::RegSlot ModuleEnvRegister = 1;
  178. static const Js::RegSlot ArrayBufferRegister = 2;
  179. static const Js::RegSlot ArraySizeRegister = 3;
  180. static const Js::RegSlot ScriptContextBufferRegister = 4;
  181. static const Js::RegSlot ReservedRegisterCount = 5;
  182. WasmBytecodeGenerator(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo, bool validateOnly);
  183. static void GenerateFunctionBytecode(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo, bool validateOnly = false);
  184. static void ValidateFunction(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo);
  185. private:
  186. void GenerateFunction();
  187. template <size_t lanes>
  188. EmitInfo EmitSimdBuildExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature);
  189. void EmitExpr(WasmOp op);
  190. PolymorphicEmitInfo EmitBlock();
  191. void EmitBlockCommon(BlockInfo* blockInfo, bool* endOnElse = nullptr);
  192. PolymorphicEmitInfo EmitLoop();
  193. template<WasmOp wasmOp>
  194. PolymorphicEmitInfo EmitCall();
  195. PolymorphicEmitInfo EmitIfElseExpr();
  196. void EmitBrTable();
  197. EmitInfo EmitDrop();
  198. EmitInfo EmitGrowMemory();
  199. EmitInfo EmitGetLocal();
  200. EmitInfo EmitGetGlobal();
  201. EmitInfo EmitSetGlobal();
  202. EmitInfo EmitSetLocal(bool tee);
  203. void EmitReturnExpr(PolymorphicEmitInfo* explicitRetInfo = nullptr);
  204. EmitInfo EmitSelect();
  205. template<typename WriteFn>
  206. void WriteTypeStack(WriteFn fn) const;
  207. uint32 WriteTypeStackToString(_Out_writes_(maxlen) char16* out, uint32 maxlen) const;
  208. #if DBG_DUMP
  209. uint32 opId = 0;
  210. uint32 lastOpId = 1;
  211. void PrintOpBegin(WasmOp op);
  212. void PrintTypeStack() const;
  213. void PrintOpEnd();
  214. #endif
  215. void EmitBr();
  216. PolymorphicEmitInfo EmitBrIf();
  217. template<bool isStore, bool isAtomic>
  218. EmitInfo EmitMemAccess(WasmOp wasmOp, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType);
  219. EmitInfo EmitSimdMemAccess(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType, uint8 dataWidth, bool isStore);
  220. EmitInfo EmitBinExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature);
  221. EmitInfo EmitUnaryExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature);
  222. EmitInfo EmitV128BitSelect();
  223. EmitInfo EmitV8X16Shuffle();
  224. EmitInfo EmitExtractLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature);
  225. EmitInfo EmitReplaceLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature);
  226. void CheckLaneIndex(Js::OpCodeAsmJs op, const uint index);
  227. EmitInfo EmitLaneIndex(Js::OpCodeAsmJs op);
  228. EmitInfo EmitConst(WasmTypes::WasmType type, WasmConstLitNode cnst);
  229. void EmitLoadConst(EmitInfo dst, WasmConstLitNode cnst);
  230. WasmConstLitNode GetZeroCnst();
  231. void EnsureStackAvailable();
  232. void EnregisterLocals();
  233. void ReleaseLocation(EmitInfo* info);
  234. void ReleaseLocation(PolymorphicEmitInfo* info);
  235. PolymorphicEmitInfo PopLabel(Js::ByteCodeLabel labelValidation);
  236. BlockInfo* PushLabel(WasmBlock blockData, Js::ByteCodeLabel label, bool addBlockYieldInfo = true, bool checkInParams = true);
  237. void YieldToBlock(BlockInfo* blockInfo, PolymorphicEmitInfo expr);
  238. BlockInfo* GetBlockInfo(uint32 relativeDepth) const;
  239. Js::OpCodeAsmJs GetLoadOp(WasmTypes::WasmType type);
  240. Js::OpCodeAsmJs GetReturnOp(WasmTypes::WasmType type);
  241. WasmRegisterSpace* GetRegisterSpace(WasmTypes::WasmType type);
  242. EmitInfo PopValuePolymorphic() { return PopEvalStack(); }
  243. PolymorphicEmitInfo PopStackPolymorphic(PolymorphicEmitInfo expectedTypes, const char16* mismatchMessage = nullptr);
  244. PolymorphicEmitInfo PopStackPolymorphic(const BlockInfo* blockInfo, const char16* mismatchMessage = nullptr);
  245. EmitInfo PopEvalStack(WasmTypes::WasmType expectedType = WasmTypes::Any, const char16* mismatchMessage = nullptr);
  246. void PushEvalStack(PolymorphicEmitInfo);
  247. PolymorphicEmitInfo EnsureYield(BlockInfo*);
  248. void EnterEvalStackScope(const BlockInfo*);
  249. // The caller needs to release the location of the returned EmitInfo
  250. void ExitEvalStackScope(const BlockInfo*);
  251. void SetUnreachableState(bool isUnreachable);
  252. bool IsUnreachable() const { return this->isUnreachable; }
  253. void SetUsesMemory(uint32 memoryIndex);
  254. Js::FunctionBody* GetFunctionBody() const { return m_funcInfo->GetBody(); }
  255. WasmReaderBase* GetReader() const;
  256. Js::ProfileId GetNextProfileId();
  257. bool IsValidating() const { return m_originalWriter == m_emptyWriter; }
  258. ArenaAllocator m_alloc;
  259. bool isUnreachable;
  260. WasmLocal* m_locals;
  261. WasmFunctionInfo* m_funcInfo;
  262. BlockInfo* m_funcBlock;
  263. Js::WebAssemblyModule* m_module;
  264. uint32 m_maxArgOutDepth;
  265. Js::IWasmByteCodeWriter* m_writer;
  266. Js::IWasmByteCodeWriter* m_emptyWriter;
  267. Js::IWasmByteCodeWriter* m_originalWriter;
  268. Js::ScriptContext* m_scriptContext;
  269. WAsmJs::TypedRegisterAllocator mTypedRegisterAllocator;
  270. Js::ProfileId currentProfileId;
  271. JsUtil::Stack<BlockInfo*> m_blockInfos;
  272. JsUtil::Stack<EmitInfo> m_evalStack;
  273. };
  274. }