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 "WebAssembly.h"
18 #include "InstPrinter/WebAssemblyInstPrinter.h"
19 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
20 #include "WebAssemblyMCInstLower.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "WebAssemblyRegisterInfo.h"
23 #include "WebAssemblySubtarget.h"
24 #include "llvm/ADT/SmallString.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/IR/DataLayout.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
40 #define DEBUG_TYPE "asm-printer"
44 class WebAssemblyAsmPrinter final : public AsmPrinter {
45 const MachineRegisterInfo *MRI;
46 const WebAssemblyFunctionInfo *MFI;
49 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
50 : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {}
53 const char *getPassName() const override {
54 return "WebAssembly Assembly Printer";
57 //===------------------------------------------------------------------===//
58 // MachineFunctionPass Implementation.
59 //===------------------------------------------------------------------===//
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AsmPrinter::getAnalysisUsage(AU);
65 bool runOnMachineFunction(MachineFunction &MF) override {
66 MRI = &MF.getRegInfo();
67 MFI = MF.getInfo<WebAssemblyFunctionInfo>();
68 return AsmPrinter::runOnMachineFunction(MF);
71 //===------------------------------------------------------------------===//
72 // AsmPrinter Implementation.
73 //===------------------------------------------------------------------===//
75 void EmitJumpTableInfo() override;
76 void EmitConstantPool() override;
77 void EmitFunctionBodyStart() override;
78 void EmitInstruction(const MachineInstr *MI) override;
79 void EmitEndOfAsmFile(Module &M) override;
81 std::string getRegTypeName(unsigned RegNo) const;
82 const char *toString(MVT VT) const;
83 std::string regToString(const MachineOperand &MO);
86 } // end anonymous namespace
88 //===----------------------------------------------------------------------===//
90 //===----------------------------------------------------------------------===//
92 std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
93 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
94 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
96 return EVT(T).getEVTString();
97 DEBUG(errs() << "Unknown type for register number: " << RegNo);
98 llvm_unreachable("Unknown register type");
102 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
103 unsigned RegNo = MO.getReg();
104 if (TargetRegisterInfo::isPhysicalRegister(RegNo))
105 return WebAssemblyInstPrinter::getRegisterName(RegNo);
107 unsigned WAReg = MFI->getWAReg(RegNo);
108 assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
109 return utostr(WAReg);
112 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
113 switch (VT.SimpleTy) {
125 DEBUG(dbgs() << "Invalid type " << EVT(VT).getEVTString() << '\n');
126 llvm_unreachable("invalid type");
130 //===----------------------------------------------------------------------===//
131 // WebAssemblyAsmPrinter Implementation.
132 //===----------------------------------------------------------------------===//
134 void WebAssemblyAsmPrinter::EmitConstantPool() {
135 assert(MF->getConstantPool()->getConstants().empty() &&
136 "WebAssembly disables constant pools");
139 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
140 // Nothing to do; jump tables are incorporated into the instruction stream.
143 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
144 SmallString<128> Str;
145 raw_svector_ostream OS(Str);
147 for (MVT VT : MFI->getParams())
148 OS << "\t" ".param " << toString(VT) << '\n';
149 for (MVT VT : MFI->getResults())
150 OS << "\t" ".result " << toString(VT) << '\n';
152 bool FirstVReg = true;
153 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
154 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
155 if (!MRI->use_empty(VReg)) {
157 OS << "\t" ".local ";
160 OS << getRegTypeName(VReg);
167 // EmitRawText appends a newline, so strip off the last newline.
168 StringRef Text = OS.str();
170 OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
171 AsmPrinter::EmitFunctionBodyStart();
174 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
175 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
177 assert(MI->getDesc().getNumDefs() <= 1 &&
178 "Instructions with multiple result values not implemented");
180 switch (MI->getOpcode()) {
181 case TargetOpcode::COPY: {
182 // TODO: Figure out a way to lower COPY instructions to MCInst form.
183 SmallString<128> Str;
184 raw_svector_ostream OS(Str);
185 OS << "\t" "set_local " << regToString(MI->getOperand(0)) << ", "
186 "(get_local " << regToString(MI->getOperand(1)) << ")";
187 OutStreamer->EmitRawText(OS.str());
190 case WebAssembly::ARGUMENT_I32:
191 case WebAssembly::ARGUMENT_I64:
192 case WebAssembly::ARGUMENT_F32:
193 case WebAssembly::ARGUMENT_F64:
194 // These represent values which are live into the function entry, so there's
195 // no instruction to emit.
198 WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
200 MCInstLowering.Lower(MI, TmpInst);
201 EmitToStreamer(*OutStreamer, TmpInst);
207 static void ComputeLegalValueVTs(LLVMContext &Context,
208 const WebAssemblyTargetLowering &TLI,
209 const DataLayout &DL, Type *Ty,
210 SmallVectorImpl<MVT> &ValueVTs) {
211 SmallVector<EVT, 4> VTs;
212 ComputeValueVTs(TLI, DL, Ty, VTs);
215 unsigned NumRegs = TLI.getNumRegisters(Context, VT);
216 MVT RegisterVT = TLI.getRegisterType(Context, VT);
217 for (unsigned i = 0; i != NumRegs; ++i)
218 ValueVTs.push_back(RegisterVT);
222 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
223 const DataLayout &DL = M.getDataLayout();
225 SmallString<128> Str;
226 raw_svector_ostream OS(Str);
227 for (const Function &F : M)
228 if (F.isDeclarationForLinker()) {
229 assert(F.hasName() && "imported functions must have a name");
233 OS << "\t.imports\n";
235 MCSymbol *Sym = OutStreamer->getContext().getOrCreateSymbol(F.getName());
236 OS << "\t.import " << *Sym << " \"\" " << *Sym;
238 const WebAssemblyTargetLowering &TLI =
239 *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
241 // If we need to legalize the return type, it'll get converted into
242 // passing a pointer.
243 bool SawParam = false;
244 SmallVector<MVT, 4> ResultVTs;
245 ComputeLegalValueVTs(M.getContext(), TLI, DL, F.getReturnType(),
247 if (ResultVTs.size() > 1) {
249 OS << " (param " << toString(TLI.getPointerTy(DL));
253 for (const Argument &A : F.args()) {
254 SmallVector<MVT, 4> ParamVTs;
255 ComputeLegalValueVTs(M.getContext(), TLI, DL, A.getType(), ParamVTs);
256 for (EVT VT : ParamVTs) {
261 OS << ' ' << toString(VT.getSimpleVT());
267 for (EVT VT : ResultVTs)
268 OS << " (result " << toString(VT.getSimpleVT()) << ')';
273 StringRef Text = OS.str();
275 OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
278 // Force static initialization.
279 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
280 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
281 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);