WebAssemblyAsmPrinter.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file contains a printer that converts from our internal
  11. /// representation of machine-dependent LLVM code to the WebAssembly assembly
  12. /// language.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "WebAssemblyAsmPrinter.h"
  16. #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
  17. #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
  18. #include "TargetInfo/WebAssemblyTargetInfo.h"
  19. #include "Utils/WebAssemblyTypeUtilities.h"
  20. #include "Utils/WebAssemblyUtilities.h"
  21. #include "WebAssembly.h"
  22. #include "WebAssemblyMCInstLower.h"
  23. #include "WebAssemblyMachineFunctionInfo.h"
  24. #include "WebAssemblyRegisterInfo.h"
  25. #include "WebAssemblyRuntimeLibcallSignatures.h"
  26. #include "WebAssemblyTargetMachine.h"
  27. #include "llvm/ADT/SmallSet.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/BinaryFormat/Wasm.h"
  30. #include "llvm/CodeGen/Analysis.h"
  31. #include "llvm/CodeGen/AsmPrinter.h"
  32. #include "llvm/CodeGen/MachineConstantPool.h"
  33. #include "llvm/CodeGen/MachineInstr.h"
  34. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/DebugInfoMetadata.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/Metadata.h"
  39. #include "llvm/MC/MCContext.h"
  40. #include "llvm/MC/MCSectionWasm.h"
  41. #include "llvm/MC/MCStreamer.h"
  42. #include "llvm/MC/MCSymbol.h"
  43. #include "llvm/MC/MCSymbolWasm.h"
  44. #include "llvm/MC/TargetRegistry.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. using namespace llvm;
  48. #define DEBUG_TYPE "asm-printer"
  49. extern cl::opt<bool> WasmKeepRegisters;
  50. //===----------------------------------------------------------------------===//
  51. // Helpers.
  52. //===----------------------------------------------------------------------===//
  53. MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
  54. const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
  55. const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
  56. for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
  57. MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
  58. if (TRI->isTypeLegalForClass(*TRC, T))
  59. return T;
  60. LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
  61. llvm_unreachable("Unknown register type");
  62. return MVT::Other;
  63. }
  64. std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
  65. Register RegNo = MO.getReg();
  66. assert(RegNo.isVirtual() &&
  67. "Unlowered physical register encountered during assembly printing");
  68. assert(!MFI->isVRegStackified(RegNo));
  69. unsigned WAReg = MFI->getWAReg(RegNo);
  70. assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
  71. return '$' + utostr(WAReg);
  72. }
  73. WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
  74. MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
  75. return static_cast<WebAssemblyTargetStreamer *>(TS);
  76. }
  77. // Emscripten exception handling helpers
  78. //
  79. // This converts invoke names generated by LowerEmscriptenEHSjLj to real names
  80. // that are expected by JavaScript glue code. The invoke names generated by
  81. // Emscripten JS glue code are based on their argument and return types; for
  82. // example, for a function that takes an i32 and returns nothing, it is
  83. // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
  84. // contains a mangled string generated from their IR types, for example,
  85. // "__invoke_void_%struct.mystruct*_int", because final wasm types are not
  86. // available in the IR pass. So we convert those names to the form that
  87. // Emscripten JS code expects.
  88. //
  89. // Refer to LowerEmscriptenEHSjLj pass for more details.
  90. // Returns true if the given function name is an invoke name generated by
  91. // LowerEmscriptenEHSjLj pass.
  92. static bool isEmscriptenInvokeName(StringRef Name) {
  93. if (Name.front() == '"' && Name.back() == '"')
  94. Name = Name.substr(1, Name.size() - 2);
  95. return Name.startswith("__invoke_");
  96. }
  97. // Returns a character that represents the given wasm value type in invoke
  98. // signatures.
  99. static char getInvokeSig(wasm::ValType VT) {
  100. switch (VT) {
  101. case wasm::ValType::I32:
  102. return 'i';
  103. case wasm::ValType::I64:
  104. return 'j';
  105. case wasm::ValType::F32:
  106. return 'f';
  107. case wasm::ValType::F64:
  108. return 'd';
  109. case wasm::ValType::V128:
  110. return 'V';
  111. case wasm::ValType::FUNCREF:
  112. return 'F';
  113. case wasm::ValType::EXTERNREF:
  114. return 'X';
  115. }
  116. llvm_unreachable("Unhandled wasm::ValType enum");
  117. }
  118. // Given the wasm signature, generate the invoke name in the format JS glue code
  119. // expects.
  120. static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
  121. assert(Sig->Returns.size() <= 1);
  122. std::string Ret = "invoke_";
  123. if (!Sig->Returns.empty())
  124. for (auto VT : Sig->Returns)
  125. Ret += getInvokeSig(VT);
  126. else
  127. Ret += 'v';
  128. // Invokes' first argument is a pointer to the original function, so skip it
  129. for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
  130. Ret += getInvokeSig(Sig->Params[I]);
  131. return Ret;
  132. }
  133. //===----------------------------------------------------------------------===//
  134. // WebAssemblyAsmPrinter Implementation.
  135. //===----------------------------------------------------------------------===//
  136. MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
  137. const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
  138. bool &InvokeDetected) {
  139. MCSymbolWasm *WasmSym = nullptr;
  140. if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
  141. assert(Sig);
  142. InvokeDetected = true;
  143. if (Sig->Returns.size() > 1) {
  144. std::string Msg =
  145. "Emscripten EH/SjLj does not support multivalue returns: " +
  146. std::string(F->getName()) + ": " +
  147. WebAssembly::signatureToString(Sig);
  148. report_fatal_error(Twine(Msg));
  149. }
  150. WasmSym = cast<MCSymbolWasm>(
  151. GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig)));
  152. } else {
  153. WasmSym = cast<MCSymbolWasm>(getSymbol(F));
  154. }
  155. return WasmSym;
  156. }
  157. void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
  158. if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) {
  159. AsmPrinter::emitGlobalVariable(GV);
  160. return;
  161. }
  162. assert(!GV->isThreadLocal());
  163. MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
  164. if (!Sym->getType()) {
  165. SmallVector<MVT, 1> VTs;
  166. Type *GlobalVT = GV->getValueType();
  167. if (Subtarget) {
  168. // Subtarget is only set when a function is defined, because
  169. // each function can declare a different subtarget. For example,
  170. // on ARM a compilation unit might have a function on ARM and
  171. // another on Thumb. Therefore only if Subtarget is non-null we
  172. // can actually calculate the legal VTs.
  173. const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
  174. computeLegalValueVTs(TLI, GV->getParent()->getContext(),
  175. GV->getParent()->getDataLayout(), GlobalVT, VTs);
  176. }
  177. WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs);
  178. }
  179. emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration());
  180. emitSymbolType(Sym);
  181. if (GV->hasInitializer()) {
  182. assert(getSymbolPreferLocal(*GV) == Sym);
  183. emitLinkage(GV, Sym);
  184. OutStreamer->emitLabel(Sym);
  185. // TODO: Actually emit the initializer value. Otherwise the global has the
  186. // default value for its type (0, ref.null, etc).
  187. OutStreamer->addBlankLine();
  188. }
  189. }
  190. MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
  191. auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
  192. // May be called multiple times, so early out.
  193. if (WasmSym->getType())
  194. return WasmSym;
  195. const WebAssemblySubtarget &Subtarget = getSubtarget();
  196. // Except for certain known symbols, all symbols used by CodeGen are
  197. // functions. It's OK to hardcode knowledge of specific symbols here; this
  198. // method is precisely there for fetching the signatures of known
  199. // Clang-provided symbols.
  200. if (Name == "__stack_pointer" || Name == "__tls_base" ||
  201. Name == "__memory_base" || Name == "__table_base" ||
  202. Name == "__tls_size" || Name == "__tls_align") {
  203. bool Mutable =
  204. Name == "__stack_pointer" || Name == "__tls_base";
  205. WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
  206. WasmSym->setGlobalType(wasm::WasmGlobalType{
  207. uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
  208. : wasm::WASM_TYPE_I32),
  209. Mutable});
  210. return WasmSym;
  211. }
  212. if (Name.startswith("GCC_except_table")) {
  213. WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
  214. return WasmSym;
  215. }
  216. SmallVector<wasm::ValType, 4> Returns;
  217. SmallVector<wasm::ValType, 4> Params;
  218. if (Name == "__cpp_exception" || Name == "__c_longjmp") {
  219. WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
  220. // In static linking we define tag symbols in WasmException::endModule().
  221. // But we may have multiple objects to be linked together, each of which
  222. // defines the tag symbols. To resolve them, we declare them as weak. In
  223. // dynamic linking we make tag symbols undefined in the backend, define it
  224. // in JS, and feed them to each importing module.
  225. if (!isPositionIndependent())
  226. WasmSym->setWeak(true);
  227. WasmSym->setExternal(true);
  228. // Currently both C++ exceptions and C longjmps have a single pointer type
  229. // param. For C++ exceptions it is a pointer to an exception object, and for
  230. // C longjmps it is pointer to a struct that contains a setjmp buffer and a
  231. // longjmp return value. We may consider using multiple value parameters for
  232. // longjmps later when multivalue support is ready.
  233. wasm::ValType AddrType =
  234. Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
  235. Params.push_back(AddrType);
  236. } else { // Function symbols
  237. WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
  238. getLibcallSignature(Subtarget, Name, Returns, Params);
  239. }
  240. auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
  241. std::move(Params));
  242. WasmSym->setSignature(Signature.get());
  243. addSignature(std::move(Signature));
  244. return WasmSym;
  245. }
  246. void WebAssemblyAsmPrinter::emitSymbolType(const MCSymbolWasm *Sym) {
  247. std::optional<wasm::WasmSymbolType> WasmTy = Sym->getType();
  248. if (!WasmTy)
  249. return;
  250. switch (*WasmTy) {
  251. case wasm::WASM_SYMBOL_TYPE_GLOBAL:
  252. getTargetStreamer()->emitGlobalType(Sym);
  253. break;
  254. case wasm::WASM_SYMBOL_TYPE_TAG:
  255. getTargetStreamer()->emitTagType(Sym);
  256. break;
  257. case wasm::WASM_SYMBOL_TYPE_TABLE:
  258. getTargetStreamer()->emitTableType(Sym);
  259. break;
  260. default:
  261. break; // We only handle globals, tags and tables here
  262. }
  263. }
  264. void WebAssemblyAsmPrinter::emitDecls(const Module &M) {
  265. if (signaturesEmitted)
  266. return;
  267. signaturesEmitted = true;
  268. // Normally symbols for globals get discovered as the MI gets lowered,
  269. // but we need to know about them ahead of time. This will however,
  270. // only find symbols that have been used. Unused symbols from globals will
  271. // not be found here.
  272. MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
  273. for (const auto &Name : MMIW.MachineSymbolsUsed) {
  274. auto *WasmSym = cast<MCSymbolWasm>(getOrCreateWasmSymbol(Name.getKey()));
  275. if (WasmSym->isFunction()) {
  276. // TODO(wvo): is there any case where this overlaps with the call to
  277. // emitFunctionType in the loop below?
  278. getTargetStreamer()->emitFunctionType(WasmSym);
  279. }
  280. }
  281. for (auto &It : OutContext.getSymbols()) {
  282. // Emit .globaltype, .tagtype, or .tabletype declarations for extern
  283. // declarations, i.e. those that have only been declared (but not defined)
  284. // in the current module
  285. auto Sym = cast<MCSymbolWasm>(It.getValue());
  286. if (!Sym->isDefined())
  287. emitSymbolType(Sym);
  288. }
  289. DenseSet<MCSymbol *> InvokeSymbols;
  290. for (const auto &F : M) {
  291. if (F.isIntrinsic())
  292. continue;
  293. // Emit function type info for all functions. This will emit duplicate
  294. // information for defined functions (which already have function type
  295. // info emitted alongside their definition), but this is necessary in
  296. // order to enable the single-pass WebAssemblyAsmTypeCheck to succeed.
  297. SmallVector<MVT, 4> Results;
  298. SmallVector<MVT, 4> Params;
  299. computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
  300. // At this point these MCSymbols may or may not have been created already
  301. // and thus also contain a signature, but we need to get the signature
  302. // anyway here in case it is an invoke that has not yet been created. We
  303. // will discard it later if it turns out not to be necessary.
  304. auto Signature = signatureFromMVTs(Results, Params);
  305. bool InvokeDetected = false;
  306. auto *Sym = getMCSymbolForFunction(
  307. &F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
  308. Signature.get(), InvokeDetected);
  309. // Multiple functions can be mapped to the same invoke symbol. For
  310. // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
  311. // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
  312. // Emscripten EH symbol so we don't emit the same symbol twice.
  313. if (InvokeDetected && !InvokeSymbols.insert(Sym).second)
  314. continue;
  315. Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
  316. if (!Sym->getSignature()) {
  317. Sym->setSignature(Signature.get());
  318. addSignature(std::move(Signature));
  319. } else {
  320. // This symbol has already been created and had a signature. Discard it.
  321. Signature.reset();
  322. }
  323. getTargetStreamer()->emitFunctionType(Sym);
  324. if (F.hasFnAttribute("wasm-import-module")) {
  325. StringRef Name =
  326. F.getFnAttribute("wasm-import-module").getValueAsString();
  327. Sym->setImportModule(storeName(Name));
  328. getTargetStreamer()->emitImportModule(Sym, Name);
  329. }
  330. if (F.hasFnAttribute("wasm-import-name")) {
  331. // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
  332. // the original function name but the converted symbol name.
  333. StringRef Name =
  334. InvokeDetected
  335. ? Sym->getName()
  336. : F.getFnAttribute("wasm-import-name").getValueAsString();
  337. Sym->setImportName(storeName(Name));
  338. getTargetStreamer()->emitImportName(Sym, Name);
  339. }
  340. if (F.hasFnAttribute("wasm-export-name")) {
  341. auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
  342. StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
  343. Sym->setExportName(storeName(Name));
  344. getTargetStreamer()->emitExportName(Sym, Name);
  345. }
  346. }
  347. }
  348. void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
  349. // This is required to emit external declarations (like .functypes) when
  350. // no functions are defined in the compilation unit and therefore,
  351. // emitDecls() is not called until now.
  352. emitDecls(M);
  353. // When a function's address is taken, a TABLE_INDEX relocation is emitted
  354. // against the function symbol at the use site. However the relocation
  355. // doesn't explicitly refer to the table. In the future we may want to
  356. // define a new kind of reloc against both the function and the table, so
  357. // that the linker can see that the function symbol keeps the table alive,
  358. // but for now manually mark the table as live.
  359. for (const auto &F : M) {
  360. if (!F.isIntrinsic() && F.hasAddressTaken()) {
  361. MCSymbolWasm *FunctionTable =
  362. WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget);
  363. OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
  364. break;
  365. }
  366. }
  367. for (const auto &G : M.globals()) {
  368. if (!G.hasInitializer() && G.hasExternalLinkage() &&
  369. !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
  370. G.getValueType()->isSized()) {
  371. uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
  372. OutStreamer->emitELFSize(getSymbol(&G),
  373. MCConstantExpr::create(Size, OutContext));
  374. }
  375. }
  376. if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
  377. for (const Metadata *MD : Named->operands()) {
  378. const auto *Tuple = dyn_cast<MDTuple>(MD);
  379. if (!Tuple || Tuple->getNumOperands() != 2)
  380. continue;
  381. const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
  382. const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
  383. if (!Name || !Contents)
  384. continue;
  385. OutStreamer->pushSection();
  386. std::string SectionName = (".custom_section." + Name->getString()).str();
  387. MCSectionWasm *MySection =
  388. OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
  389. OutStreamer->switchSection(MySection);
  390. OutStreamer->emitBytes(Contents->getString());
  391. OutStreamer->popSection();
  392. }
  393. }
  394. EmitProducerInfo(M);
  395. EmitTargetFeatures(M);
  396. }
  397. void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
  398. llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
  399. if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
  400. llvm::SmallSet<StringRef, 4> SeenLanguages;
  401. for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
  402. const auto *CU = cast<DICompileUnit>(Debug->getOperand(I));
  403. StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
  404. Language.consume_front("DW_LANG_");
  405. if (SeenLanguages.insert(Language).second)
  406. Languages.emplace_back(Language.str(), "");
  407. }
  408. }
  409. llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
  410. if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
  411. llvm::SmallSet<StringRef, 4> SeenTools;
  412. for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
  413. const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
  414. std::pair<StringRef, StringRef> Field = S->getString().split("version");
  415. StringRef Name = Field.first.trim();
  416. StringRef Version = Field.second.trim();
  417. if (SeenTools.insert(Name).second)
  418. Tools.emplace_back(Name.str(), Version.str());
  419. }
  420. }
  421. int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
  422. if (FieldCount != 0) {
  423. MCSectionWasm *Producers = OutContext.getWasmSection(
  424. ".custom_section.producers", SectionKind::getMetadata());
  425. OutStreamer->pushSection();
  426. OutStreamer->switchSection(Producers);
  427. OutStreamer->emitULEB128IntValue(FieldCount);
  428. for (auto &Producers : {std::make_pair("language", &Languages),
  429. std::make_pair("processed-by", &Tools)}) {
  430. if (Producers.second->empty())
  431. continue;
  432. OutStreamer->emitULEB128IntValue(strlen(Producers.first));
  433. OutStreamer->emitBytes(Producers.first);
  434. OutStreamer->emitULEB128IntValue(Producers.second->size());
  435. for (auto &Producer : *Producers.second) {
  436. OutStreamer->emitULEB128IntValue(Producer.first.size());
  437. OutStreamer->emitBytes(Producer.first);
  438. OutStreamer->emitULEB128IntValue(Producer.second.size());
  439. OutStreamer->emitBytes(Producer.second);
  440. }
  441. }
  442. OutStreamer->popSection();
  443. }
  444. }
  445. void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
  446. struct FeatureEntry {
  447. uint8_t Prefix;
  448. std::string Name;
  449. };
  450. // Read target features and linkage policies from module metadata
  451. SmallVector<FeatureEntry, 4> EmittedFeatures;
  452. auto EmitFeature = [&](std::string Feature) {
  453. std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
  454. Metadata *Policy = M.getModuleFlag(MDKey);
  455. if (Policy == nullptr)
  456. return;
  457. FeatureEntry Entry;
  458. Entry.Prefix = 0;
  459. Entry.Name = Feature;
  460. if (auto *MD = cast<ConstantAsMetadata>(Policy))
  461. if (auto *I = cast<ConstantInt>(MD->getValue()))
  462. Entry.Prefix = I->getZExtValue();
  463. // Silently ignore invalid metadata
  464. if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
  465. Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
  466. Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
  467. return;
  468. EmittedFeatures.push_back(Entry);
  469. };
  470. for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
  471. EmitFeature(KV.Key);
  472. }
  473. // This pseudo-feature tells the linker whether shared memory would be safe
  474. EmitFeature("shared-mem");
  475. // This is an "architecture", not a "feature", but we emit it as such for
  476. // the benefit of tools like Binaryen and consistency with other producers.
  477. // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
  478. if (M.getDataLayout().getPointerSize() == 8) {
  479. // Can't use EmitFeature since "wasm-feature-memory64" is not a module
  480. // flag.
  481. EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
  482. }
  483. if (EmittedFeatures.size() == 0)
  484. return;
  485. // Emit features and linkage policies into the "target_features" section
  486. MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
  487. ".custom_section.target_features", SectionKind::getMetadata());
  488. OutStreamer->pushSection();
  489. OutStreamer->switchSection(FeaturesSection);
  490. OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
  491. for (auto &F : EmittedFeatures) {
  492. OutStreamer->emitIntValue(F.Prefix, 1);
  493. OutStreamer->emitULEB128IntValue(F.Name.size());
  494. OutStreamer->emitBytes(F.Name);
  495. }
  496. OutStreamer->popSection();
  497. }
  498. void WebAssemblyAsmPrinter::emitConstantPool() {
  499. emitDecls(*MMI->getModule());
  500. assert(MF->getConstantPool()->getConstants().empty() &&
  501. "WebAssembly disables constant pools");
  502. }
  503. void WebAssemblyAsmPrinter::emitJumpTableInfo() {
  504. // Nothing to do; jump tables are incorporated into the instruction stream.
  505. }
  506. void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
  507. const Function &F = MF->getFunction();
  508. SmallVector<MVT, 1> ResultVTs;
  509. SmallVector<MVT, 4> ParamVTs;
  510. computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
  511. auto Signature = signatureFromMVTs(ResultVTs, ParamVTs);
  512. auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
  513. WasmSym->setSignature(Signature.get());
  514. addSignature(std::move(Signature));
  515. WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
  516. getTargetStreamer()->emitFunctionType(WasmSym);
  517. // Emit the function index.
  518. if (MDNode *Idx = F.getMetadata("wasm.index")) {
  519. assert(Idx->getNumOperands() == 1);
  520. getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
  521. cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
  522. }
  523. SmallVector<wasm::ValType, 16> Locals;
  524. valTypesFromMVTs(MFI->getLocals(), Locals);
  525. getTargetStreamer()->emitLocal(Locals);
  526. AsmPrinter::emitFunctionBodyStart();
  527. }
  528. void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
  529. LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
  530. WebAssembly_MC::verifyInstructionPredicates(MI->getOpcode(),
  531. Subtarget->getFeatureBits());
  532. switch (MI->getOpcode()) {
  533. case WebAssembly::ARGUMENT_i32:
  534. case WebAssembly::ARGUMENT_i32_S:
  535. case WebAssembly::ARGUMENT_i64:
  536. case WebAssembly::ARGUMENT_i64_S:
  537. case WebAssembly::ARGUMENT_f32:
  538. case WebAssembly::ARGUMENT_f32_S:
  539. case WebAssembly::ARGUMENT_f64:
  540. case WebAssembly::ARGUMENT_f64_S:
  541. case WebAssembly::ARGUMENT_v16i8:
  542. case WebAssembly::ARGUMENT_v16i8_S:
  543. case WebAssembly::ARGUMENT_v8i16:
  544. case WebAssembly::ARGUMENT_v8i16_S:
  545. case WebAssembly::ARGUMENT_v4i32:
  546. case WebAssembly::ARGUMENT_v4i32_S:
  547. case WebAssembly::ARGUMENT_v2i64:
  548. case WebAssembly::ARGUMENT_v2i64_S:
  549. case WebAssembly::ARGUMENT_v4f32:
  550. case WebAssembly::ARGUMENT_v4f32_S:
  551. case WebAssembly::ARGUMENT_v2f64:
  552. case WebAssembly::ARGUMENT_v2f64_S:
  553. // These represent values which are live into the function entry, so there's
  554. // no instruction to emit.
  555. break;
  556. case WebAssembly::FALLTHROUGH_RETURN: {
  557. // These instructions represent the implicit return at the end of a
  558. // function body.
  559. if (isVerbose()) {
  560. OutStreamer->AddComment("fallthrough-return");
  561. OutStreamer->addBlankLine();
  562. }
  563. break;
  564. }
  565. case WebAssembly::COMPILER_FENCE:
  566. // This is a compiler barrier that prevents instruction reordering during
  567. // backend compilation, and should not be emitted.
  568. break;
  569. default: {
  570. WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
  571. MCInst TmpInst;
  572. MCInstLowering.lower(MI, TmpInst);
  573. EmitToStreamer(*OutStreamer, TmpInst);
  574. break;
  575. }
  576. }
  577. }
  578. bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
  579. unsigned OpNo,
  580. const char *ExtraCode,
  581. raw_ostream &OS) {
  582. // First try the generic code, which knows about modifiers like 'c' and 'n'.
  583. if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
  584. return false;
  585. if (!ExtraCode) {
  586. const MachineOperand &MO = MI->getOperand(OpNo);
  587. switch (MO.getType()) {
  588. case MachineOperand::MO_Immediate:
  589. OS << MO.getImm();
  590. return false;
  591. case MachineOperand::MO_Register:
  592. // FIXME: only opcode that still contains registers, as required by
  593. // MachineInstr::getDebugVariable().
  594. assert(MI->getOpcode() == WebAssembly::INLINEASM);
  595. OS << regToString(MO);
  596. return false;
  597. case MachineOperand::MO_GlobalAddress:
  598. PrintSymbolOperand(MO, OS);
  599. return false;
  600. case MachineOperand::MO_ExternalSymbol:
  601. GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
  602. printOffset(MO.getOffset(), OS);
  603. return false;
  604. case MachineOperand::MO_MachineBasicBlock:
  605. MO.getMBB()->getSymbol()->print(OS, MAI);
  606. return false;
  607. default:
  608. break;
  609. }
  610. }
  611. return true;
  612. }
  613. bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
  614. unsigned OpNo,
  615. const char *ExtraCode,
  616. raw_ostream &OS) {
  617. // The current approach to inline asm is that "r" constraints are expressed
  618. // as local indices, rather than values on the operand stack. This simplifies
  619. // using "r" as it eliminates the need to push and pop the values in a
  620. // particular order, however it also makes it impossible to have an "m"
  621. // constraint. So we don't support it.
  622. return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
  623. }
  624. // Force static initialization.
  625. extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() {
  626. RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
  627. RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
  628. }