blob: 27095ec51df4aad1ca00af3f280be86acc2d959d [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"
Dan Gohman754cd112015-11-11 01:33:02 +000026#include "llvm/CodeGen/Analysis.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000027#include "llvm/CodeGen/AsmPrinter.h"
JF Bastien54be3b12015-08-25 23:19:49 +000028#include "llvm/CodeGen/MachineConstantPool.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000029#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/MC/MCStreamer.h"
JF Bastienb6091df2015-08-25 22:58:05 +000033#include "llvm/MC/MCSymbol.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/raw_ostream.h"
37
38using namespace llvm;
39
40#define DEBUG_TYPE "asm-printer"
41
42namespace {
43
44class WebAssemblyAsmPrinter final : public AsmPrinter {
JF Bastien600aee92015-07-31 17:53:38 +000045 const WebAssemblyInstrInfo *TII;
JF Bastien1d20a5e2015-10-16 00:53:49 +000046 const MachineRegisterInfo *MRI;
Dan Gohmane51c0582015-10-06 00:27:55 +000047 unsigned NumArgs;
JF Bastien600aee92015-07-31 17:53:38 +000048
JF Bastienb9073fb2015-07-22 21:28:15 +000049public:
50 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
JF Bastien1d20a5e2015-10-16 00:53:49 +000051 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr), MRI(nullptr) {}
JF Bastienb9073fb2015-07-22 21:28:15 +000052
53private:
54 const char *getPassName() const override {
55 return "WebAssembly Assembly Printer";
56 }
57
58 //===------------------------------------------------------------------===//
59 // MachineFunctionPass Implementation.
60 //===------------------------------------------------------------------===//
61
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AsmPrinter::getAnalysisUsage(AU);
64 }
65
JF Bastien600aee92015-07-31 17:53:38 +000066 bool runOnMachineFunction(MachineFunction &MF) override {
JF Bastien73ff6af2015-08-31 22:24:11 +000067 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
JF Bastien73ff6af2015-08-31 22:24:11 +000068 TII = Subtarget.getInstrInfo();
JF Bastien1d20a5e2015-10-16 00:53:49 +000069 MRI = &MF.getRegInfo();
Dan Gohman754cd112015-11-11 01:33:02 +000070 NumArgs = MF.getInfo<WebAssemblyFunctionInfo>()->getParams().size();
JF Bastien600aee92015-07-31 17:53:38 +000071 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000072 }
73
74 //===------------------------------------------------------------------===//
75 // AsmPrinter Implementation.
76 //===------------------------------------------------------------------===//
77
Dan Gohman950a13c2015-09-16 16:51:30 +000078 void EmitJumpTableInfo() override;
JF Bastien54be3b12015-08-25 23:19:49 +000079 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000080 void EmitFunctionBodyStart() override;
JF Bastienb9073fb2015-07-22 21:28:15 +000081 void EmitInstruction(const MachineInstr *MI) override;
JF Bastien1a59c6b2015-10-21 02:23:09 +000082 void EmitEndOfAsmFile(Module &M) override;
Dan Gohman979840d2015-09-23 16:59:10 +000083
JF Bastien1d20a5e2015-10-16 00:53:49 +000084 std::string getRegTypeName(unsigned RegNo) const;
Dan Gohman979840d2015-09-23 16:59:10 +000085 static std::string toString(const APFloat &APF);
Dan Gohman754cd112015-11-11 01:33:02 +000086 const char *toString(MVT VT) const;
JF Bastien1d20a5e2015-10-16 00:53:49 +000087 std::string regToString(const MachineOperand &MO);
88 std::string argToString(const MachineOperand &MO);
JF Bastienb9073fb2015-07-22 21:28:15 +000089};
90
91} // end anonymous namespace
92
93//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000094// Helpers.
95//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000096
JF Bastien1d20a5e2015-10-16 00:53:49 +000097// Operand type (if any), followed by the lower-case version of the opcode's
98// name matching the names WebAssembly opcodes are expected to have. The
99// tablegen names are uppercase and suffixed with their type (after an
JF Bastien7b452e22015-10-29 04:10:52 +0000100// underscore). Conversions are additionally prefixed with their input type
101// (before a double underscore).
JF Bastien1d20a5e2015-10-16 00:53:49 +0000102static std::string OpcodeName(const WebAssemblyInstrInfo *TII,
103 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +0000104 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
JF Bastien1d20a5e2015-10-16 00:53:49 +0000105 std::string::size_type Len = N.length();
106 std::string::size_type Under = N.rfind('_');
107 bool HasType = std::string::npos != Under;
108 std::string::size_type NameEnd = HasType ? Under : Len;
109 std::string Name(&N[0], &N[NameEnd]);
JF Bastienc8f89e82015-10-20 01:26:54 +0000110 if (!HasType)
111 return Name;
JF Bastienf2364bf2015-10-22 02:32:50 +0000112 for (const char *typelessOpcode : { "return", "call", "br_if" })
JF Bastienc8f89e82015-10-20 01:26:54 +0000113 if (Name == typelessOpcode)
114 return Name;
JF Bastien7b452e22015-10-29 04:10:52 +0000115 std::string Type(&N[NameEnd + 1], &N[Len]);
116 std::string::size_type DoubleUnder = Name.find("__");
117 bool IsConv = std::string::npos != DoubleUnder;
118 if (!IsConv)
119 return Type + '.' + Name;
120 std::string InType(&Name[0], &Name[DoubleUnder]);
121 return Type + '.' + std::string(&Name[DoubleUnder + 2], &Name[NameEnd]) +
122 '/' + InType;
JF Bastien315cc062015-08-07 01:57:03 +0000123}
124
JF Bastienaf111db2015-08-24 22:16:48 +0000125static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
126
JF Bastien1d20a5e2015-10-16 00:53:49 +0000127std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
128 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
129 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
130 if (TRC->hasType(T))
131 return EVT(T).getEVTString();
132 DEBUG(errs() << "Unknown type for register number: " << RegNo);
133 llvm_unreachable("Unknown register type");
134 return "?";
135}
136
Dan Gohman979840d2015-09-23 16:59:10 +0000137std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
JF Bastien45479f62015-08-26 22:09:54 +0000138 static const size_t BufBytes = 128;
139 char buf[BufBytes];
140 if (FP.isNaN())
141 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
142 FP.bitwiseIsEqual(
143 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
144 "convertToHexString handles neither SNaN nor NaN payloads");
145 // Use C99's hexadecimal floating-point representation.
146 auto Written = FP.convertToHexString(
147 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
148 (void)Written;
149 assert(Written != 0);
150 assert(Written < BufBytes);
151 return buf;
152}
153
JF Bastien1d20a5e2015-10-16 00:53:49 +0000154std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
155 unsigned RegNo = MO.getReg();
Dan Gohmane51c0582015-10-06 00:27:55 +0000156 if (TargetRegisterInfo::isPhysicalRegister(RegNo))
157 return WebAssemblyInstPrinter::getRegisterName(RegNo);
158
159 // WebAssembly arguments and local variables are in the same index space, and
160 // there are no explicit varargs, so we just add the number of arguments to
161 // the virtual register number to get the local variable number.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000162 return utostr(TargetRegisterInfo::virtReg2Index(RegNo) + NumArgs);
Dan Gohmane51c0582015-10-06 00:27:55 +0000163}
164
JF Bastien1d20a5e2015-10-16 00:53:49 +0000165std::string WebAssemblyAsmPrinter::argToString(const MachineOperand &MO) {
166 unsigned ArgNo = MO.getImm();
Dan Gohmane51c0582015-10-06 00:27:55 +0000167 // Same as above, but we don't need to add NumArgs here.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000168 return utostr(ArgNo);
Dan Gohmane51c0582015-10-06 00:27:55 +0000169}
170
Dan Gohman754cd112015-11-11 01:33:02 +0000171const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
172 switch (VT.SimpleTy) {
Dan Gohman979840d2015-09-23 16:59:10 +0000173 default:
174 break;
Dan Gohman754cd112015-11-11 01:33:02 +0000175 case MVT::f32:
Dan Gohman979840d2015-09-23 16:59:10 +0000176 return "f32";
Dan Gohman754cd112015-11-11 01:33:02 +0000177 case MVT::f64:
Dan Gohman979840d2015-09-23 16:59:10 +0000178 return "f64";
Dan Gohman754cd112015-11-11 01:33:02 +0000179 case MVT::i32:
180 return "i32";
181 case MVT::i64:
182 return "i64";
JF Bastien73ff6af2015-08-31 22:24:11 +0000183 }
Dan Gohman754cd112015-11-11 01:33:02 +0000184 DEBUG(dbgs() << "Invalid type " << EVT(VT).getEVTString() << '\n');
JF Bastien73ff6af2015-08-31 22:24:11 +0000185 llvm_unreachable("invalid type");
186 return "<invalid>";
187}
188
JF Bastien45479f62015-08-26 22:09:54 +0000189//===----------------------------------------------------------------------===//
190// WebAssemblyAsmPrinter Implementation.
191//===----------------------------------------------------------------------===//
192
JF Bastien54be3b12015-08-25 23:19:49 +0000193void WebAssemblyAsmPrinter::EmitConstantPool() {
194 assert(MF->getConstantPool()->getConstants().empty() &&
195 "WebAssembly disables constant pools");
196}
197
Dan Gohman950a13c2015-09-16 16:51:30 +0000198void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
199 // Nothing to do; jump tables are incorporated into the instruction stream.
200}
201
JF Bastienb6091df2015-08-25 22:58:05 +0000202void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000203 SmallString<128> Str;
204 raw_svector_ostream OS(Str);
Dan Gohmane51c0582015-10-06 00:27:55 +0000205
Dan Gohman754cd112015-11-11 01:33:02 +0000206 for (MVT VT : MF->getInfo<WebAssemblyFunctionInfo>()->getParams())
207 OS << "\t" ".param "
208 << toString(VT) << '\n';
209 for (MVT VT : MF->getInfo<WebAssemblyFunctionInfo>()->getResults())
210 OS << "\t" ".result "
211 << toString(VT) << '\n';
JF Bastienb6091df2015-08-25 22:58:05 +0000212
JF Bastien1d20a5e2015-10-16 00:53:49 +0000213 bool FirstVReg = true;
214 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
215 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
JF Bastien3428ed42015-10-17 00:25:38 +0000216 // FIXME: Don't skip dead virtual registers for now: that would require
217 // remapping all locals' numbers.
Dan Gohman754cd112015-11-11 01:33:02 +0000218 // if (!MRI->use_empty(VReg)) {
219 if (FirstVReg)
220 OS << "\t" ".local ";
221 else
222 OS << ", ";
223 OS << getRegTypeName(VReg);
224 FirstVReg = false;
JF Bastien3428ed42015-10-17 00:25:38 +0000225 //}
JF Bastien1d20a5e2015-10-16 00:53:49 +0000226 }
Dan Gohman754cd112015-11-11 01:33:02 +0000227 if (!FirstVReg)
228 OS << '\n';
JF Bastien1d20a5e2015-10-16 00:53:49 +0000229
Dan Gohman754cd112015-11-11 01:33:02 +0000230 // EmitRawText appends a newline, so strip off the last newline.
231 StringRef Text = OS.str();
232 if (!Text.empty())
233 OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000234 AsmPrinter::EmitFunctionBodyStart();
JF Bastienb6091df2015-08-25 22:58:05 +0000235}
236
JF Bastienb9073fb2015-07-22 21:28:15 +0000237void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000238 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000239 SmallString<128> Str;
240 raw_svector_ostream OS(Str);
241
JF Bastien600aee92015-07-31 17:53:38 +0000242 unsigned NumDefs = MI->getDesc().getNumDefs();
243 assert(NumDefs <= 1 &&
244 "Instructions with multiple result values not implemented");
245
Dan Gohman12e19972015-08-24 21:19:48 +0000246 OS << '\t';
247
Dan Gohmane51c0582015-10-06 00:27:55 +0000248 switch (MI->getOpcode()) {
249 case TargetOpcode::COPY:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000250 OS << "get_local push, " << regToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000251 break;
Dan Gohmane51c0582015-10-06 00:27:55 +0000252 case WebAssembly::ARGUMENT_I32:
253 case WebAssembly::ARGUMENT_I64:
254 case WebAssembly::ARGUMENT_F32:
255 case WebAssembly::ARGUMENT_F64:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000256 OS << "get_local push, " << argToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000257 break;
Dan Gohmane51c0582015-10-06 00:27:55 +0000258 default: {
259 OS << OpcodeName(TII, MI);
260 bool NeedComma = false;
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000261 bool DefsPushed = false;
262 if (NumDefs != 0 && !MI->isCall()) {
263 OS << " push";
264 NeedComma = true;
265 DefsPushed = true;
266 }
Dan Gohmane51c0582015-10-06 00:27:55 +0000267 for (const MachineOperand &MO : MI->uses()) {
268 if (MO.isReg() && MO.isImplicit())
269 continue;
270 if (NeedComma)
271 OS << ',';
272 NeedComma = true;
273 OS << ' ';
Dan Gohman4f52e002015-09-09 00:52:47 +0000274 switch (MO.getType()) {
275 default:
276 llvm_unreachable("unexpected machine operand type");
Dan Gohmane51c0582015-10-06 00:27:55 +0000277 case MachineOperand::MO_Register:
JF Bastien1d20a5e2015-10-16 00:53:49 +0000278 OS << "(get_local " << regToString(MO) << ')';
Dan Gohmane51c0582015-10-06 00:27:55 +0000279 break;
280 case MachineOperand::MO_Immediate:
281 OS << MO.getImm();
282 break;
283 case MachineOperand::MO_FPImmediate:
284 OS << toString(MO.getFPImm()->getValueAPF());
285 break;
286 case MachineOperand::MO_GlobalAddress:
287 OS << toSymbol(MO.getGlobal()->getName());
288 break;
289 case MachineOperand::MO_MachineBasicBlock:
290 OS << toSymbol(MO.getMBB()->getSymbol()->getName());
291 break;
Dan Gohman4f52e002015-09-09 00:52:47 +0000292 }
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000293 if (NumDefs != 0 && !DefsPushed) {
294 // Special-case for calls; print the push after the callee.
295 assert(MI->isCall());
296 OS << ", push";
297 DefsPushed = true;
298 }
Dan Gohmane51c0582015-10-06 00:27:55 +0000299 }
300 break;
301 }
Dan Gohman4f52e002015-09-09 00:52:47 +0000302 }
JF Bastien600aee92015-07-31 17:53:38 +0000303
JF Bastienb9073fb2015-07-22 21:28:15 +0000304 OutStreamer->EmitRawText(OS.str());
Dan Gohmane51c0582015-10-06 00:27:55 +0000305
306 if (NumDefs != 0) {
307 SmallString<128> Str;
308 raw_svector_ostream OS(Str);
JF Bastien1d20a5e2015-10-16 00:53:49 +0000309 const MachineOperand &Operand = MI->getOperand(0);
310 OS << "\tset_local " << regToString(Operand) << ", pop";
Dan Gohmane51c0582015-10-06 00:27:55 +0000311 OutStreamer->EmitRawText(OS.str());
312 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000313}
314
Dan Gohman754cd112015-11-11 01:33:02 +0000315static void ComputeLegalValueVTs(LLVMContext &Context,
316 const WebAssemblyTargetLowering &TLI,
317 const DataLayout &DL, Type *Ty,
318 SmallVectorImpl<MVT> &ValueVTs) {
319 SmallVector<EVT, 4> VTs;
320 ComputeValueVTs(TLI, DL, Ty, VTs);
321
322 for (EVT VT : VTs) {
323 unsigned NumRegs = TLI.getNumRegisters(Context, VT);
324 MVT RegisterVT = TLI.getRegisterType(Context, VT);
325 for (unsigned i = 0; i != NumRegs; ++i)
326 ValueVTs.push_back(RegisterVT);
327 }
328}
329
JF Bastien1a59c6b2015-10-21 02:23:09 +0000330void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
Dan Gohman754cd112015-11-11 01:33:02 +0000331 const DataLayout &DL = M.getDataLayout();
332
JF Bastien5789a692015-10-30 16:41:21 +0000333 SmallString<128> Str;
334 raw_svector_ostream OS(Str);
JF Bastien1a59c6b2015-10-21 02:23:09 +0000335 for (const Function &F : M)
336 if (F.isDeclarationForLinker()) {
337 assert(F.hasName() && "imported functions must have a name");
Dan Gohman754cd112015-11-11 01:33:02 +0000338 if (F.isIntrinsic())
JF Bastien5789a692015-10-30 16:41:21 +0000339 continue;
JF Bastien1a59c6b2015-10-21 02:23:09 +0000340 if (Str.empty())
JF Bastien5789a692015-10-30 16:41:21 +0000341 OS << "\t.imports\n";
Dan Gohman754cd112015-11-11 01:33:02 +0000342
JF Bastien5789a692015-10-30 16:41:21 +0000343 OS << "\t.import " << toSymbol(F.getName()) << " \"\" \"" << F.getName()
Dan Gohman754cd112015-11-11 01:33:02 +0000344 << "\"";
345
346 const WebAssemblyTargetLowering &TLI =
347 *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
348
349 // If we need to legalize the return type, it'll get converted into
350 // passing a pointer.
351 bool SawParam = false;
352 SmallVector<MVT, 4> ResultVTs;
353 ComputeLegalValueVTs(M.getContext(), TLI, DL, F.getReturnType(),
354 ResultVTs);
355 if (ResultVTs.size() > 1) {
356 ResultVTs.clear();
357 OS << " (param " << toString(TLI.getPointerTy(DL));
358 SawParam = true;
359 }
360
361 for (const Argument &A : F.args()) {
362 SmallVector<MVT, 4> ParamVTs;
363 ComputeLegalValueVTs(M.getContext(), TLI, DL, A.getType(), ParamVTs);
364 for (EVT VT : ParamVTs) {
365 if (!SawParam) {
366 OS << " (param";
367 SawParam = true;
368 }
369 OS << ' ' << toString(VT.getSimpleVT());
370 }
371 }
372 if (SawParam)
373 OS << ')';
374
375 for (EVT VT : ResultVTs)
376 OS << " (result " << toString(VT.getSimpleVT()) << ')';
377
JF Bastien1a59c6b2015-10-21 02:23:09 +0000378 OS << '\n';
JF Bastien5789a692015-10-30 16:41:21 +0000379 }
Dan Gohman754cd112015-11-11 01:33:02 +0000380
381 StringRef Text = OS.str();
382 if (!Text.empty())
383 OutStreamer->EmitRawText(Text.substr(0, Text.size() - 1));
JF Bastien1a59c6b2015-10-21 02:23:09 +0000384}
385
JF Bastienb9073fb2015-07-22 21:28:15 +0000386// Force static initialization.
387extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
388 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
389 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
390}