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 "InstPrinter/WebAssemblyInstPrinter.h"
18 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
19 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
20 #include "WebAssembly.h"
21 #include "WebAssemblyMCInstLower.h"
22 #include "WebAssemblyMachineFunctionInfo.h"
23 #include "WebAssemblyRegisterInfo.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfoMetadata.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCSectionWasm.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCSymbolWasm.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/raw_ostream.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "asm-printer"
45 
46 //===----------------------------------------------------------------------===//
47 // Helpers.
48 //===----------------------------------------------------------------------===//
49 
50 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
51   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
52   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
53   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
54                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
55     if (TRI->isTypeLegalForClass(*TRC, T))
56       return T;
57   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
58   llvm_unreachable("Unknown register type");
59   return MVT::Other;
60 }
61 
62 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
63   unsigned RegNo = MO.getReg();
64   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
65          "Unlowered physical register encountered during assembly printing");
66   assert(!MFI->isVRegStackified(RegNo));
67   unsigned WAReg = MFI->getWAReg(RegNo);
68   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
69   return '$' + utostr(WAReg);
70 }
71 
72 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
73   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
74   return static_cast<WebAssemblyTargetStreamer *>(TS);
75 }
76 
77 //===----------------------------------------------------------------------===//
78 // WebAssemblyAsmPrinter Implementation.
79 //===----------------------------------------------------------------------===//
80 
81 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
82   for (auto &It : OutContext.getSymbols()) {
83     // Emit a .globaltype and .eventtype declaration.
84     auto Sym = cast<MCSymbolWasm>(It.getValue());
85     if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_GLOBAL)
86       getTargetStreamer()->emitGlobalType(Sym);
87     else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_EVENT)
88       getTargetStreamer()->emitEventType(Sym);
89   }
90 
91   for (const auto &F : M) {
92     // Emit function type info for all undefined functions
93     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
94       SmallVector<MVT, 4> Results;
95       SmallVector<MVT, 4> Params;
96       ComputeSignatureVTs(F.getFunctionType(), F, TM, Params, Results);
97       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
98       Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
99       if (!Sym->getSignature()) {
100         auto Signature = SignatureFromMVTs(Results, Params);
101         Sym->setSignature(Signature.get());
102         addSignature(std::move(Signature));
103       }
104       // FIXME: this was originally intended for post-linking and was only used
105       // for imports that were only called indirectly (i.e. s2wasm could not
106       // infer the type from a call). With object files it applies to all
107       // imports. so fix the names and the tests, or rethink how import
108       // delcarations work in asm files.
109       getTargetStreamer()->emitFunctionType(Sym);
110 
111       if (TM.getTargetTriple().isOSBinFormatWasm() &&
112           F.hasFnAttribute("wasm-import-module")) {
113         StringRef Name =
114             F.getFnAttribute("wasm-import-module").getValueAsString();
115         Sym->setModuleName(Name);
116         getTargetStreamer()->emitImportModule(Sym, Name);
117       }
118     }
119   }
120 
121   for (const auto &G : M.globals()) {
122     if (!G.hasInitializer() && G.hasExternalLinkage()) {
123       if (G.getValueType()->isSized()) {
124         uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
125         OutStreamer->emitELFSize(getSymbol(&G),
126                                  MCConstantExpr::create(Size, OutContext));
127       }
128     }
129   }
130 
131   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
132     for (const Metadata *MD : Named->operands()) {
133       const MDTuple *Tuple = dyn_cast<MDTuple>(MD);
134       if (!Tuple || Tuple->getNumOperands() != 2)
135         continue;
136       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
137       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
138       if (!Name || !Contents)
139         continue;
140 
141       OutStreamer->PushSection();
142       std::string SectionName = (".custom_section." + Name->getString()).str();
143       MCSectionWasm *mySection =
144           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
145       OutStreamer->SwitchSection(mySection);
146       OutStreamer->EmitBytes(Contents->getString());
147       OutStreamer->PopSection();
148     }
149   }
150 
151   EmitProducerInfo(M);
152 }
153 
154 void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
155   llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
156   if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
157      llvm::SmallSet<StringRef, 4> SeenLanguages;
158     for (size_t i = 0, e = Debug->getNumOperands(); i < e; ++i) {
159       const auto *CU = cast<DICompileUnit>(Debug->getOperand(i));
160       StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
161       Language.consume_front("DW_LANG_");
162       if (SeenLanguages.insert(Language).second)
163         Languages.emplace_back(Language.str(), "");
164     }
165   }
166 
167   llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
168   if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
169     llvm::SmallSet<StringRef, 4> SeenTools;
170     for (size_t i = 0, e = Ident->getNumOperands(); i < e; ++i) {
171       const auto *S = cast<MDString>(Ident->getOperand(i)->getOperand(0));
172       std::pair<StringRef, StringRef> Field = S->getString().split("version");
173       StringRef Name = Field.first.trim();
174       StringRef Version = Field.second.trim();
175       if (SeenTools.insert(Name).second)
176         Tools.emplace_back(Name.str(), Version.str());
177     }
178   }
179 
180   int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
181   if (FieldCount != 0) {
182     MCSectionWasm *Producers = OutContext.getWasmSection(
183         ".custom_section.producers", SectionKind::getMetadata());
184     OutStreamer->PushSection();
185     OutStreamer->SwitchSection(Producers);
186     OutStreamer->EmitULEB128IntValue(FieldCount);
187     for (auto &Producers : {std::make_pair("language", &Languages),
188             std::make_pair("processed-by", &Tools)}) {
189       if (Producers.second->empty())
190         continue;
191       OutStreamer->EmitULEB128IntValue(strlen(Producers.first));
192       OutStreamer->EmitBytes(Producers.first);
193       OutStreamer->EmitULEB128IntValue(Producers.second->size());
194       for (auto &Producer : *Producers.second) {
195         OutStreamer->EmitULEB128IntValue(Producer.first.size());
196         OutStreamer->EmitBytes(Producer.first);
197         OutStreamer->EmitULEB128IntValue(Producer.second.size());
198         OutStreamer->EmitBytes(Producer.second);
199       }
200     }
201     OutStreamer->PopSection();
202   }
203 }
204 
205 void WebAssemblyAsmPrinter::EmitConstantPool() {
206   assert(MF->getConstantPool()->getConstants().empty() &&
207          "WebAssembly disables constant pools");
208 }
209 
210 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
211   // Nothing to do; jump tables are incorporated into the instruction stream.
212 }
213 
214 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
215   const Function &F = MF->getFunction();
216   SmallVector<MVT, 1> ResultVTs;
217   SmallVector<MVT, 4> ParamVTs;
218   ComputeSignatureVTs(F.getFunctionType(), F, TM, ParamVTs, ResultVTs);
219   auto Signature = SignatureFromMVTs(ResultVTs, ParamVTs);
220   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
221   WasmSym->setSignature(Signature.get());
222   addSignature(std::move(Signature));
223   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
224 
225   // FIXME: clean up how params and results are emitted (use signatures)
226   getTargetStreamer()->emitFunctionType(WasmSym);
227 
228   // Emit the function index.
229   if (MDNode *Idx = F.getMetadata("wasm.index")) {
230     assert(Idx->getNumOperands() == 1);
231 
232     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
233         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
234   }
235 
236   SmallVector<wasm::ValType, 16> Locals;
237   ValTypesFromMVTs(MFI->getLocals(), Locals);
238   getTargetStreamer()->emitLocal(Locals);
239 
240   AsmPrinter::EmitFunctionBodyStart();
241 }
242 
243 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
244   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
245 
246   switch (MI->getOpcode()) {
247   case WebAssembly::ARGUMENT_i32:
248   case WebAssembly::ARGUMENT_i32_S:
249   case WebAssembly::ARGUMENT_i64:
250   case WebAssembly::ARGUMENT_i64_S:
251   case WebAssembly::ARGUMENT_f32:
252   case WebAssembly::ARGUMENT_f32_S:
253   case WebAssembly::ARGUMENT_f64:
254   case WebAssembly::ARGUMENT_f64_S:
255   case WebAssembly::ARGUMENT_v16i8:
256   case WebAssembly::ARGUMENT_v16i8_S:
257   case WebAssembly::ARGUMENT_v8i16:
258   case WebAssembly::ARGUMENT_v8i16_S:
259   case WebAssembly::ARGUMENT_v4i32:
260   case WebAssembly::ARGUMENT_v4i32_S:
261   case WebAssembly::ARGUMENT_v2i64:
262   case WebAssembly::ARGUMENT_v2i64_S:
263   case WebAssembly::ARGUMENT_v4f32:
264   case WebAssembly::ARGUMENT_v4f32_S:
265   case WebAssembly::ARGUMENT_v2f64:
266   case WebAssembly::ARGUMENT_v2f64_S:
267     // These represent values which are live into the function entry, so there's
268     // no instruction to emit.
269     break;
270   case WebAssembly::FALLTHROUGH_RETURN_I32:
271   case WebAssembly::FALLTHROUGH_RETURN_I32_S:
272   case WebAssembly::FALLTHROUGH_RETURN_I64:
273   case WebAssembly::FALLTHROUGH_RETURN_I64_S:
274   case WebAssembly::FALLTHROUGH_RETURN_F32:
275   case WebAssembly::FALLTHROUGH_RETURN_F32_S:
276   case WebAssembly::FALLTHROUGH_RETURN_F64:
277   case WebAssembly::FALLTHROUGH_RETURN_F64_S:
278   case WebAssembly::FALLTHROUGH_RETURN_v16i8:
279   case WebAssembly::FALLTHROUGH_RETURN_v16i8_S:
280   case WebAssembly::FALLTHROUGH_RETURN_v8i16:
281   case WebAssembly::FALLTHROUGH_RETURN_v8i16_S:
282   case WebAssembly::FALLTHROUGH_RETURN_v4i32:
283   case WebAssembly::FALLTHROUGH_RETURN_v4i32_S:
284   case WebAssembly::FALLTHROUGH_RETURN_v2i64:
285   case WebAssembly::FALLTHROUGH_RETURN_v2i64_S:
286   case WebAssembly::FALLTHROUGH_RETURN_v4f32:
287   case WebAssembly::FALLTHROUGH_RETURN_v4f32_S:
288   case WebAssembly::FALLTHROUGH_RETURN_v2f64:
289   case WebAssembly::FALLTHROUGH_RETURN_v2f64_S: {
290     // These instructions represent the implicit return at the end of a
291     // function body. Always pops one value off the stack.
292     if (isVerbose()) {
293       OutStreamer->AddComment("fallthrough-return-value");
294       OutStreamer->AddBlankLine();
295     }
296     break;
297   }
298   case WebAssembly::FALLTHROUGH_RETURN_VOID:
299   case WebAssembly::FALLTHROUGH_RETURN_VOID_S:
300     // This instruction represents the implicit return at the end of a
301     // function body with no return value.
302     if (isVerbose()) {
303       OutStreamer->AddComment("fallthrough-return-void");
304       OutStreamer->AddBlankLine();
305     }
306     break;
307   default: {
308     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
309     MCInst TmpInst;
310     MCInstLowering.Lower(MI, TmpInst);
311     EmitToStreamer(*OutStreamer, TmpInst);
312     break;
313   }
314   }
315 }
316 
317 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
318   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
319     if (GV->getValueType()->isFunctionTy()) {
320       return MCSymbolRefExpr::create(
321           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
322     }
323   return AsmPrinter::lowerConstant(CV);
324 }
325 
326 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
327                                             unsigned OpNo, unsigned AsmVariant,
328                                             const char *ExtraCode,
329                                             raw_ostream &OS) {
330   if (AsmVariant != 0)
331     report_fatal_error("There are no defined alternate asm variants");
332 
333   // First try the generic code, which knows about modifiers like 'c' and 'n'.
334   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
335     return false;
336 
337   if (!ExtraCode) {
338     const MachineOperand &MO = MI->getOperand(OpNo);
339     switch (MO.getType()) {
340     case MachineOperand::MO_Immediate:
341       OS << MO.getImm();
342       return false;
343     case MachineOperand::MO_Register:
344       // FIXME: only opcode that still contains registers, as required by
345       // MachineInstr::getDebugVariable().
346       assert(MI->getOpcode() == WebAssembly::INLINEASM);
347       OS << regToString(MO);
348       return false;
349     case MachineOperand::MO_GlobalAddress:
350       getSymbol(MO.getGlobal())->print(OS, MAI);
351       printOffset(MO.getOffset(), OS);
352       return false;
353     case MachineOperand::MO_ExternalSymbol:
354       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
355       printOffset(MO.getOffset(), OS);
356       return false;
357     case MachineOperand::MO_MachineBasicBlock:
358       MO.getMBB()->getSymbol()->print(OS, MAI);
359       return false;
360     default:
361       break;
362     }
363   }
364 
365   return true;
366 }
367 
368 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
369                                                   unsigned OpNo,
370                                                   unsigned AsmVariant,
371                                                   const char *ExtraCode,
372                                                   raw_ostream &OS) {
373   if (AsmVariant != 0)
374     report_fatal_error("There are no defined alternate asm variants");
375 
376   // The current approach to inline asm is that "r" constraints are expressed
377   // as local indices, rather than values on the operand stack. This simplifies
378   // using "r" as it eliminates the need to push and pop the values in a
379   // particular order, however it also makes it impossible to have an "m"
380   // constraint. So we don't support it.
381 
382   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
383 }
384 
385 // Force static initialization.
386 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
387   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
388   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
389 }
390