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