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