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 "Utils/WebAssemblyUtilities.h"
22 #include "WebAssembly.h"
23 #include "WebAssemblyMCInstLower.h"
24 #include "WebAssemblyMachineFunctionInfo.h"
25 #include "WebAssemblyRegisterInfo.h"
26 #include "WebAssemblyRuntimeLibcallSignatures.h"
27 #include "WebAssemblyTargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/BinaryFormat/Wasm.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/AsmPrinter.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCSectionWasm.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSymbolWasm.h"
45 #include "llvm/MC/TargetRegistry.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "asm-printer"
52 
53 extern cl::opt<bool> WasmKeepRegisters;
54 extern cl::opt<bool> WasmEnableEmEH;
55 extern cl::opt<bool> WasmEnableEmSjLj;
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(Register::isVirtualRegister(RegNo) &&
76          "Unlowered physical register encountered during assembly printing");
77   assert(!MFI->isVRegStackified(RegNo));
78   unsigned WAReg = MFI->getWAReg(RegNo);
79   assert(WAReg != WebAssemblyFunctionInfo::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.startswith("__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   }
129   llvm_unreachable("Unhandled wasm::ValType enum");
130 }
131 
132 // Given the wasm signature, generate the invoke name in the format JS glue code
133 // expects.
134 static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
135   assert(Sig->Returns.size() <= 1);
136   std::string Ret = "invoke_";
137   if (!Sig->Returns.empty())
138     for (auto VT : Sig->Returns)
139       Ret += getInvokeSig(VT);
140   else
141     Ret += 'v';
142   // Invokes' first argument is a pointer to the original function, so skip it
143   for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
144     Ret += getInvokeSig(Sig->Params[I]);
145   return Ret;
146 }
147 
148 //===----------------------------------------------------------------------===//
149 // WebAssemblyAsmPrinter Implementation.
150 //===----------------------------------------------------------------------===//
151 
152 MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
153     const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
154     bool &InvokeDetected) {
155   MCSymbolWasm *WasmSym = nullptr;
156   if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
157     assert(Sig);
158     InvokeDetected = true;
159     if (Sig->Returns.size() > 1) {
160       std::string Msg =
161           "Emscripten EH/SjLj does not support multivalue returns: " +
162           std::string(F->getName()) + ": " +
163           WebAssembly::signatureToString(Sig);
164       report_fatal_error(Twine(Msg));
165     }
166     WasmSym = cast<MCSymbolWasm>(
167         GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig)));
168   } else {
169     WasmSym = cast<MCSymbolWasm>(getSymbol(F));
170   }
171   return WasmSym;
172 }
173 
174 void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
175   if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) {
176     AsmPrinter::emitGlobalVariable(GV);
177     return;
178   }
179 
180   assert(!GV->isThreadLocal());
181 
182   MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
183 
184   if (!Sym->getType()) {
185     const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
186     SmallVector<EVT, 1> VTs;
187     ComputeValueVTs(TLI, GV->getParent()->getDataLayout(), GV->getValueType(),
188                     VTs);
189     if (VTs.size() != 1 ||
190         TLI.getNumRegisters(GV->getParent()->getContext(), VTs[0]) != 1)
191       report_fatal_error("Aggregate globals not yet implemented");
192     MVT VT = TLI.getRegisterType(GV->getParent()->getContext(), VTs[0]);
193     bool Mutable = true;
194     wasm::ValType Type = WebAssembly::toValType(VT);
195     Sym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
196     Sym->setGlobalType(wasm::WasmGlobalType{uint8_t(Type), Mutable});
197   }
198 
199   // If the GlobalVariable refers to a table, we handle it here instead of
200   // in emitExternalDecls
201   if (Sym->isTable()) {
202     getTargetStreamer()->emitTableType(Sym);
203     return;
204   }
205 
206   emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration());
207   if (GV->hasInitializer()) {
208     assert(getSymbolPreferLocal(*GV) == Sym);
209     emitLinkage(GV, Sym);
210     getTargetStreamer()->emitGlobalType(Sym);
211     OutStreamer->emitLabel(Sym);
212     // TODO: Actually emit the initializer value.  Otherwise the global has the
213     // default value for its type (0, ref.null, etc).
214     OutStreamer->AddBlankLine();
215   }
216 }
217 
218 MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
219   auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
220 
221   // May be called multiple times, so early out.
222   if (WasmSym->getType().hasValue())
223     return WasmSym;
224 
225   const WebAssemblySubtarget &Subtarget = getSubtarget();
226 
227   // Except for certain known symbols, all symbols used by CodeGen are
228   // functions. It's OK to hardcode knowledge of specific symbols here; this
229   // method is precisely there for fetching the signatures of known
230   // Clang-provided symbols.
231   if (Name == "__stack_pointer" || Name == "__tls_base" ||
232       Name == "__memory_base" || Name == "__table_base" ||
233       Name == "__tls_size" || Name == "__tls_align") {
234     bool Mutable =
235         Name == "__stack_pointer" || Name == "__tls_base";
236     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
237     WasmSym->setGlobalType(wasm::WasmGlobalType{
238         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
239                                       : wasm::WASM_TYPE_I32),
240         Mutable});
241     return WasmSym;
242   }
243 
244   if (Name.startswith("GCC_except_table")) {
245     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
246     return WasmSym;
247   }
248 
249   SmallVector<wasm::ValType, 4> Returns;
250   SmallVector<wasm::ValType, 4> Params;
251   if (Name == "__cpp_exception" || Name == "__c_longjmp") {
252     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
253     // In static linking we define tag symbols in WasmException::endModule().
254     // But we may have multiple objects to be linked together, each of which
255     // defines the tag symbols. To resolve them, we declare them as weak. In
256     // dynamic linking we make tag symbols undefined in the backend, define it
257     // in JS, and feed them to each importing module.
258     if (!isPositionIndependent())
259       WasmSym->setWeak(true);
260     WasmSym->setExternal(true);
261 
262     // Currently both C++ exceptions and C longjmps have a single pointer type
263     // param. For C++ exceptions it is a pointer to an exception object, and for
264     // C longjmps it is pointer to a struct that contains a setjmp buffer and a
265     // longjmp return value. We may consider using multiple value parameters for
266     // longjmps later when multivalue support is ready.
267     wasm::ValType AddrType =
268         Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
269     Params.push_back(AddrType);
270   } else { // Function symbols
271     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
272     getLibcallSignature(Subtarget, Name, Returns, Params);
273   }
274   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
275                                                          std::move(Params));
276   WasmSym->setSignature(Signature.get());
277   addSignature(std::move(Signature));
278 
279   return WasmSym;
280 }
281 
282 void WebAssemblyAsmPrinter::emitExternalDecls(const Module &M) {
283   if (signaturesEmitted)
284     return;
285   signaturesEmitted = true;
286 
287   // Normally symbols for globals get discovered as the MI gets lowered,
288   // but we need to know about them ahead of time.
289   MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
290   for (const auto &Name : MMIW.MachineSymbolsUsed) {
291     getOrCreateWasmSymbol(Name.getKey());
292   }
293 
294   for (auto &It : OutContext.getSymbols()) {
295     // Emit .globaltype, .tagtype, or .tabletype declarations.
296     auto Sym = cast<MCSymbolWasm>(It.getValue());
297     if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_GLOBAL) {
298       // .globaltype already handled by emitGlobalVariable for defined
299       // variables; here we make sure the types of external wasm globals get
300       // written to the file.
301       if (Sym->isUndefined())
302         getTargetStreamer()->emitGlobalType(Sym);
303     } else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_TAG)
304       getTargetStreamer()->emitTagType(Sym);
305     else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_TABLE)
306       getTargetStreamer()->emitTableType(Sym);
307   }
308 
309   DenseSet<MCSymbol *> InvokeSymbols;
310   for (const auto &F : M) {
311     if (F.isIntrinsic())
312       continue;
313 
314     // Emit function type info for all undefined functions
315     if (F.isDeclarationForLinker()) {
316       SmallVector<MVT, 4> Results;
317       SmallVector<MVT, 4> Params;
318       computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
319       // At this point these MCSymbols may or may not have been created already
320       // and thus also contain a signature, but we need to get the signature
321       // anyway here in case it is an invoke that has not yet been created. We
322       // will discard it later if it turns out not to be necessary.
323       auto Signature = signatureFromMVTs(Results, Params);
324       bool InvokeDetected = false;
325       auto *Sym = getMCSymbolForFunction(&F, WasmEnableEmEH || WasmEnableEmSjLj,
326                                          Signature.get(), InvokeDetected);
327 
328       // Multiple functions can be mapped to the same invoke symbol. For
329       // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
330       // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
331       // Emscripten EH symbol so we don't emit the same symbol twice.
332       if (InvokeDetected && !InvokeSymbols.insert(Sym).second)
333         continue;
334 
335       Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
336       if (!Sym->getSignature()) {
337         Sym->setSignature(Signature.get());
338         addSignature(std::move(Signature));
339       } else {
340         // This symbol has already been created and had a signature. Discard it.
341         Signature.reset();
342       }
343 
344       getTargetStreamer()->emitFunctionType(Sym);
345 
346       if (F.hasFnAttribute("wasm-import-module")) {
347         StringRef Name =
348             F.getFnAttribute("wasm-import-module").getValueAsString();
349         Sym->setImportModule(storeName(Name));
350         getTargetStreamer()->emitImportModule(Sym, Name);
351       }
352       if (F.hasFnAttribute("wasm-import-name")) {
353         // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
354         // the original function name but the converted symbol name.
355         StringRef Name =
356             InvokeDetected
357                 ? Sym->getName()
358                 : F.getFnAttribute("wasm-import-name").getValueAsString();
359         Sym->setImportName(storeName(Name));
360         getTargetStreamer()->emitImportName(Sym, Name);
361       }
362     }
363 
364     if (F.hasFnAttribute("wasm-export-name")) {
365       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
366       StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
367       Sym->setExportName(storeName(Name));
368       getTargetStreamer()->emitExportName(Sym, Name);
369     }
370   }
371 }
372 
373 void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
374   emitExternalDecls(M);
375 
376   // When a function's address is taken, a TABLE_INDEX relocation is emitted
377   // against the function symbol at the use site.  However the relocation
378   // doesn't explicitly refer to the table.  In the future we may want to
379   // define a new kind of reloc against both the function and the table, so
380   // that the linker can see that the function symbol keeps the table alive,
381   // but for now manually mark the table as live.
382   for (const auto &F : M) {
383     if (!F.isIntrinsic() && F.hasAddressTaken()) {
384       MCSymbolWasm *FunctionTable =
385           WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget);
386       OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
387       break;
388     }
389   }
390 
391   for (const auto &G : M.globals()) {
392     if (!G.hasInitializer() && G.hasExternalLinkage() &&
393         !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
394         G.getValueType()->isSized()) {
395       uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
396       OutStreamer->emitELFSize(getSymbol(&G),
397                                MCConstantExpr::create(Size, OutContext));
398     }
399   }
400 
401   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
402     for (const Metadata *MD : Named->operands()) {
403       const auto *Tuple = dyn_cast<MDTuple>(MD);
404       if (!Tuple || Tuple->getNumOperands() != 2)
405         continue;
406       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
407       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
408       if (!Name || !Contents)
409         continue;
410 
411       OutStreamer->PushSection();
412       std::string SectionName = (".custom_section." + Name->getString()).str();
413       MCSectionWasm *MySection =
414           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
415       OutStreamer->SwitchSection(MySection);
416       OutStreamer->emitBytes(Contents->getString());
417       OutStreamer->PopSection();
418     }
419   }
420 
421   EmitProducerInfo(M);
422   EmitTargetFeatures(M);
423 }
424 
425 void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
426   llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
427   if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
428     llvm::SmallSet<StringRef, 4> SeenLanguages;
429     for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
430       const auto *CU = cast<DICompileUnit>(Debug->getOperand(I));
431       StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
432       Language.consume_front("DW_LANG_");
433       if (SeenLanguages.insert(Language).second)
434         Languages.emplace_back(Language.str(), "");
435     }
436   }
437 
438   llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
439   if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
440     llvm::SmallSet<StringRef, 4> SeenTools;
441     for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
442       const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
443       std::pair<StringRef, StringRef> Field = S->getString().split("version");
444       StringRef Name = Field.first.trim();
445       StringRef Version = Field.second.trim();
446       if (SeenTools.insert(Name).second)
447         Tools.emplace_back(Name.str(), Version.str());
448     }
449   }
450 
451   int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
452   if (FieldCount != 0) {
453     MCSectionWasm *Producers = OutContext.getWasmSection(
454         ".custom_section.producers", SectionKind::getMetadata());
455     OutStreamer->PushSection();
456     OutStreamer->SwitchSection(Producers);
457     OutStreamer->emitULEB128IntValue(FieldCount);
458     for (auto &Producers : {std::make_pair("language", &Languages),
459             std::make_pair("processed-by", &Tools)}) {
460       if (Producers.second->empty())
461         continue;
462       OutStreamer->emitULEB128IntValue(strlen(Producers.first));
463       OutStreamer->emitBytes(Producers.first);
464       OutStreamer->emitULEB128IntValue(Producers.second->size());
465       for (auto &Producer : *Producers.second) {
466         OutStreamer->emitULEB128IntValue(Producer.first.size());
467         OutStreamer->emitBytes(Producer.first);
468         OutStreamer->emitULEB128IntValue(Producer.second.size());
469         OutStreamer->emitBytes(Producer.second);
470       }
471     }
472     OutStreamer->PopSection();
473   }
474 }
475 
476 void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
477   struct FeatureEntry {
478     uint8_t Prefix;
479     std::string Name;
480   };
481 
482   // Read target features and linkage policies from module metadata
483   SmallVector<FeatureEntry, 4> EmittedFeatures;
484   auto EmitFeature = [&](std::string Feature) {
485     std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
486     Metadata *Policy = M.getModuleFlag(MDKey);
487     if (Policy == nullptr)
488       return;
489 
490     FeatureEntry Entry;
491     Entry.Prefix = 0;
492     Entry.Name = Feature;
493 
494     if (auto *MD = cast<ConstantAsMetadata>(Policy))
495       if (auto *I = cast<ConstantInt>(MD->getValue()))
496         Entry.Prefix = I->getZExtValue();
497 
498     // Silently ignore invalid metadata
499     if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
500         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
501         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
502       return;
503 
504     EmittedFeatures.push_back(Entry);
505   };
506 
507   for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
508     EmitFeature(KV.Key);
509   }
510   // This pseudo-feature tells the linker whether shared memory would be safe
511   EmitFeature("shared-mem");
512 
513   // This is an "architecture", not a "feature", but we emit it as such for
514   // the benefit of tools like Binaryen and consistency with other producers.
515   // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
516   if (M.getDataLayout().getPointerSize() == 8) {
517     // Can't use EmitFeature since "wasm-feature-memory64" is not a module
518     // flag.
519     EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
520   }
521 
522   if (EmittedFeatures.size() == 0)
523     return;
524 
525   // Emit features and linkage policies into the "target_features" section
526   MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
527       ".custom_section.target_features", SectionKind::getMetadata());
528   OutStreamer->PushSection();
529   OutStreamer->SwitchSection(FeaturesSection);
530 
531   OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
532   for (auto &F : EmittedFeatures) {
533     OutStreamer->emitIntValue(F.Prefix, 1);
534     OutStreamer->emitULEB128IntValue(F.Name.size());
535     OutStreamer->emitBytes(F.Name);
536   }
537 
538   OutStreamer->PopSection();
539 }
540 
541 void WebAssemblyAsmPrinter::emitConstantPool() {
542   assert(MF->getConstantPool()->getConstants().empty() &&
543          "WebAssembly disables constant pools");
544 }
545 
546 void WebAssemblyAsmPrinter::emitJumpTableInfo() {
547   // Nothing to do; jump tables are incorporated into the instruction stream.
548 }
549 
550 void WebAssemblyAsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *Sym)
551   const {
552   AsmPrinter::emitLinkage(GV, Sym);
553   // This gets called before the function label and type are emitted.
554   // We use it to emit signatures of external functions.
555   // FIXME casts!
556   const_cast<WebAssemblyAsmPrinter *>(this)
557     ->emitExternalDecls(*MMI->getModule());
558 }
559 
560 
561 void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
562   const Function &F = MF->getFunction();
563   SmallVector<MVT, 1> ResultVTs;
564   SmallVector<MVT, 4> ParamVTs;
565   computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
566 
567   auto Signature = signatureFromMVTs(ResultVTs, ParamVTs);
568   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
569   WasmSym->setSignature(Signature.get());
570   addSignature(std::move(Signature));
571   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
572 
573   getTargetStreamer()->emitFunctionType(WasmSym);
574 
575   // Emit the function index.
576   if (MDNode *Idx = F.getMetadata("wasm.index")) {
577     assert(Idx->getNumOperands() == 1);
578 
579     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
580         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
581   }
582 
583   SmallVector<wasm::ValType, 16> Locals;
584   valTypesFromMVTs(MFI->getLocals(), Locals);
585   getTargetStreamer()->emitLocal(Locals);
586 
587   AsmPrinter::emitFunctionBodyStart();
588 }
589 
590 void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
591   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
592 
593   switch (MI->getOpcode()) {
594   case WebAssembly::ARGUMENT_i32:
595   case WebAssembly::ARGUMENT_i32_S:
596   case WebAssembly::ARGUMENT_i64:
597   case WebAssembly::ARGUMENT_i64_S:
598   case WebAssembly::ARGUMENT_f32:
599   case WebAssembly::ARGUMENT_f32_S:
600   case WebAssembly::ARGUMENT_f64:
601   case WebAssembly::ARGUMENT_f64_S:
602   case WebAssembly::ARGUMENT_v16i8:
603   case WebAssembly::ARGUMENT_v16i8_S:
604   case WebAssembly::ARGUMENT_v8i16:
605   case WebAssembly::ARGUMENT_v8i16_S:
606   case WebAssembly::ARGUMENT_v4i32:
607   case WebAssembly::ARGUMENT_v4i32_S:
608   case WebAssembly::ARGUMENT_v2i64:
609   case WebAssembly::ARGUMENT_v2i64_S:
610   case WebAssembly::ARGUMENT_v4f32:
611   case WebAssembly::ARGUMENT_v4f32_S:
612   case WebAssembly::ARGUMENT_v2f64:
613   case WebAssembly::ARGUMENT_v2f64_S:
614     // These represent values which are live into the function entry, so there's
615     // no instruction to emit.
616     break;
617   case WebAssembly::FALLTHROUGH_RETURN: {
618     // These instructions represent the implicit return at the end of a
619     // function body.
620     if (isVerbose()) {
621       OutStreamer->AddComment("fallthrough-return");
622       OutStreamer->AddBlankLine();
623     }
624     break;
625   }
626   case WebAssembly::COMPILER_FENCE:
627     // This is a compiler barrier that prevents instruction reordering during
628     // backend compilation, and should not be emitted.
629     break;
630   default: {
631     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
632     MCInst TmpInst;
633     MCInstLowering.lower(MI, TmpInst);
634     EmitToStreamer(*OutStreamer, TmpInst);
635     break;
636   }
637   }
638 }
639 
640 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
641                                             unsigned OpNo,
642                                             const char *ExtraCode,
643                                             raw_ostream &OS) {
644   // First try the generic code, which knows about modifiers like 'c' and 'n'.
645   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
646     return false;
647 
648   if (!ExtraCode) {
649     const MachineOperand &MO = MI->getOperand(OpNo);
650     switch (MO.getType()) {
651     case MachineOperand::MO_Immediate:
652       OS << MO.getImm();
653       return false;
654     case MachineOperand::MO_Register:
655       // FIXME: only opcode that still contains registers, as required by
656       // MachineInstr::getDebugVariable().
657       assert(MI->getOpcode() == WebAssembly::INLINEASM);
658       OS << regToString(MO);
659       return false;
660     case MachineOperand::MO_GlobalAddress:
661       PrintSymbolOperand(MO, OS);
662       return false;
663     case MachineOperand::MO_ExternalSymbol:
664       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
665       printOffset(MO.getOffset(), OS);
666       return false;
667     case MachineOperand::MO_MachineBasicBlock:
668       MO.getMBB()->getSymbol()->print(OS, MAI);
669       return false;
670     default:
671       break;
672     }
673   }
674 
675   return true;
676 }
677 
678 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
679                                                   unsigned OpNo,
680                                                   const char *ExtraCode,
681                                                   raw_ostream &OS) {
682   // The current approach to inline asm is that "r" constraints are expressed
683   // as local indices, rather than values on the operand stack. This simplifies
684   // using "r" as it eliminates the need to push and pop the values in a
685   // particular order, however it also makes it impossible to have an "m"
686   // constraint. So we don't support it.
687 
688   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
689 }
690 
691 // Force static initialization.
692 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() {
693   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
694   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
695 }
696