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 (const auto &F : M) {
82     // Emit function type info for all undefined functions
83     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
84       SmallVector<MVT, 4> Results;
85       SmallVector<MVT, 4> Params;
86       ComputeSignatureVTs(F, TM, Params, Results);
87       MCSymbol *Sym = getSymbol(&F);
88       getTargetStreamer()->emitIndirectFunctionType(Sym, Params, Results);
89 
90       if (TM.getTargetTriple().isOSBinFormatWasm() &&
91           F.hasFnAttribute("wasm-import-module")) {
92         MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Sym);
93         StringRef Name =
94             F.getFnAttribute("wasm-import-module").getValueAsString();
95         getTargetStreamer()->emitImportModule(WasmSym, Name);
96       }
97     }
98   }
99   for (const auto &G : M.globals()) {
100     if (!G.hasInitializer() && G.hasExternalLinkage()) {
101       if (G.getValueType()->isSized()) {
102         uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
103         OutStreamer->emitELFSize(getSymbol(&G),
104                                  MCConstantExpr::create(Size, OutContext));
105       }
106     }
107   }
108 
109   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
110     for (const Metadata *MD : Named->operands()) {
111       const MDTuple *Tuple = dyn_cast<MDTuple>(MD);
112       if (!Tuple || Tuple->getNumOperands() != 2)
113         continue;
114       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
115       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
116       if (!Name || !Contents)
117         continue;
118 
119       OutStreamer->PushSection();
120       std::string SectionName = (".custom_section." + Name->getString()).str();
121       MCSectionWasm *mySection =
122           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
123       OutStreamer->SwitchSection(mySection);
124       OutStreamer->EmitBytes(Contents->getString());
125       OutStreamer->PopSection();
126     }
127   }
128 }
129 
130 void WebAssemblyAsmPrinter::EmitConstantPool() {
131   assert(MF->getConstantPool()->getConstants().empty() &&
132          "WebAssembly disables constant pools");
133 }
134 
135 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
136   // Nothing to do; jump tables are incorporated into the instruction stream.
137 }
138 
139 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
140   getTargetStreamer()->emitParam(CurrentFnSym, MFI->getParams());
141 
142   SmallVector<MVT, 4> ResultVTs;
143   const Function &F = MF->getFunction();
144 
145   // Emit the function index.
146   if (MDNode *Idx = F.getMetadata("wasm.index")) {
147     assert(Idx->getNumOperands() == 1);
148 
149     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
150         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
151   }
152 
153   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
154 
155   // If the return type needs to be legalized it will get converted into
156   // passing a pointer.
157   if (ResultVTs.size() == 1)
158     getTargetStreamer()->emitResult(CurrentFnSym, ResultVTs);
159   else
160     getTargetStreamer()->emitResult(CurrentFnSym, ArrayRef<MVT>());
161 
162   getTargetStreamer()->emitLocal(MFI->getLocals());
163 
164   AsmPrinter::EmitFunctionBodyStart();
165 }
166 
167 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
168   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
169 
170   switch (MI->getOpcode()) {
171   case WebAssembly::ARGUMENT_I32:
172   case WebAssembly::ARGUMENT_I32_S:
173   case WebAssembly::ARGUMENT_I64:
174   case WebAssembly::ARGUMENT_I64_S:
175   case WebAssembly::ARGUMENT_F32:
176   case WebAssembly::ARGUMENT_F32_S:
177   case WebAssembly::ARGUMENT_F64:
178   case WebAssembly::ARGUMENT_F64_S:
179   case WebAssembly::ARGUMENT_v16i8:
180   case WebAssembly::ARGUMENT_v16i8_S:
181   case WebAssembly::ARGUMENT_v8i16:
182   case WebAssembly::ARGUMENT_v8i16_S:
183   case WebAssembly::ARGUMENT_v4i32:
184   case WebAssembly::ARGUMENT_v4i32_S:
185   case WebAssembly::ARGUMENT_v2i64:
186   case WebAssembly::ARGUMENT_v2i64_S:
187   case WebAssembly::ARGUMENT_v4f32:
188   case WebAssembly::ARGUMENT_v4f32_S:
189   case WebAssembly::ARGUMENT_v2f64:
190   case WebAssembly::ARGUMENT_v2f64_S:
191     // These represent values which are live into the function entry, so there's
192     // no instruction to emit.
193     break;
194   case WebAssembly::FALLTHROUGH_RETURN_I32:
195   case WebAssembly::FALLTHROUGH_RETURN_I32_S:
196   case WebAssembly::FALLTHROUGH_RETURN_I64:
197   case WebAssembly::FALLTHROUGH_RETURN_I64_S:
198   case WebAssembly::FALLTHROUGH_RETURN_F32:
199   case WebAssembly::FALLTHROUGH_RETURN_F32_S:
200   case WebAssembly::FALLTHROUGH_RETURN_F64:
201   case WebAssembly::FALLTHROUGH_RETURN_F64_S:
202   case WebAssembly::FALLTHROUGH_RETURN_v16i8:
203   case WebAssembly::FALLTHROUGH_RETURN_v16i8_S:
204   case WebAssembly::FALLTHROUGH_RETURN_v8i16:
205   case WebAssembly::FALLTHROUGH_RETURN_v8i16_S:
206   case WebAssembly::FALLTHROUGH_RETURN_v4i32:
207   case WebAssembly::FALLTHROUGH_RETURN_v4i32_S:
208   case WebAssembly::FALLTHROUGH_RETURN_v2i64:
209   case WebAssembly::FALLTHROUGH_RETURN_v2i64_S:
210   case WebAssembly::FALLTHROUGH_RETURN_v4f32:
211   case WebAssembly::FALLTHROUGH_RETURN_v4f32_S:
212   case WebAssembly::FALLTHROUGH_RETURN_v2f64:
213   case WebAssembly::FALLTHROUGH_RETURN_v2f64_S: {
214     // These instructions represent the implicit return at the end of a
215     // function body. Always pops one value off the stack.
216     if (isVerbose()) {
217       OutStreamer->AddComment("fallthrough-return-value");
218       OutStreamer->AddBlankLine();
219     }
220     break;
221   }
222   case WebAssembly::FALLTHROUGH_RETURN_VOID:
223   case WebAssembly::FALLTHROUGH_RETURN_VOID_S:
224     // This instruction represents the implicit return at the end of a
225     // function body with no return value.
226     if (isVerbose()) {
227       OutStreamer->AddComment("fallthrough-return-void");
228       OutStreamer->AddBlankLine();
229     }
230     break;
231   default: {
232     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
233     MCInst TmpInst;
234     MCInstLowering.Lower(MI, TmpInst);
235     EmitToStreamer(*OutStreamer, TmpInst);
236     break;
237   }
238   }
239 }
240 
241 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
242   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
243     if (GV->getValueType()->isFunctionTy()) {
244       return MCSymbolRefExpr::create(
245           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
246     }
247   return AsmPrinter::lowerConstant(CV);
248 }
249 
250 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
251                                             unsigned OpNo, unsigned AsmVariant,
252                                             const char *ExtraCode,
253                                             raw_ostream &OS) {
254   if (AsmVariant != 0)
255     report_fatal_error("There are no defined alternate asm variants");
256 
257   // First try the generic code, which knows about modifiers like 'c' and 'n'.
258   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
259     return false;
260 
261   if (!ExtraCode) {
262     const MachineOperand &MO = MI->getOperand(OpNo);
263     switch (MO.getType()) {
264     case MachineOperand::MO_Immediate:
265       OS << MO.getImm();
266       return false;
267     case MachineOperand::MO_Register:
268       // FIXME: only opcode that still contains registers, as required by
269       // MachineInstr::getDebugVariable().
270       assert(MI->getOpcode() == WebAssembly::INLINEASM);
271       OS << regToString(MO);
272       return false;
273     case MachineOperand::MO_GlobalAddress:
274       getSymbol(MO.getGlobal())->print(OS, MAI);
275       printOffset(MO.getOffset(), OS);
276       return false;
277     case MachineOperand::MO_ExternalSymbol:
278       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
279       printOffset(MO.getOffset(), OS);
280       return false;
281     case MachineOperand::MO_MachineBasicBlock:
282       MO.getMBB()->getSymbol()->print(OS, MAI);
283       return false;
284     default:
285       break;
286     }
287   }
288 
289   return true;
290 }
291 
292 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
293                                                   unsigned OpNo,
294                                                   unsigned AsmVariant,
295                                                   const char *ExtraCode,
296                                                   raw_ostream &OS) {
297   if (AsmVariant != 0)
298     report_fatal_error("There are no defined alternate asm variants");
299 
300   // The current approach to inline asm is that "r" constraints are expressed
301   // as local indices, rather than values on the operand stack. This simplifies
302   // using "r" as it eliminates the need to push and pop the values in a
303   // particular order, however it also makes it impossible to have an "m"
304   // constraint. So we don't support it.
305 
306   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
307 }
308 
309 // Force static initialization.
310 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
311   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
312   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
313 }
314