xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 // WebAssemblyMCInstLower.cpp - Convert WebAssembly MachineInstr to an MCInst //
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file contains code to lower WebAssembly MachineInstrs to their
11 /// corresponding MCInst records.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WebAssemblyMCInstLower.h"
16 #include "TargetInfo/WebAssemblyTargetInfo.h"
17 #include "Utils/WebAssemblyTypeUtilities.h"
18 #include "Utils/WebAssemblyUtilities.h"
19 #include "WebAssemblyAsmPrinter.h"
20 #include "WebAssemblyISelLowering.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSymbolWasm.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace llvm;
34 
35 // This disables the removal of registers when lowering into MC, as required
36 // by some current tests.
37 cl::opt<bool>
38     WasmKeepRegisters("wasm-keep-registers", cl::Hidden,
39                       cl::desc("WebAssembly: output stack registers in"
40                                " instruction output for test purposes only."),
41                       cl::init(false));
42 
43 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
44 
45 MCSymbol *
46 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
47   const GlobalValue *Global = MO.getGlobal();
48   if (!isa<Function>(Global)) {
49     auto *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
50     // If the symbol doesn't have an explicit WasmSymbolType yet and the
51     // GlobalValue is actually a WebAssembly global, then ensure the symbol is a
52     // WASM_SYMBOL_TYPE_GLOBAL.
53     if (WebAssembly::isWasmVarAddressSpace(Global->getAddressSpace()) &&
54         !WasmSym->getType()) {
55       const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
56       const TargetMachine &TM = MF.getTarget();
57       const Function &CurrentFunc = MF.getFunction();
58       Type *GlobalVT = Global->getValueType();
59       SmallVector<MVT, 1> VTs;
60       computeLegalValueVTs(CurrentFunc, TM, GlobalVT, VTs);
61 
62       // Tables are represented as Arrays in LLVM IR therefore
63       // they reach this point as aggregate Array types with an element type
64       // that is a reference type.
65       wasm::ValType Type;
66       bool IsTable = false;
67       if (GlobalVT->isArrayTy() &&
68           WebAssembly::isRefType(GlobalVT->getArrayElementType())) {
69         MVT VT;
70         IsTable = true;
71         switch (GlobalVT->getArrayElementType()->getPointerAddressSpace()) {
72         case WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF:
73           VT = MVT::funcref;
74           break;
75         case WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF:
76           VT = MVT::externref;
77           break;
78         default:
79           report_fatal_error("unhandled address space type");
80         }
81         Type = WebAssembly::toValType(VT);
82       } else if (VTs.size() == 1) {
83         Type = WebAssembly::toValType(VTs[0]);
84       } else
85         report_fatal_error("Aggregate globals not yet implemented");
86 
87       if (IsTable) {
88         WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
89         WasmSym->setTableType(Type);
90       } else {
91         WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
92         WasmSym->setGlobalType(
93             wasm::WasmGlobalType{uint8_t(Type), /*Mutable=*/true});
94       }
95     }
96     return WasmSym;
97   }
98 
99   const auto *FuncTy = cast<FunctionType>(Global->getValueType());
100   const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
101   const TargetMachine &TM = MF.getTarget();
102   const Function &CurrentFunc = MF.getFunction();
103 
104   SmallVector<MVT, 1> ResultMVTs;
105   SmallVector<MVT, 4> ParamMVTs;
106   const auto *const F = dyn_cast<Function>(Global);
107   computeSignatureVTs(FuncTy, F, CurrentFunc, TM, ParamMVTs, ResultMVTs);
108   auto Signature = signatureFromMVTs(ResultMVTs, ParamMVTs);
109 
110   bool InvokeDetected = false;
111   auto *WasmSym = Printer.getMCSymbolForFunction(
112       F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
113       Signature.get(), InvokeDetected);
114   WasmSym->setSignature(Signature.get());
115   Printer.addSignature(std::move(Signature));
116   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
117   return WasmSym;
118 }
119 
120 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
121     const MachineOperand &MO) const {
122   return Printer.getOrCreateWasmSymbol(MO.getSymbolName());
123 }
124 
125 MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand &MO,
126                                                      MCSymbol *Sym) const {
127   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
128   unsigned TargetFlags = MO.getTargetFlags();
129 
130   switch (TargetFlags) {
131     case WebAssemblyII::MO_NO_FLAG:
132       break;
133     case WebAssemblyII::MO_GOT_TLS:
134       Kind = MCSymbolRefExpr::VK_WASM_GOT_TLS;
135       break;
136     case WebAssemblyII::MO_GOT:
137       Kind = MCSymbolRefExpr::VK_GOT;
138       break;
139     case WebAssemblyII::MO_MEMORY_BASE_REL:
140       Kind = MCSymbolRefExpr::VK_WASM_MBREL;
141       break;
142     case WebAssemblyII::MO_TLS_BASE_REL:
143       Kind = MCSymbolRefExpr::VK_WASM_TLSREL;
144       break;
145     case WebAssemblyII::MO_TABLE_BASE_REL:
146       Kind = MCSymbolRefExpr::VK_WASM_TBREL;
147       break;
148     default:
149       llvm_unreachable("Unknown target flag on GV operand");
150   }
151 
152   const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Kind, Ctx);
153 
154   if (MO.getOffset() != 0) {
155     const auto *WasmSym = cast<MCSymbolWasm>(Sym);
156     if (TargetFlags == WebAssemblyII::MO_GOT)
157       report_fatal_error("GOT symbol references do not support offsets");
158     if (WasmSym->isFunction())
159       report_fatal_error("Function addresses with offsets not supported");
160     if (WasmSym->isGlobal())
161       report_fatal_error("Global indexes with offsets not supported");
162     if (WasmSym->isTag())
163       report_fatal_error("Tag indexes with offsets not supported");
164     if (WasmSym->isTable())
165       report_fatal_error("Table indexes with offsets not supported");
166 
167     Expr = MCBinaryExpr::createAdd(
168         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
169   }
170 
171   return MCOperand::createExpr(Expr);
172 }
173 
174 MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand(
175     SmallVector<wasm::ValType, 1> &&Returns,
176     SmallVector<wasm::ValType, 4> &&Params) const {
177   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
178                                                          std::move(Params));
179   MCSymbol *Sym = Printer.createTempSymbol("typeindex");
180   auto *WasmSym = cast<MCSymbolWasm>(Sym);
181   WasmSym->setSignature(Signature.get());
182   Printer.addSignature(std::move(Signature));
183   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
184   const MCExpr *Expr =
185       MCSymbolRefExpr::create(WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
186   return MCOperand::createExpr(Expr);
187 }
188 
189 // Return the WebAssembly type associated with the given register class.
190 static wasm::ValType getType(const TargetRegisterClass *RC) {
191   if (RC == &WebAssembly::I32RegClass)
192     return wasm::ValType::I32;
193   if (RC == &WebAssembly::I64RegClass)
194     return wasm::ValType::I64;
195   if (RC == &WebAssembly::F32RegClass)
196     return wasm::ValType::F32;
197   if (RC == &WebAssembly::F64RegClass)
198     return wasm::ValType::F64;
199   if (RC == &WebAssembly::V128RegClass)
200     return wasm::ValType::V128;
201   if (RC == &WebAssembly::EXTERNREFRegClass)
202     return wasm::ValType::EXTERNREF;
203   if (RC == &WebAssembly::FUNCREFRegClass)
204     return wasm::ValType::FUNCREF;
205   llvm_unreachable("Unexpected register class");
206 }
207 
208 static void getFunctionReturns(const MachineInstr *MI,
209                                SmallVectorImpl<wasm::ValType> &Returns) {
210   const Function &F = MI->getMF()->getFunction();
211   const TargetMachine &TM = MI->getMF()->getTarget();
212   Type *RetTy = F.getReturnType();
213   SmallVector<MVT, 4> CallerRetTys;
214   computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
215   valTypesFromMVTs(CallerRetTys, Returns);
216 }
217 
218 void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
219                                    MCInst &OutMI) const {
220   OutMI.setOpcode(MI->getOpcode());
221 
222   const MCInstrDesc &Desc = MI->getDesc();
223   unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
224   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
225     const MachineOperand &MO = MI->getOperand(I);
226 
227     MCOperand MCOp;
228     switch (MO.getType()) {
229     default:
230       MI->print(errs());
231       llvm_unreachable("unknown operand type");
232     case MachineOperand::MO_MachineBasicBlock:
233       MI->print(errs());
234       llvm_unreachable("MachineBasicBlock operand should have been rewritten");
235     case MachineOperand::MO_Register: {
236       // Ignore all implicit register operands.
237       if (MO.isImplicit())
238         continue;
239       const WebAssemblyFunctionInfo &MFI =
240           *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
241       unsigned WAReg = MFI.getWAReg(MO.getReg());
242       MCOp = MCOperand::createReg(WAReg);
243       break;
244     }
245     case MachineOperand::MO_Immediate: {
246       unsigned DescIndex = I - NumVariadicDefs;
247       if (DescIndex < Desc.NumOperands) {
248         const MCOperandInfo &Info = Desc.OpInfo[DescIndex];
249         if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
250           SmallVector<wasm::ValType, 4> Returns;
251           SmallVector<wasm::ValType, 4> Params;
252 
253           const MachineRegisterInfo &MRI =
254               MI->getParent()->getParent()->getRegInfo();
255           for (const MachineOperand &MO : MI->defs())
256             Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
257           for (const MachineOperand &MO : MI->explicit_uses())
258             if (MO.isReg())
259               Params.push_back(getType(MRI.getRegClass(MO.getReg())));
260 
261           // call_indirect instructions have a callee operand at the end which
262           // doesn't count as a param.
263           if (WebAssembly::isCallIndirect(MI->getOpcode()))
264             Params.pop_back();
265 
266           // return_call_indirect instructions have the return type of the
267           // caller
268           if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
269             getFunctionReturns(MI, Returns);
270 
271           MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
272           break;
273         } else if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
274           auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
275           assert(BT != WebAssembly::BlockType::Invalid);
276           if (BT == WebAssembly::BlockType::Multivalue) {
277             SmallVector<wasm::ValType, 1> Returns;
278             getFunctionReturns(MI, Returns);
279             MCOp = lowerTypeIndexOperand(std::move(Returns),
280                                          SmallVector<wasm::ValType, 4>());
281             break;
282           }
283         }
284       }
285       MCOp = MCOperand::createImm(MO.getImm());
286       break;
287     }
288     case MachineOperand::MO_FPImmediate: {
289       const ConstantFP *Imm = MO.getFPImm();
290       const uint64_t BitPattern =
291           Imm->getValueAPF().bitcastToAPInt().getZExtValue();
292       if (Imm->getType()->isFloatTy())
293         MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern));
294       else if (Imm->getType()->isDoubleTy())
295         MCOp = MCOperand::createDFPImm(BitPattern);
296       else
297         llvm_unreachable("unknown floating point immediate type");
298       break;
299     }
300     case MachineOperand::MO_GlobalAddress:
301       MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
302       break;
303     case MachineOperand::MO_ExternalSymbol:
304       MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
305       break;
306     case MachineOperand::MO_MCSymbol:
307       assert(MO.getTargetFlags() == 0 &&
308              "WebAssembly does not use target flags on MCSymbol");
309       MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
310       break;
311     }
312 
313     OutMI.addOperand(MCOp);
314   }
315 
316   if (!WasmKeepRegisters)
317     removeRegisterOperands(MI, OutMI);
318   else if (Desc.variadicOpsAreDefs())
319     OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
320 }
321 
322 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
323   // Remove all uses of stackified registers to bring the instruction format
324   // into its final stack form used thruout MC, and transition opcodes to
325   // their _S variant.
326   // We do this separate from the above code that still may need these
327   // registers for e.g. call_indirect signatures.
328   // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
329   // details.
330   // TODO: the code above creates new registers which are then removed here.
331   // That code could be slightly simplified by not doing that, though maybe
332   // it is simpler conceptually to keep the code above in "register mode"
333   // until this transition point.
334   // FIXME: we are not processing inline assembly, which contains register
335   // operands, because it is used by later target generic code.
336   if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
337     return;
338 
339   // Transform to _S instruction.
340   auto RegOpcode = OutMI.getOpcode();
341   auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
342   assert(StackOpcode != -1 && "Failed to stackify instruction");
343   OutMI.setOpcode(StackOpcode);
344 
345   // Remove register operands.
346   for (auto I = OutMI.getNumOperands(); I; --I) {
347     auto &MO = OutMI.getOperand(I - 1);
348     if (MO.isReg()) {
349       OutMI.erase(&MO);
350     }
351   }
352 }
353