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