6803319fe2887ff4ae32a98d883a5ea7ae1427a6
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyAsmPrinter.cpp
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 /// \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 "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"
37 using namespace llvm;
38
39 #define DEBUG_TYPE "asm-printer"
40
41 namespace {
42
43 class WebAssemblyAsmPrinter final : public AsmPrinter {
44   const MachineRegisterInfo *MRI;
45   const WebAssemblyFunctionInfo *MFI;
46
47 public:
48   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
49       : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {}
50
51 private:
52   const char *getPassName() const override {
53     return "WebAssembly Assembly Printer";
54   }
55
56   //===------------------------------------------------------------------===//
57   // MachineFunctionPass Implementation.
58   //===------------------------------------------------------------------===//
59
60   bool runOnMachineFunction(MachineFunction &MF) override {
61     MRI = &MF.getRegInfo();
62     MFI = MF.getInfo<WebAssemblyFunctionInfo>();
63     return AsmPrinter::runOnMachineFunction(MF);
64   }
65
66   //===------------------------------------------------------------------===//
67   // AsmPrinter Implementation.
68   //===------------------------------------------------------------------===//
69
70   void EmitJumpTableInfo() override;
71   void EmitConstantPool() override;
72   void EmitFunctionBodyStart() override;
73   void EmitInstruction(const MachineInstr *MI) override;
74   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
75                        unsigned AsmVariant, const char *ExtraCode,
76                        raw_ostream &OS) override;
77   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
78                              unsigned AsmVariant, const char *ExtraCode,
79                              raw_ostream &OS) override;
80
81   MVT getRegType(unsigned RegNo) const;
82   const char *toString(MVT VT) const;
83   std::string regToString(const MachineOperand &MO);
84 };
85
86 } // end anonymous namespace
87
88 //===----------------------------------------------------------------------===//
89 // Helpers.
90 //===----------------------------------------------------------------------===//
91
92 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
93   const TargetRegisterClass *TRC =
94       TargetRegisterInfo::isVirtualRegister(RegNo) ?
95       MRI->getRegClass(RegNo) :
96       MRI->getTargetRegisterInfo()->getMinimalPhysRegClass(RegNo);
97   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
98     if (TRC->hasType(T))
99       return T;
100   DEBUG(errs() << "Unknown type for register number: " << RegNo);
101   llvm_unreachable("Unknown register type");
102   return MVT::Other;
103 }
104
105 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
106   unsigned RegNo = MO.getReg();
107   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
108          "Unlowered physical register encountered during assembly printing");
109   assert(!MFI->isVRegStackified(RegNo));
110   unsigned WAReg = MFI->getWAReg(RegNo);
111   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
112   return '$' + utostr(WAReg);
113 }
114
115 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
116   return WebAssembly::TypeToString(VT);
117 }
118
119 //===----------------------------------------------------------------------===//
120 // WebAssemblyAsmPrinter Implementation.
121 //===----------------------------------------------------------------------===//
122
123 void WebAssemblyAsmPrinter::EmitConstantPool() {
124   assert(MF->getConstantPool()->getConstants().empty() &&
125          "WebAssembly disables constant pools");
126 }
127
128 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
129   // Nothing to do; jump tables are incorporated into the instruction stream.
130 }
131
132 static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM,
133                                  Type *Ty, SmallVectorImpl<MVT> &ValueVTs) {
134   const DataLayout &DL(F.getParent()->getDataLayout());
135   const WebAssemblyTargetLowering &TLI =
136       *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
137   SmallVector<EVT, 4> VTs;
138   ComputeValueVTs(TLI, DL, Ty, VTs);
139
140   for (EVT VT : VTs) {
141     unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT);
142     MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT);
143     for (unsigned i = 0; i != NumRegs; ++i)
144       ValueVTs.push_back(RegisterVT);
145   }
146 }
147
148 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
149   if (!MFI->getParams().empty()) {
150     MCInst Param;
151     Param.setOpcode(WebAssembly::PARAM);
152     for (MVT VT : MFI->getParams())
153       Param.addOperand(MCOperand::createImm(VT.SimpleTy));
154     EmitToStreamer(*OutStreamer, Param);
155   }
156
157   SmallVector<MVT, 4> ResultVTs;
158   const Function &F(*MF->getFunction());
159   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
160   // If the return type needs to be legalized it will get converted into
161   // passing a pointer.
162   if (ResultVTs.size() == 1) {
163     MCInst Result;
164     Result.setOpcode(WebAssembly::RESULT);
165     Result.addOperand(MCOperand::createImm(ResultVTs.front().SimpleTy));
166     EmitToStreamer(*OutStreamer, Result);
167   }
168
169   bool AnyWARegs = false;
170   MCInst Local;
171   Local.setOpcode(WebAssembly::LOCAL);
172   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
173     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
174     unsigned WAReg = MFI->getWAReg(VReg);
175     // Don't declare unused registers.
176     if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
177       continue;
178     // Don't redeclare parameters.
179     if (WAReg < MFI->getParams().size())
180       continue;
181     // Don't declare stackified registers.
182     if (int(WAReg) < 0)
183       continue;
184     Local.addOperand(MCOperand::createImm(getRegType(VReg).SimpleTy));
185     AnyWARegs = true;
186   }
187   auto &PhysRegs = MFI->getPhysRegs();
188   for (unsigned PReg = 0; PReg < PhysRegs.size(); ++PReg) {
189     if (PhysRegs[PReg] == -1U)
190       continue;
191     Local.addOperand(MCOperand::createImm(getRegType(PReg).SimpleTy));
192     AnyWARegs = true;
193   }
194   if (AnyWARegs)
195     EmitToStreamer(*OutStreamer, Local);
196
197   AsmPrinter::EmitFunctionBodyStart();
198 }
199
200 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
201   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
202
203   switch (MI->getOpcode()) {
204   case WebAssembly::ARGUMENT_I32:
205   case WebAssembly::ARGUMENT_I64:
206   case WebAssembly::ARGUMENT_F32:
207   case WebAssembly::ARGUMENT_F64:
208     // These represent values which are live into the function entry, so there's
209     // no instruction to emit.
210     break;
211   case WebAssembly::LOOP_END:
212     // This is a no-op which just exists to tell AsmPrinter.cpp that there's a
213     // fallthrough which nevertheless requires a label for the destination here.
214     break;
215   default: {
216     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
217     MCInst TmpInst;
218     MCInstLowering.Lower(MI, TmpInst);
219     EmitToStreamer(*OutStreamer, TmpInst);
220     break;
221   }
222   }
223 }
224
225 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
226                                             unsigned OpNo, unsigned AsmVariant,
227                                             const char *ExtraCode,
228                                             raw_ostream &OS) {
229   if (AsmVariant != 0)
230     report_fatal_error("There are no defined alternate asm variants");
231
232   // First try the generic code, which knows about modifiers like 'c' and 'n'.
233   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
234     return false;
235
236   if (!ExtraCode) {
237     const MachineOperand &MO = MI->getOperand(OpNo);
238     switch (MO.getType()) {
239     case MachineOperand::MO_Immediate:
240       OS << MO.getImm();
241       return false;
242     case MachineOperand::MO_Register:
243       OS << regToString(MO);
244       return false;
245     case MachineOperand::MO_GlobalAddress:
246       getSymbol(MO.getGlobal())->print(OS, MAI);
247       printOffset(MO.getOffset(), OS);
248       return false;
249     case MachineOperand::MO_ExternalSymbol:
250       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
251       printOffset(MO.getOffset(), OS);
252       return false;
253     case MachineOperand::MO_MachineBasicBlock:
254       MO.getMBB()->getSymbol()->print(OS, MAI);
255       return false;
256     default:
257       break;
258     }
259   }
260
261   return true;
262 }
263
264 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
265                                                   unsigned OpNo,
266                                                   unsigned AsmVariant,
267                                                   const char *ExtraCode,
268                                                   raw_ostream &OS) {
269   if (AsmVariant != 0)
270     report_fatal_error("There are no defined alternate asm variants");
271
272   if (!ExtraCode) {
273     // TODO: For now, we just hard-code 0 as the constant offset; teach
274     // SelectInlineAsmMemoryOperand how to do address mode matching.
275     OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
276     return false;
277   }
278
279   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
280 }
281
282 // Force static initialization.
283 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
284   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
285   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
286 }