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 "MCTargetDesc/WebAssemblyTargetStreamer.h"
21 #include "WebAssemblyMCInstLower.h"
22 #include "WebAssemblyMachineFunctionInfo.h"
23 #include "WebAssemblyRegisterInfo.h"
24 #include "WebAssemblySubtarget.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 EmitFunctionBodyEnd() override;
74   void EmitInstruction(const MachineInstr *MI) override;
75   const MCExpr *lowerConstant(const Constant *CV) override;
76   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
77                        unsigned AsmVariant, const char *ExtraCode,
78                        raw_ostream &OS) override;
79   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
80                              unsigned AsmVariant, const char *ExtraCode,
81                              raw_ostream &OS) override;
82 
83   MVT getRegType(unsigned RegNo) const;
84   const char *toString(MVT VT) const;
85   std::string regToString(const MachineOperand &MO);
86   WebAssemblyTargetStreamer *getTargetStreamer();
87 };
88 
89 } // end anonymous namespace
90 
91 //===----------------------------------------------------------------------===//
92 // Helpers.
93 //===----------------------------------------------------------------------===//
94 
95 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
96   const TargetRegisterClass *TRC = MRI->getRegClass(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 const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
106   return WebAssembly::TypeToString(VT);
107 }
108 
109 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
110   unsigned RegNo = MO.getReg();
111   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
112          "Unlowered physical register encountered during assembly printing");
113   assert(!MFI->isVRegStackified(RegNo));
114   unsigned WAReg = MFI->getWAReg(RegNo);
115   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
116   return '$' + utostr(WAReg);
117 }
118 
119 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
120   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
121   return static_cast<WebAssemblyTargetStreamer *>(TS);
122 }
123 
124 //===----------------------------------------------------------------------===//
125 // WebAssemblyAsmPrinter Implementation.
126 //===----------------------------------------------------------------------===//
127 
128 void WebAssemblyAsmPrinter::EmitConstantPool() {
129   assert(MF->getConstantPool()->getConstants().empty() &&
130          "WebAssembly disables constant pools");
131 }
132 
133 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
134   // Nothing to do; jump tables are incorporated into the instruction stream.
135 }
136 
137 static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM,
138                                  Type *Ty, SmallVectorImpl<MVT> &ValueVTs) {
139   const DataLayout &DL(F.getParent()->getDataLayout());
140   const WebAssemblyTargetLowering &TLI =
141       *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
142   SmallVector<EVT, 4> VTs;
143   ComputeValueVTs(TLI, DL, Ty, VTs);
144 
145   for (EVT VT : VTs) {
146     unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT);
147     MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT);
148     for (unsigned i = 0; i != NumRegs; ++i)
149       ValueVTs.push_back(RegisterVT);
150   }
151 }
152 
153 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
154   if (!MFI->getParams().empty())
155     getTargetStreamer()->emitParam(MFI->getParams());
156 
157   SmallVector<MVT, 4> ResultVTs;
158   const Function &F(*MF->getFunction());
159   ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
160 
161   // If the return type needs to be legalized it will get converted into
162   // passing a pointer.
163   if (ResultVTs.size() == 1)
164     getTargetStreamer()->emitResult(ResultVTs);
165 
166   bool AnyWARegs = false;
167   SmallVector<MVT, 16> LocalTypes;
168   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
169     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
170     unsigned WAReg = MFI->getWAReg(VReg);
171     // Don't declare unused registers.
172     if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
173       continue;
174     // Don't redeclare parameters.
175     if (WAReg < MFI->getParams().size())
176       continue;
177     // Don't declare stackified registers.
178     if (int(WAReg) < 0)
179       continue;
180     LocalTypes.push_back(getRegType(VReg));
181     AnyWARegs = true;
182   }
183   if (AnyWARegs)
184     getTargetStreamer()->emitLocal(LocalTypes);
185 
186   AsmPrinter::EmitFunctionBodyStart();
187 }
188 
189 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
190   getTargetStreamer()->emitEndFunc();
191 }
192 
193 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
194   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
195 
196   switch (MI->getOpcode()) {
197   case WebAssembly::ARGUMENT_I32:
198   case WebAssembly::ARGUMENT_I64:
199   case WebAssembly::ARGUMENT_F32:
200   case WebAssembly::ARGUMENT_F64:
201     // These represent values which are live into the function entry, so there's
202     // no instruction to emit.
203     break;
204   case WebAssembly::FALLTHROUGH_RETURN_I32:
205   case WebAssembly::FALLTHROUGH_RETURN_I64:
206   case WebAssembly::FALLTHROUGH_RETURN_F32:
207   case WebAssembly::FALLTHROUGH_RETURN_F64: {
208     // These instructions represent the implicit return at the end of a
209     // function body. The operand is always a pop.
210     assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
211 
212     if (isVerbose()) {
213       OutStreamer->AddComment("fallthrough-return: $pop" +
214                               utostr(MFI->getWARegStackId(
215                                   MFI->getWAReg(MI->getOperand(0).getReg()))));
216       OutStreamer->AddBlankLine();
217     }
218     break;
219   }
220   case WebAssembly::FALLTHROUGH_RETURN_VOID:
221     // This instruction represents the implicit return at the end of a
222     // function body with no return value.
223     if (isVerbose()) {
224       OutStreamer->AddComment("fallthrough-return");
225       OutStreamer->AddBlankLine();
226     }
227     break;
228   default: {
229     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
230     MCInst TmpInst;
231     MCInstLowering.Lower(MI, TmpInst);
232     EmitToStreamer(*OutStreamer, TmpInst);
233     break;
234   }
235   }
236 }
237 
238 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
239   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
240     if (GV->getValueType()->isFunctionTy())
241       return MCSymbolRefExpr::create(
242           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
243   return AsmPrinter::lowerConstant(CV);
244 }
245 
246 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
247                                             unsigned OpNo, unsigned AsmVariant,
248                                             const char *ExtraCode,
249                                             raw_ostream &OS) {
250   if (AsmVariant != 0)
251     report_fatal_error("There are no defined alternate asm variants");
252 
253   // First try the generic code, which knows about modifiers like 'c' and 'n'.
254   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
255     return false;
256 
257   if (!ExtraCode) {
258     const MachineOperand &MO = MI->getOperand(OpNo);
259     switch (MO.getType()) {
260     case MachineOperand::MO_Immediate:
261       OS << MO.getImm();
262       return false;
263     case MachineOperand::MO_Register:
264       OS << regToString(MO);
265       return false;
266     case MachineOperand::MO_GlobalAddress:
267       getSymbol(MO.getGlobal())->print(OS, MAI);
268       printOffset(MO.getOffset(), OS);
269       return false;
270     case MachineOperand::MO_ExternalSymbol:
271       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
272       printOffset(MO.getOffset(), OS);
273       return false;
274     case MachineOperand::MO_MachineBasicBlock:
275       MO.getMBB()->getSymbol()->print(OS, MAI);
276       return false;
277     default:
278       break;
279     }
280   }
281 
282   return true;
283 }
284 
285 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
286                                                   unsigned OpNo,
287                                                   unsigned AsmVariant,
288                                                   const char *ExtraCode,
289                                                   raw_ostream &OS) {
290   if (AsmVariant != 0)
291     report_fatal_error("There are no defined alternate asm variants");
292 
293   if (!ExtraCode) {
294     // TODO: For now, we just hard-code 0 as the constant offset; teach
295     // SelectInlineAsmMemoryOperand how to do address mode matching.
296     OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
297     return false;
298   }
299 
300   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
301 }
302 
303 // Force static initialization.
304 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
305   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
306   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
307 }
308