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