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 "Utils/WebAssemblyTypeUtilities.h" 19 #include "WebAssemblyAsmPrinter.h" 20 #include "WebAssemblyISelLowering.h" 21 #include "WebAssemblyMachineFunctionInfo.h" 22 #include "WebAssemblyUtilities.h" 23 #include "llvm/CodeGen/AsmPrinter.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCContext.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/MC/MCInst.h" 30 #include "llvm/MC/MCSymbolWasm.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/raw_ostream.h" 33 34 using namespace llvm; 35 36 // This disables the removal of registers when lowering into MC, as required 37 // by some current tests. 38 cl::opt<bool> 39 WasmKeepRegisters("wasm-keep-registers", cl::Hidden, 40 cl::desc("WebAssembly: output stack registers in" 41 " instruction output for test purposes only."), 42 cl::init(false)); 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 auto *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global)); 51 // If the symbol doesn't have an explicit WasmSymbolType yet and the 52 // GlobalValue is actually a WebAssembly global, then ensure the symbol is a 53 // WASM_SYMBOL_TYPE_GLOBAL. 54 if (WebAssembly::isWasmVarAddressSpace(Global->getAddressSpace()) && 55 !WasmSym->getType()) { 56 const MachineFunction &MF = *MO.getParent()->getParent()->getParent(); 57 const TargetMachine &TM = MF.getTarget(); 58 const Function &CurrentFunc = MF.getFunction(); 59 Type *GlobalVT = Global->getValueType(); 60 SmallVector<MVT, 1> VTs; 61 computeLegalValueVTs(CurrentFunc, TM, GlobalVT, VTs); 62 63 WebAssembly::wasmSymbolSetType(WasmSym, GlobalVT, VTs); 64 } 65 return WasmSym; 66 } 67 68 const auto *FuncTy = cast<FunctionType>(Global->getValueType()); 69 const MachineFunction &MF = *MO.getParent()->getParent()->getParent(); 70 const TargetMachine &TM = MF.getTarget(); 71 const Function &CurrentFunc = MF.getFunction(); 72 73 SmallVector<MVT, 1> ResultMVTs; 74 SmallVector<MVT, 4> ParamMVTs; 75 const auto *const F = dyn_cast<Function>(Global); 76 computeSignatureVTs(FuncTy, F, CurrentFunc, TM, ParamMVTs, ResultMVTs); 77 auto Signature = signatureFromMVTs(Ctx, ResultMVTs, ParamMVTs); 78 79 bool InvokeDetected = false; 80 auto *WasmSym = Printer.getMCSymbolForFunction( 81 F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj, 82 Signature, InvokeDetected); 83 WasmSym->setSignature(Signature); 84 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 85 return WasmSym; 86 } 87 88 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol( 89 const MachineOperand &MO) const { 90 return Printer.getOrCreateWasmSymbol(MO.getSymbolName()); 91 } 92 93 MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand &MO, 94 MCSymbol *Sym) const { 95 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None; 96 unsigned TargetFlags = MO.getTargetFlags(); 97 98 switch (TargetFlags) { 99 case WebAssemblyII::MO_NO_FLAG: 100 break; 101 case WebAssemblyII::MO_GOT_TLS: 102 Kind = MCSymbolRefExpr::VK_WASM_GOT_TLS; 103 break; 104 case WebAssemblyII::MO_GOT: 105 Kind = MCSymbolRefExpr::VK_GOT; 106 break; 107 case WebAssemblyII::MO_MEMORY_BASE_REL: 108 Kind = MCSymbolRefExpr::VK_WASM_MBREL; 109 break; 110 case WebAssemblyII::MO_TLS_BASE_REL: 111 Kind = MCSymbolRefExpr::VK_WASM_TLSREL; 112 break; 113 case WebAssemblyII::MO_TABLE_BASE_REL: 114 Kind = MCSymbolRefExpr::VK_WASM_TBREL; 115 break; 116 default: 117 llvm_unreachable("Unknown target flag on GV operand"); 118 } 119 120 const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Kind, Ctx); 121 122 if (MO.getOffset() != 0) { 123 const auto *WasmSym = cast<MCSymbolWasm>(Sym); 124 if (TargetFlags == WebAssemblyII::MO_GOT) 125 report_fatal_error("GOT symbol references do not support offsets"); 126 if (WasmSym->isFunction()) 127 report_fatal_error("Function addresses with offsets not supported"); 128 if (WasmSym->isGlobal()) 129 report_fatal_error("Global indexes with offsets not supported"); 130 if (WasmSym->isTag()) 131 report_fatal_error("Tag indexes with offsets not supported"); 132 if (WasmSym->isTable()) 133 report_fatal_error("Table indexes with offsets not supported"); 134 135 Expr = MCBinaryExpr::createAdd( 136 Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx); 137 } 138 139 return MCOperand::createExpr(Expr); 140 } 141 142 MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand( 143 SmallVectorImpl<wasm::ValType> &&Returns, 144 SmallVectorImpl<wasm::ValType> &&Params) const { 145 auto Signature = Ctx.createWasmSignature(); 146 Signature->Returns = std::move(Returns); 147 Signature->Params = std::move(Params); 148 MCSymbol *Sym = Printer.createTempSymbol("typeindex"); 149 auto *WasmSym = cast<MCSymbolWasm>(Sym); 150 WasmSym->setSignature(Signature); 151 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 152 const MCExpr *Expr = 153 MCSymbolRefExpr::create(WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx); 154 return MCOperand::createExpr(Expr); 155 } 156 157 static void getFunctionReturns(const MachineInstr *MI, 158 SmallVectorImpl<wasm::ValType> &Returns) { 159 const Function &F = MI->getMF()->getFunction(); 160 const TargetMachine &TM = MI->getMF()->getTarget(); 161 Type *RetTy = F.getReturnType(); 162 SmallVector<MVT, 4> CallerRetTys; 163 computeLegalValueVTs(F, TM, RetTy, CallerRetTys); 164 valTypesFromMVTs(CallerRetTys, Returns); 165 } 166 167 void WebAssemblyMCInstLower::lower(const MachineInstr *MI, 168 MCInst &OutMI) const { 169 OutMI.setOpcode(MI->getOpcode()); 170 171 const MCInstrDesc &Desc = MI->getDesc(); 172 unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs(); 173 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 174 const MachineOperand &MO = MI->getOperand(I); 175 176 MCOperand MCOp; 177 switch (MO.getType()) { 178 default: 179 MI->print(errs()); 180 llvm_unreachable("unknown operand type"); 181 case MachineOperand::MO_MachineBasicBlock: 182 MI->print(errs()); 183 llvm_unreachable("MachineBasicBlock operand should have been rewritten"); 184 case MachineOperand::MO_Register: { 185 // Ignore all implicit register operands. 186 if (MO.isImplicit()) 187 continue; 188 const WebAssemblyFunctionInfo &MFI = 189 *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>(); 190 unsigned WAReg = MFI.getWAReg(MO.getReg()); 191 MCOp = MCOperand::createReg(WAReg); 192 break; 193 } 194 case MachineOperand::MO_Immediate: { 195 unsigned DescIndex = I - NumVariadicDefs; 196 if (DescIndex < Desc.NumOperands) { 197 const MCOperandInfo &Info = Desc.operands()[DescIndex]; 198 if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) { 199 SmallVector<wasm::ValType, 4> Returns; 200 SmallVector<wasm::ValType, 4> Params; 201 202 const MachineRegisterInfo &MRI = 203 MI->getParent()->getParent()->getRegInfo(); 204 for (const MachineOperand &MO : MI->defs()) 205 Returns.push_back(WebAssembly::regClassToValType( 206 MRI.getRegClass(MO.getReg())->getID())); 207 for (const MachineOperand &MO : MI->explicit_uses()) 208 if (MO.isReg()) 209 Params.push_back(WebAssembly::regClassToValType( 210 MRI.getRegClass(MO.getReg())->getID())); 211 212 // call_indirect instructions have a callee operand at the end which 213 // doesn't count as a param. 214 if (WebAssembly::isCallIndirect(MI->getOpcode())) 215 Params.pop_back(); 216 217 // return_call_indirect instructions have the return type of the 218 // caller 219 if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT) 220 getFunctionReturns(MI, Returns); 221 222 MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params)); 223 break; 224 } 225 if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) { 226 auto BT = static_cast<WebAssembly::BlockType>(MO.getImm()); 227 assert(BT != WebAssembly::BlockType::Invalid); 228 if (BT == WebAssembly::BlockType::Multivalue) { 229 SmallVector<wasm::ValType, 2> Returns; 230 // Multivalue blocks are emitted in two cases: 231 // 1. When the blocks will never be exited and are at the ends of 232 // functions (see 233 // WebAssemblyCFGStackify::fixEndsAtEndOfFunction). In this case 234 // the exact multivalue signature can always be inferred from the 235 // return type of the parent function. 236 // 2. (catch_ref ...) clause in try_table instruction. Currently all 237 // tags we support (cpp_exception and c_longjmp) throws a single 238 // i32, so the multivalue signature for this case will be (i32, 239 // exnref). Having MO_CATCH_BLOCK_SIG target flags means this is 240 // a destination of a catch_ref. 241 if (MO.getTargetFlags() == WebAssemblyII::MO_CATCH_BLOCK_SIG) 242 Returns = {wasm::ValType::I32, wasm::ValType::EXNREF}; 243 else 244 getFunctionReturns(MI, Returns); 245 MCOp = lowerTypeIndexOperand(std::move(Returns), 246 SmallVector<wasm::ValType, 4>()); 247 break; 248 } 249 } 250 } 251 MCOp = MCOperand::createImm(MO.getImm()); 252 break; 253 } 254 case MachineOperand::MO_FPImmediate: { 255 const ConstantFP *Imm = MO.getFPImm(); 256 const uint64_t BitPattern = 257 Imm->getValueAPF().bitcastToAPInt().getZExtValue(); 258 if (Imm->getType()->isFloatTy()) 259 MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern)); 260 else if (Imm->getType()->isDoubleTy()) 261 MCOp = MCOperand::createDFPImm(BitPattern); 262 else 263 llvm_unreachable("unknown floating point immediate type"); 264 break; 265 } 266 case MachineOperand::MO_GlobalAddress: 267 MCOp = lowerSymbolOperand(MO, GetGlobalAddressSymbol(MO)); 268 break; 269 case MachineOperand::MO_ExternalSymbol: 270 MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO)); 271 break; 272 case MachineOperand::MO_MCSymbol: 273 assert(MO.getTargetFlags() == 0 && 274 "WebAssembly does not use target flags on MCSymbol"); 275 MCOp = lowerSymbolOperand(MO, MO.getMCSymbol()); 276 break; 277 } 278 279 OutMI.addOperand(MCOp); 280 } 281 282 if (!WasmKeepRegisters) 283 removeRegisterOperands(MI, OutMI); 284 else if (Desc.variadicOpsAreDefs()) 285 OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs())); 286 } 287 288 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) { 289 // Remove all uses of stackified registers to bring the instruction format 290 // into its final stack form used thruout MC, and transition opcodes to 291 // their _S variant. 292 // We do this separate from the above code that still may need these 293 // registers for e.g. call_indirect signatures. 294 // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for 295 // details. 296 // TODO: the code above creates new registers which are then removed here. 297 // That code could be slightly simplified by not doing that, though maybe 298 // it is simpler conceptually to keep the code above in "register mode" 299 // until this transition point. 300 // FIXME: we are not processing inline assembly, which contains register 301 // operands, because it is used by later target generic code. 302 if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm()) 303 return; 304 305 // Transform to _S instruction. 306 auto RegOpcode = OutMI.getOpcode(); 307 auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode); 308 assert(StackOpcode != -1 && "Failed to stackify instruction"); 309 OutMI.setOpcode(StackOpcode); 310 311 // Remove register operands. 312 for (auto I = OutMI.getNumOperands(); I; --I) { 313 auto &MO = OutMI.getOperand(I - 1); 314 if (MO.isReg()) { 315 OutMI.erase(&MO); 316 } 317 } 318 } 319