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