1 // WebAssemblyMCInstLower.cpp - Convert WebAssembly MachineInstr to an MCInst //
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 /// This file contains code to lower WebAssembly MachineInstrs to their
12 /// corresponding MCInst records.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "WebAssemblyMCInstLower.h"
17 #include "WebAssemblyAsmPrinter.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyRuntimeLibcallSignatures.h"
20 #include "WebAssemblyUtilities.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCSymbolWasm.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
32 
33 // Defines llvm::WebAssembly::getStackOpcode to convert register instructions to
34 // stack instructions
35 #define GET_INSTRMAP_INFO 1
36 #include "WebAssemblyGenInstrInfo.inc"
37 
38 // This disables the removal of registers when lowering into MC, as required
39 // by some current tests.
40 static cl::opt<bool>
41     WasmKeepRegisters("wasm-keep-registers", cl::Hidden,
42                       cl::desc("WebAssembly: output stack registers in"
43                                " instruction output for test purposes only."),
44                       cl::init(false));
45 
46 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
47 
48 MCSymbol *
49 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
50   const GlobalValue *Global = MO.getGlobal();
51   MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
52 
53   if (const auto *FuncTy = dyn_cast<FunctionType>(Global->getValueType())) {
54     const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
55     const TargetMachine &TM = MF.getTarget();
56     const Function &CurrentFunc = MF.getFunction();
57 
58     SmallVector<MVT, 1> ResultMVTs;
59     SmallVector<MVT, 4> ParamMVTs;
60     ComputeSignatureVTs(FuncTy, CurrentFunc, TM, ParamMVTs, ResultMVTs);
61 
62     auto Signature = SignatureFromMVTs(ResultMVTs, ParamMVTs);
63     WasmSym->setSignature(Signature.get());
64     Printer.addSignature(std::move(Signature));
65     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
66   }
67 
68   return WasmSym;
69 }
70 
71 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
72     const MachineOperand &MO) const {
73   const char *Name = MO.getSymbolName();
74   MCSymbolWasm *WasmSym =
75       cast<MCSymbolWasm>(Printer.GetExternalSymbolSymbol(Name));
76   const WebAssemblySubtarget &Subtarget = Printer.getSubtarget();
77 
78   // __stack_pointer is a global variable; all other external symbols used by
79   // CodeGen are functions.  It's OK to hardcode knowledge of specific symbols
80   // here; this method is precisely there for fetching the signatures of known
81   // Clang-provided symbols.
82   if (strcmp(Name, "__stack_pointer") == 0) {
83     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
84     WasmSym->setGlobalType(wasm::WasmGlobalType{
85         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
86                                       : wasm::WASM_TYPE_I32),
87         true});
88     return WasmSym;
89   }
90 
91   SmallVector<wasm::ValType, 4> Returns;
92   SmallVector<wasm::ValType, 4> Params;
93   GetLibcallSignature(Subtarget, Name, Returns, Params);
94   auto Signature =
95       make_unique<wasm::WasmSignature>(std::move(Returns), std::move(Params));
96   WasmSym->setSignature(Signature.get());
97   Printer.addSignature(std::move(Signature));
98   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
99 
100   return WasmSym;
101 }
102 
103 MCOperand WebAssemblyMCInstLower::LowerSymbolOperand(MCSymbol *Sym,
104                                                      int64_t Offset,
105                                                      bool IsFunc,
106                                                      bool IsGlob) const {
107   MCSymbolRefExpr::VariantKind VK =
108       IsFunc ? MCSymbolRefExpr::VK_WebAssembly_FUNCTION
109              : IsGlob ? MCSymbolRefExpr::VK_WebAssembly_GLOBAL
110                       : MCSymbolRefExpr::VK_None;
111 
112   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, VK, Ctx);
113 
114   if (Offset != 0) {
115     if (IsFunc)
116       report_fatal_error("Function addresses with offsets not supported");
117     if (IsGlob)
118       report_fatal_error("Global indexes with offsets not supported");
119     Expr =
120         MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(Offset, Ctx), Ctx);
121   }
122 
123   return MCOperand::createExpr(Expr);
124 }
125 
126 // Return the WebAssembly type associated with the given register class.
127 static wasm::ValType getType(const TargetRegisterClass *RC) {
128   if (RC == &WebAssembly::I32RegClass)
129     return wasm::ValType::I32;
130   if (RC == &WebAssembly::I64RegClass)
131     return wasm::ValType::I64;
132   if (RC == &WebAssembly::F32RegClass)
133     return wasm::ValType::F32;
134   if (RC == &WebAssembly::F64RegClass)
135     return wasm::ValType::F64;
136   if (RC == &WebAssembly::V128RegClass)
137     return wasm::ValType::V128;
138   llvm_unreachable("Unexpected register class");
139 }
140 
141 void WebAssemblyMCInstLower::Lower(const MachineInstr *MI,
142                                    MCInst &OutMI) const {
143   OutMI.setOpcode(MI->getOpcode());
144 
145   const MCInstrDesc &Desc = MI->getDesc();
146   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
147     const MachineOperand &MO = MI->getOperand(i);
148 
149     MCOperand MCOp;
150     switch (MO.getType()) {
151     default:
152       MI->print(errs());
153       llvm_unreachable("unknown operand type");
154     case MachineOperand::MO_MachineBasicBlock:
155       MI->print(errs());
156       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
157     case MachineOperand::MO_Register: {
158       // Ignore all implicit register operands.
159       if (MO.isImplicit())
160         continue;
161       const WebAssemblyFunctionInfo &MFI =
162           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
163       unsigned WAReg = MFI.getWAReg(MO.getReg());
164       MCOp = MCOperand::createReg(WAReg);
165       break;
166     }
167     case MachineOperand::MO_Immediate:
168       if (i < Desc.NumOperands) {
169         const MCOperandInfo &Info = Desc.OpInfo[i];
170         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
171           MCSymbol *Sym = Printer.createTempSymbol("typeindex");
172 
173           SmallVector<wasm::ValType, 4> Returns;
174           SmallVector<wasm::ValType, 4> Params;
175 
176           const MachineRegisterInfo &MRI =
177               MI->getParent()->getParent()->getRegInfo();
178           for (const MachineOperand &MO : MI->defs())
179             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
180           for (const MachineOperand &MO : MI->explicit_uses())
181             if (MO.isReg())
182               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
183 
184           // call_indirect instructions have a callee operand at the end which
185           // doesn't count as a param.
186           if (WebAssembly::isCallIndirect(*MI))
187             Params.pop_back();
188 
189           MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Sym);
190           auto Signature = make_unique<wasm::WasmSignature>(std::move(Returns),
191                                                             std::move(Params));
192           WasmSym->setSignature(Signature.get());
193           Printer.addSignature(std::move(Signature));
194           WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
195 
196           const MCExpr *Expr = MCSymbolRefExpr::create(
197               WasmSym, MCSymbolRefExpr::VK_WebAssembly_TYPEINDEX, Ctx);
198           MCOp = MCOperand::createExpr(Expr);
199           break;
200         }
201       }
202       MCOp = MCOperand::createImm(MO.getImm());
203       break;
204     case MachineOperand::MO_FPImmediate: {
205       // TODO: MC converts all floating point immediate operands to double.
206       // This is fine for numeric values, but may cause NaNs to change bits.
207       const ConstantFP *Imm = MO.getFPImm();
208       if (Imm->getType()->isFloatTy())
209         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToFloat());
210       else if (Imm->getType()->isDoubleTy())
211         MCOp = MCOperand::createFPImm(Imm->getValueAPF().convertToDouble());
212       else
213         llvm_unreachable("unknown floating point immediate type");
214       break;
215     }
216     case MachineOperand::MO_GlobalAddress:
217       assert(MO.getTargetFlags() == WebAssemblyII::MO_NO_FLAG &&
218              "WebAssembly does not use target flags on GlobalAddresses");
219       MCOp = LowerSymbolOperand(GetGlobalAddressSymbol(MO), MO.getOffset(),
220                                 MO.getGlobal()->getValueType()->isFunctionTy(),
221                                 false);
222       break;
223     case MachineOperand::MO_ExternalSymbol:
224       // The target flag indicates whether this is a symbol for a
225       // variable or a function.
226       assert((MO.getTargetFlags() & ~WebAssemblyII::MO_SYMBOL_MASK) == 0 &&
227              "WebAssembly uses only symbol flags on ExternalSymbols");
228       MCOp = LowerSymbolOperand(
229           GetExternalSymbolSymbol(MO), /*Offset=*/0,
230           (MO.getTargetFlags() & WebAssemblyII::MO_SYMBOL_FUNCTION) != 0,
231           (MO.getTargetFlags() & WebAssemblyII::MO_SYMBOL_GLOBAL) != 0);
232       break;
233     case MachineOperand::MO_MCSymbol:
234       // This is currently used only for LSDA symbols (GCC_except_table),
235       // because global addresses or other external symbols are handled above.
236       assert(MO.getTargetFlags() == 0 &&
237              "WebAssembly does not use target flags on MCSymbol");
238       MCOp = LowerSymbolOperand(MO.getMCSymbol(), /*Offset=*/0, false, false);
239       break;
240     }
241 
242     OutMI.addOperand(MCOp);
243   }
244 
245   if (!WasmKeepRegisters)
246     removeRegisterOperands(MI, OutMI);
247 }
248 
249 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
250   // Remove all uses of stackified registers to bring the instruction format
251   // into its final stack form used thruout MC, and transition opcodes to
252   // their _S variant.
253   // We do this seperate from the above code that still may need these
254   // registers for e.g. call_indirect signatures.
255   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
256   // details.
257   // TODO: the code above creates new registers which are then removed here.
258   // That code could be slightly simplified by not doing that, though maybe
259   // it is simpler conceptually to keep the code above in "register mode"
260   // until this transition point.
261   // FIXME: we are not processing inline assembly, which contains register
262   // operands, because it is used by later target generic code.
263   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
264     return;
265 
266   // Transform to _S instruction.
267   auto RegOpcode = OutMI.getOpcode();
268   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
269   assert(StackOpcode != -1 && "Failed to stackify instruction");
270   OutMI.setOpcode(StackOpcode);
271 
272   // Remove register operands.
273   for (auto I = OutMI.getNumOperands(); I; --I) {
274     auto &MO = OutMI.getOperand(I - 1);
275     if (MO.isReg()) {
276       OutMI.erase(&MO);
277     }
278   }
279 }
280