blob: 6b5f653f3b9b811816fb588d0a3be18106661614 [file] [log] [blame]
JF Bastienb9073fb2015-07-22 21:28:15 +00001//===-- 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/// \brief 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 "WebAssembly.h"
18#include "WebAssemblyMachineFunctionInfo.h"
19#include "WebAssemblyRegisterInfo.h"
20#include "WebAssemblySubtarget.h"
21#include "InstPrinter/WebAssemblyInstPrinter.h"
22#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
23
24#include "llvm/ADT/SmallString.h"
Dan Gohmane51c0582015-10-06 00:27:55 +000025#include "llvm/ADT/StringExtras.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000026#include "llvm/CodeGen/AsmPrinter.h"
JF Bastien54be3b12015-08-25 23:19:49 +000027#include "llvm/CodeGen/MachineConstantPool.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000028#include "llvm/CodeGen/MachineInstr.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DebugInfo.h"
31#include "llvm/MC/MCStreamer.h"
JF Bastienb6091df2015-08-25 22:58:05 +000032#include "llvm/MC/MCSymbol.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/raw_ostream.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "asm-printer"
40
41namespace {
42
43class WebAssemblyAsmPrinter final : public AsmPrinter {
JF Bastien600aee92015-07-31 17:53:38 +000044 const WebAssemblyInstrInfo *TII;
JF Bastien1d20a5e2015-10-16 00:53:49 +000045 const MachineRegisterInfo *MRI;
Dan Gohmane51c0582015-10-06 00:27:55 +000046 unsigned NumArgs;
JF Bastien600aee92015-07-31 17:53:38 +000047
JF Bastienb9073fb2015-07-22 21:28:15 +000048public:
49 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
JF Bastien1d20a5e2015-10-16 00:53:49 +000050 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr), MRI(nullptr) {}
JF Bastienb9073fb2015-07-22 21:28:15 +000051
52private:
53 const char *getPassName() const override {
54 return "WebAssembly Assembly Printer";
55 }
56
57 //===------------------------------------------------------------------===//
58 // MachineFunctionPass Implementation.
59 //===------------------------------------------------------------------===//
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AsmPrinter::getAnalysisUsage(AU);
63 }
64
JF Bastien600aee92015-07-31 17:53:38 +000065 bool runOnMachineFunction(MachineFunction &MF) override {
JF Bastien73ff6af2015-08-31 22:24:11 +000066 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
JF Bastien73ff6af2015-08-31 22:24:11 +000067 TII = Subtarget.getInstrInfo();
JF Bastien1d20a5e2015-10-16 00:53:49 +000068 MRI = &MF.getRegInfo();
Dan Gohmane51c0582015-10-06 00:27:55 +000069 NumArgs = MF.getInfo<WebAssemblyFunctionInfo>()->getNumArguments();
JF Bastien600aee92015-07-31 17:53:38 +000070 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000071 }
72
73 //===------------------------------------------------------------------===//
74 // AsmPrinter Implementation.
75 //===------------------------------------------------------------------===//
76
Dan Gohman950a13c2015-09-16 16:51:30 +000077 void EmitJumpTableInfo() override;
JF Bastien54be3b12015-08-25 23:19:49 +000078 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000079 void EmitFunctionBodyStart() override;
JF Bastienb9073fb2015-07-22 21:28:15 +000080 void EmitInstruction(const MachineInstr *MI) override;
JF Bastien1a59c6b2015-10-21 02:23:09 +000081 void EmitEndOfAsmFile(Module &M) override;
Dan Gohman979840d2015-09-23 16:59:10 +000082
JF Bastien1d20a5e2015-10-16 00:53:49 +000083 std::string getRegTypeName(unsigned RegNo) const;
Dan Gohman979840d2015-09-23 16:59:10 +000084 static std::string toString(const APFloat &APF);
85 const char *toString(Type *Ty) const;
JF Bastien1d20a5e2015-10-16 00:53:49 +000086 std::string regToString(const MachineOperand &MO);
87 std::string argToString(const MachineOperand &MO);
JF Bastienb9073fb2015-07-22 21:28:15 +000088};
89
90} // end anonymous namespace
91
92//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000093// Helpers.
94//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000095
JF Bastien1d20a5e2015-10-16 00:53:49 +000096// Operand type (if any), followed by the lower-case version of the opcode's
97// name matching the names WebAssembly opcodes are expected to have. The
98// tablegen names are uppercase and suffixed with their type (after an
99// underscore).
100static std::string OpcodeName(const WebAssemblyInstrInfo *TII,
101 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +0000102 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
JF Bastien1d20a5e2015-10-16 00:53:49 +0000103 std::string::size_type Len = N.length();
104 std::string::size_type Under = N.rfind('_');
105 bool HasType = std::string::npos != Under;
106 std::string::size_type NameEnd = HasType ? Under : Len;
107 std::string Name(&N[0], &N[NameEnd]);
JF Bastienc8f89e82015-10-20 01:26:54 +0000108 if (!HasType)
109 return Name;
JF Bastienf2364bf2015-10-22 02:32:50 +0000110 for (const char *typelessOpcode : { "return", "call", "br_if" })
JF Bastienc8f89e82015-10-20 01:26:54 +0000111 if (Name == typelessOpcode)
112 return Name;
113 return std::string(&N[NameEnd + 1], &N[Len]) + '.' + Name;
JF Bastien315cc062015-08-07 01:57:03 +0000114}
115
JF Bastienaf111db2015-08-24 22:16:48 +0000116static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
117
JF Bastien1d20a5e2015-10-16 00:53:49 +0000118std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
119 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
120 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
121 if (TRC->hasType(T))
122 return EVT(T).getEVTString();
123 DEBUG(errs() << "Unknown type for register number: " << RegNo);
124 llvm_unreachable("Unknown register type");
125 return "?";
126}
127
Dan Gohman979840d2015-09-23 16:59:10 +0000128std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
JF Bastien45479f62015-08-26 22:09:54 +0000129 static const size_t BufBytes = 128;
130 char buf[BufBytes];
131 if (FP.isNaN())
132 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
133 FP.bitwiseIsEqual(
134 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
135 "convertToHexString handles neither SNaN nor NaN payloads");
136 // Use C99's hexadecimal floating-point representation.
137 auto Written = FP.convertToHexString(
138 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
139 (void)Written;
140 assert(Written != 0);
141 assert(Written < BufBytes);
142 return buf;
143}
144
JF Bastien1d20a5e2015-10-16 00:53:49 +0000145std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
146 unsigned RegNo = MO.getReg();
Dan Gohmane51c0582015-10-06 00:27:55 +0000147 if (TargetRegisterInfo::isPhysicalRegister(RegNo))
148 return WebAssemblyInstPrinter::getRegisterName(RegNo);
149
150 // WebAssembly arguments and local variables are in the same index space, and
151 // there are no explicit varargs, so we just add the number of arguments to
152 // the virtual register number to get the local variable number.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000153 return utostr(TargetRegisterInfo::virtReg2Index(RegNo) + NumArgs);
Dan Gohmane51c0582015-10-06 00:27:55 +0000154}
155
JF Bastien1d20a5e2015-10-16 00:53:49 +0000156std::string WebAssemblyAsmPrinter::argToString(const MachineOperand &MO) {
157 unsigned ArgNo = MO.getImm();
Dan Gohmane51c0582015-10-06 00:27:55 +0000158 // Same as above, but we don't need to add NumArgs here.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000159 return utostr(ArgNo);
Dan Gohmane51c0582015-10-06 00:27:55 +0000160}
161
Dan Gohman979840d2015-09-23 16:59:10 +0000162const char *WebAssemblyAsmPrinter::toString(Type *Ty) const {
JF Bastien73ff6af2015-08-31 22:24:11 +0000163 switch (Ty->getTypeID()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000164 default:
165 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000166 // Treat all pointers as the underlying integer into linear memory.
Dan Gohman979840d2015-09-23 16:59:10 +0000167 case Type::PointerTyID:
168 switch (getPointerSize()) {
169 case 4:
170 return "i32";
171 case 8:
172 return "i64";
173 default:
174 llvm_unreachable("unsupported pointer size");
175 }
176 break;
177 case Type::FloatTyID:
178 return "f32";
179 case Type::DoubleTyID:
180 return "f64";
JF Bastien73ff6af2015-08-31 22:24:11 +0000181 case Type::IntegerTyID:
182 switch (Ty->getIntegerBitWidth()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000183 case 8:
184 return "i8";
185 case 16:
186 return "i16";
187 case 32:
188 return "i32";
189 case 64:
190 return "i64";
191 default:
192 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000193 }
194 }
195 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
196 llvm_unreachable("invalid type");
197 return "<invalid>";
198}
199
JF Bastien45479f62015-08-26 22:09:54 +0000200//===----------------------------------------------------------------------===//
201// WebAssemblyAsmPrinter Implementation.
202//===----------------------------------------------------------------------===//
203
JF Bastien54be3b12015-08-25 23:19:49 +0000204void WebAssemblyAsmPrinter::EmitConstantPool() {
205 assert(MF->getConstantPool()->getConstants().empty() &&
206 "WebAssembly disables constant pools");
207}
208
Dan Gohman950a13c2015-09-16 16:51:30 +0000209void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
210 // Nothing to do; jump tables are incorporated into the instruction stream.
211}
212
JF Bastienb6091df2015-08-25 22:58:05 +0000213void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
JF Bastienb6091df2015-08-25 22:58:05 +0000214 const Function *F = MF->getFunction();
Dan Gohman979840d2015-09-23 16:59:10 +0000215 Type *Rt = F->getReturnType();
JF Bastien1d20a5e2015-10-16 00:53:49 +0000216 SmallString<128> Str;
217 raw_svector_ostream OS(Str);
218 bool First = true;
Dan Gohmane51c0582015-10-06 00:27:55 +0000219
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000220 if (!Rt->isVoidTy() || !F->arg_empty()) {
Dan Gohmane51c0582015-10-06 00:27:55 +0000221 for (const Argument &A : F->args()) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000222 OS << (First ? "" : "\n") << "\t.param " << toString(A.getType());
Dan Gohmane51c0582015-10-06 00:27:55 +0000223 First = false;
224 }
225 if (!Rt->isVoidTy()) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000226 OS << (First ? "" : "\n") << "\t.result " << toString(Rt);
Dan Gohmane51c0582015-10-06 00:27:55 +0000227 First = false;
228 }
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000229 }
JF Bastienb6091df2015-08-25 22:58:05 +0000230
JF Bastien1d20a5e2015-10-16 00:53:49 +0000231 bool FirstVReg = true;
232 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
233 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
JF Bastien3428ed42015-10-17 00:25:38 +0000234 // FIXME: Don't skip dead virtual registers for now: that would require
235 // remapping all locals' numbers.
236 //if (!MRI->use_empty(VReg)) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000237 if (FirstVReg) {
238 OS << (First ? "" : "\n") << "\t.local ";
239 First = false;
240 }
241 OS << (FirstVReg ? "" : ", ") << getRegTypeName(VReg);
242 FirstVReg = false;
JF Bastien3428ed42015-10-17 00:25:38 +0000243 //}
JF Bastien1d20a5e2015-10-16 00:53:49 +0000244 }
245
246 if (!First)
247 OutStreamer->EmitRawText(OS.str());
Dan Gohmane51c0582015-10-06 00:27:55 +0000248 AsmPrinter::EmitFunctionBodyStart();
JF Bastienb6091df2015-08-25 22:58:05 +0000249}
250
JF Bastienb9073fb2015-07-22 21:28:15 +0000251void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000252 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000253 SmallString<128> Str;
254 raw_svector_ostream OS(Str);
255
JF Bastien600aee92015-07-31 17:53:38 +0000256 unsigned NumDefs = MI->getDesc().getNumDefs();
257 assert(NumDefs <= 1 &&
258 "Instructions with multiple result values not implemented");
259
Dan Gohman12e19972015-08-24 21:19:48 +0000260 OS << '\t';
261
Dan Gohmane51c0582015-10-06 00:27:55 +0000262 switch (MI->getOpcode()) {
263 case TargetOpcode::COPY:
JF Bastien1d20a5e2015-10-16 00:53:49 +0000264 OS << "get_local " << regToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000265 break;
266 case WebAssembly::GLOBAL:
267 // TODO: wasm64
268 OS << "i32.const " << toSymbol(MI->getOperand(1).getGlobal()->getName());
269 break;
270 case WebAssembly::ARGUMENT_I32:
271 case WebAssembly::ARGUMENT_I64:
272 case WebAssembly::ARGUMENT_F32:
273 case WebAssembly::ARGUMENT_F64:
JF Bastien1d20a5e2015-10-16 00:53:49 +0000274 OS << "get_local " << argToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000275 break;
276 case WebAssembly::Immediate_I32:
277 OS << "i32.const " << MI->getOperand(1).getImm();
278 break;
279 case WebAssembly::Immediate_I64:
280 OS << "i64.const " << MI->getOperand(1).getImm();
281 break;
282 case WebAssembly::Immediate_F32:
283 OS << "f32.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
284 break;
285 case WebAssembly::Immediate_F64:
286 OS << "f64.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
287 break;
288 default: {
289 OS << OpcodeName(TII, MI);
290 bool NeedComma = false;
291 for (const MachineOperand &MO : MI->uses()) {
292 if (MO.isReg() && MO.isImplicit())
293 continue;
294 if (NeedComma)
295 OS << ',';
296 NeedComma = true;
297 OS << ' ';
Dan Gohman4f52e002015-09-09 00:52:47 +0000298 switch (MO.getType()) {
299 default:
300 llvm_unreachable("unexpected machine operand type");
Dan Gohmane51c0582015-10-06 00:27:55 +0000301 case MachineOperand::MO_Register:
JF Bastien1d20a5e2015-10-16 00:53:49 +0000302 OS << "(get_local " << regToString(MO) << ')';
Dan Gohmane51c0582015-10-06 00:27:55 +0000303 break;
304 case MachineOperand::MO_Immediate:
305 OS << MO.getImm();
306 break;
307 case MachineOperand::MO_FPImmediate:
308 OS << toString(MO.getFPImm()->getValueAPF());
309 break;
310 case MachineOperand::MO_GlobalAddress:
311 OS << toSymbol(MO.getGlobal()->getName());
312 break;
313 case MachineOperand::MO_MachineBasicBlock:
314 OS << toSymbol(MO.getMBB()->getSymbol()->getName());
315 break;
Dan Gohman4f52e002015-09-09 00:52:47 +0000316 }
Dan Gohmane51c0582015-10-06 00:27:55 +0000317 }
318 break;
319 }
Dan Gohman4f52e002015-09-09 00:52:47 +0000320 }
JF Bastien600aee92015-07-31 17:53:38 +0000321
JF Bastienb9073fb2015-07-22 21:28:15 +0000322 OutStreamer->EmitRawText(OS.str());
Dan Gohmane51c0582015-10-06 00:27:55 +0000323
324 if (NumDefs != 0) {
325 SmallString<128> Str;
326 raw_svector_ostream OS(Str);
JF Bastien1d20a5e2015-10-16 00:53:49 +0000327 const MachineOperand &Operand = MI->getOperand(0);
328 OS << "\tset_local " << regToString(Operand) << ", pop";
Dan Gohmane51c0582015-10-06 00:27:55 +0000329 OutStreamer->EmitRawText(OS.str());
330 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000331}
332
JF Bastien1a59c6b2015-10-21 02:23:09 +0000333void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
334 SmallString<128> Str;
335 raw_svector_ostream OS(Str);
336 for (const Function &F : M)
337 if (F.isDeclarationForLinker()) {
338 assert(F.hasName() && "imported functions must have a name");
339 if (F.getName().startswith("llvm."))
340 continue;
341 if (Str.empty())
342 OS << "\t.imports\n";
343 Type *Rt = F.getReturnType();
344 OS << "\t.import " << toSymbol(F.getName()) << " \"\" \"" << F.getName()
345 << "\"";
346 for (const Argument &A : F.args())
347 OS << " (param " << toString(A.getType()) << ')';
348 if (!Rt->isVoidTy())
349 OS << " (result " << toString(Rt) << ')';
350 OS << '\n';
351 }
352 OutStreamer->EmitRawText(OS.str());
353}
354
JF Bastienb9073fb2015-07-22 21:28:15 +0000355// Force static initialization.
356extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
357 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
358 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
359}