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