1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
15 //===----------------------------------------------------------------------===//
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/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolWasm.h"
37 #include "llvm/MC/MCSymbolELF.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "asm-printer"
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
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::v4f32})
54 if (TRI->isTypeLegalForClass(*TRC, T))
56 DEBUG(errs() << "Unknown type for register number: " << RegNo);
57 llvm_unreachable("Unknown register type");
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);
71 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
72 MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
73 return static_cast<WebAssemblyTargetStreamer *>(TS);
76 //===----------------------------------------------------------------------===//
77 // WebAssemblyAsmPrinter Implementation.
78 //===----------------------------------------------------------------------===//
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 getTargetStreamer()->emitIndirectFunctionType(F.getName(), Params,
91 for (const auto &G : M.globals()) {
92 if (!G.hasInitializer() && G.hasExternalLinkage()) {
93 uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
94 getTargetStreamer()->emitGlobalImport(G.getGlobalIdentifier());
95 OutStreamer->emitELFSize(getSymbol(&G),
96 MCConstantExpr::create(Size, OutContext));
101 void WebAssemblyAsmPrinter::EmitConstantPool() {
102 assert(MF->getConstantPool()->getConstants().empty() &&
103 "WebAssembly disables constant pools");
106 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
107 // Nothing to do; jump tables are incorporated into the instruction stream.
110 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
111 getTargetStreamer()->emitParam(CurrentFnSym, MFI->getParams());
113 SmallVector<MVT, 4> ResultVTs;
114 const Function &F(*MF->getFunction());
116 // Emit the function index.
117 if (MDNode *Idx = F.getMetadata("wasm.index")) {
118 assert(Idx->getNumOperands() == 1);
120 getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
121 cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
124 ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
126 // If the return type needs to be legalized it will get converted into
127 // passing a pointer.
128 if (ResultVTs.size() == 1)
129 getTargetStreamer()->emitResult(CurrentFnSym, ResultVTs);
131 getTargetStreamer()->emitResult(CurrentFnSym, ArrayRef<MVT>());
133 if (TM.getTargetTriple().isOSBinFormatELF()) {
134 assert(MFI->getLocals().empty());
135 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
136 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
137 unsigned WAReg = MFI->getWAReg(VReg);
138 // Don't declare unused registers.
139 if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
141 // Don't redeclare parameters.
142 if (WAReg < MFI->getParams().size())
144 // Don't declare stackified registers.
147 MFI->addLocal(getRegType(VReg));
151 getTargetStreamer()->emitLocal(MFI->getLocals());
153 AsmPrinter::EmitFunctionBodyStart();
156 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
157 if (TM.getTargetTriple().isOSBinFormatELF())
158 getTargetStreamer()->emitEndFunc();
161 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
162 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
164 switch (MI->getOpcode()) {
165 case WebAssembly::ARGUMENT_I32:
166 case WebAssembly::ARGUMENT_I64:
167 case WebAssembly::ARGUMENT_F32:
168 case WebAssembly::ARGUMENT_F64:
169 case WebAssembly::ARGUMENT_v16i8:
170 case WebAssembly::ARGUMENT_v8i16:
171 case WebAssembly::ARGUMENT_v4i32:
172 case WebAssembly::ARGUMENT_v4f32:
173 // These represent values which are live into the function entry, so there's
174 // no instruction to emit.
176 case WebAssembly::FALLTHROUGH_RETURN_I32:
177 case WebAssembly::FALLTHROUGH_RETURN_I64:
178 case WebAssembly::FALLTHROUGH_RETURN_F32:
179 case WebAssembly::FALLTHROUGH_RETURN_F64:
180 case WebAssembly::FALLTHROUGH_RETURN_v16i8:
181 case WebAssembly::FALLTHROUGH_RETURN_v8i16:
182 case WebAssembly::FALLTHROUGH_RETURN_v4i32:
183 case WebAssembly::FALLTHROUGH_RETURN_v4f32: {
184 // These instructions represent the implicit return at the end of a
185 // function body. The operand is always a pop.
186 assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
189 OutStreamer->AddComment("fallthrough-return: $pop" +
190 utostr(MFI->getWARegStackId(
191 MFI->getWAReg(MI->getOperand(0).getReg()))));
192 OutStreamer->AddBlankLine();
196 case WebAssembly::FALLTHROUGH_RETURN_VOID:
197 // This instruction represents the implicit return at the end of a
198 // function body with no return value.
200 OutStreamer->AddComment("fallthrough-return");
201 OutStreamer->AddBlankLine();
205 WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
207 MCInstLowering.Lower(MI, TmpInst);
208 EmitToStreamer(*OutStreamer, TmpInst);
214 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
215 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
216 if (GV->getValueType()->isFunctionTy()) {
217 MCSymbol* Sym = getSymbol(GV);
218 if (!isa<MCSymbolELF>(Sym))
219 cast<MCSymbolWasm>(Sym)->setIsFunction(true);
220 return MCSymbolRefExpr::create(
221 Sym, MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
223 return AsmPrinter::lowerConstant(CV);
226 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
227 unsigned OpNo, unsigned AsmVariant,
228 const char *ExtraCode,
231 report_fatal_error("There are no defined alternate asm variants");
233 // First try the generic code, which knows about modifiers like 'c' and 'n'.
234 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
238 const MachineOperand &MO = MI->getOperand(OpNo);
239 switch (MO.getType()) {
240 case MachineOperand::MO_Immediate:
243 case MachineOperand::MO_Register:
244 OS << regToString(MO);
246 case MachineOperand::MO_GlobalAddress:
247 getSymbol(MO.getGlobal())->print(OS, MAI);
248 printOffset(MO.getOffset(), OS);
250 case MachineOperand::MO_ExternalSymbol:
251 GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
252 printOffset(MO.getOffset(), OS);
254 case MachineOperand::MO_MachineBasicBlock:
255 MO.getMBB()->getSymbol()->print(OS, MAI);
265 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
268 const char *ExtraCode,
271 report_fatal_error("There are no defined alternate asm variants");
274 // TODO: For now, we just hard-code 0 as the constant offset; teach
275 // SelectInlineAsmMemoryOperand how to do address mode matching.
276 OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
280 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
283 // Force static initialization.
284 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
285 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
286 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());