LLVM 24.0.0git
WebAssemblyMCInstLower.cpp
Go to the documentation of this file.
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
24#include "llvm/ADT/APInt.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCExpr.h"
36#include "llvm/MC/MCInst.h"
40#include <optional>
41
42using namespace llvm;
43
44static std::optional<bool> getWasmGlobalMutable(const GlobalValue *Global,
45 const Function &CurrentFunc,
46 const DiagnosticLocation &DL) {
47 const auto *BaseObject = Global->getAliaseeObject();
48 const auto *GV = dyn_cast_or_null<GlobalVariable>(BaseObject);
49 if (!GV) {
51 CurrentFunc,
52 "wasm_var address space symbol must resolve to a "
53 "GlobalVariable",
54 DL));
55 return std::nullopt;
56 }
57 return !GV->isConstant();
58}
59
60static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
61
63WebAssemblyMCInstLower::GetGlobalAddressSymbol(const GlobalValue &Global,
64 const DebugLoc &DL) const {
65 const TargetMachine &TM = Printer.TM;
66 const Function &CurrentFunc = Printer.MF->getFunction();
67 if (!isa<Function>(Global)) {
68 auto *WasmSym = static_cast<MCSymbolWasm *>(Printer.getSymbol(&Global));
69 // If the symbol doesn't have an explicit WasmSymbolType yet and the
70 // GlobalValue is actually a WebAssembly global, then ensure the symbol is a
71 // WASM_SYMBOL_TYPE_GLOBAL.
72 if (WebAssembly::isWasmVarAddressSpace(Global.getAddressSpace()) &&
73 !WasmSym->getType()) {
74 std::optional<bool> Mutable =
75 getWasmGlobalMutable(&Global, CurrentFunc, DL);
76 if (!Mutable.has_value())
77 return WasmSym;
78
79 Type *GlobalVT = Global.getValueType();
81 computeLegalValueVTs(CurrentFunc, TM, GlobalVT, VTs);
82
83 WebAssembly::wasmSymbolSetType(WasmSym, GlobalVT, VTs, *Mutable);
84 }
85 return WasmSym;
86 }
87
88 const auto *FuncTy = cast<FunctionType>(Global.getValueType());
89
90 SmallVector<MVT, 1> ResultMVTs;
91 SmallVector<MVT, 4> ParamMVTs;
92 const auto *const F = dyn_cast<Function>(&Global);
93 computeSignatureVTs(FuncTy, F, CurrentFunc, TM, ParamMVTs, ResultMVTs);
94 auto Signature = signatureFromMVTs(Ctx, ResultMVTs, ParamMVTs);
95
96 bool InvokeDetected = false;
97 auto *WasmSym = Printer.getMCSymbolForFunction(F, Signature, InvokeDetected);
98 WasmSym->setSignature(Signature);
99 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
100 return WasmSym;
101}
102
103MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
104 const MachineOperand &MO) const {
105 return Printer.getOrCreateWasmSymbol(MO.getSymbolName());
106}
107
108MCOperand WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand &MO,
109 MCSymbol *Sym) const {
110 auto Spec = WebAssembly::S_None;
111 unsigned TargetFlags = MO.getTargetFlags();
112
113 switch (TargetFlags) {
115 break;
118 break;
120 Spec = WebAssembly::S_GOT;
121 break;
124 break;
127 break;
130 break;
131 default:
132 llvm_unreachable("Unknown target flag on GV operand");
133 }
134
135 const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Spec, Ctx);
136
137 if (MO.getOffset() != 0) {
138 const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
139 if (TargetFlags == WebAssemblyII::MO_GOT)
140 report_fatal_error("GOT symbol references do not support offsets");
141 if (WasmSym->isFunction())
142 report_fatal_error("Function addresses with offsets not supported");
143 if (WasmSym->isGlobal())
144 report_fatal_error("Global indexes with offsets not supported");
145 if (WasmSym->isTag())
146 report_fatal_error("Tag indexes with offsets not supported");
147 if (WasmSym->isTable())
148 report_fatal_error("Table indexes with offsets not supported");
149
151 Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
152 }
153
154 return MCOperand::createExpr(Expr);
155}
156
157MCOperand WebAssemblyMCInstLower::lowerTypeIndexOperand(
159 SmallVectorImpl<wasm::ValType> &&Params) const {
160 auto Signature = Ctx.createWasmSignature();
161 Signature->Returns = std::move(Returns);
162 Signature->Params = std::move(Params);
163 auto *Sym =
164 static_cast<MCSymbolWasm *>(Printer.createTempSymbol("typeindex"));
165 Sym->setSignature(Signature);
167 const MCExpr *Expr =
169 return MCOperand::createExpr(Expr);
170}
171
173WebAssemblyMCInstLower::lowerEncodedFunctionSignature(const APInt &Sig) const {
174 // For APInt a word is 64 bits on all architectures, see definition in APInt.h
175 auto NumWords = Sig.getNumWords();
178
179 int Idx = NumWords;
180 auto GetWord = [&Idx, &Sig]() {
181 Idx--;
182 return Sig.extractBitsAsZExtValue(64, 64 * Idx);
183 };
184 // Annoying special case: if getSignificantBits() <= 64 then InstrEmitter will
185 // emit an Imm instead of a CImm. It simplifies WebAssemblyMCInstLower if we
186 // always emit a CImm. So xor NParams with 0x7ffffff to ensure
187 // getSignificantBits() > 64
188 // See encodeFunctionSignature in WebAssemblyISelDAGtoDAG.cpp
189 int NReturns = GetWord() ^ 0x7ffffff;
190 for (int I = 0; I < NReturns; I++) {
191 Returns.push_back(static_cast<wasm::ValType>(GetWord()));
192 }
193 int NParams = GetWord();
194 for (int I = 0; I < NParams; I++) {
195 Params.push_back(static_cast<wasm::ValType>(GetWord()));
196 }
197 return lowerTypeIndexOperand(std::move(Returns), std::move(Params));
198}
199
202 const Function &F = MI->getMF()->getFunction();
203 const TargetMachine &TM = MI->getMF()->getTarget();
204 Type *RetTy = F.getReturnType();
205 SmallVector<MVT, 4> CallerRetTys;
206 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
207 valTypesFromMVTs(CallerRetTys, Returns);
208}
209
211 MCInst &OutMI) const {
212 OutMI.setOpcode(MI->getOpcode());
213
214 const MCInstrDesc &Desc = MI->getDesc();
215 unsigned NumVariadicDefs = MI->getNumExplicitDefs() - Desc.getNumDefs();
216 const MachineFunction *MF = MI->getMF();
217 const auto &TLI =
218 *MF->getSubtarget<WebAssemblySubtarget>().getTargetLowering();
219 wasm::ValType PtrTy = TLI.getPointerTy(MF->getDataLayout()) == MVT::i32
222
223 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
224 const MachineOperand &MO = MI->getOperand(I);
225
226 MCOperand MCOp;
227 switch (MO.getType()) {
228 default:
229 MI->print(errs());
230 llvm_unreachable("unknown operand type");
232 MI->print(errs());
233 llvm_unreachable("MachineBasicBlock operand should have been rewritten");
235 // Ignore all implicit register operands.
236 if (MO.isImplicit())
237 continue;
238 const WebAssemblyFunctionInfo &MFI =
239 *MI->getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
240 unsigned WAReg = MFI.getWAReg(MO.getReg());
241 MCOp = MCOperand::createReg(WAReg);
242 break;
243 }
245 // Lower type index placeholder for ref.test
246 // Currently this is the only way that CImmediates show up so panic if we
247 // get confused.
248 unsigned DescIndex = I - NumVariadicDefs;
249 assert(DescIndex < Desc.NumOperands && "unexpected CImmediate operand");
250 auto Operands = Desc.operands();
251 const MCOperandInfo &Info = Operands[DescIndex];
252 assert(Info.OperandType == WebAssembly::OPERAND_TYPEINDEX &&
253 "unexpected CImmediate operand");
254 (void)Info;
255 MCOp = lowerEncodedFunctionSignature(MO.getCImm()->getValue());
256 break;
257 }
259 unsigned DescIndex = I - NumVariadicDefs;
260 if (DescIndex < Desc.NumOperands) {
261 auto Operands = Desc.operands();
262 const MCOperandInfo &Info = Operands[DescIndex];
263 // Replace type index placeholder with actual type index. The type index
264 // placeholders are Immediates and have an operand type of
265 // OPERAND_TYPEINDEX or OPERAND_SIGNATURE.
266 if (Info.OperandType == WebAssembly::OPERAND_TYPEINDEX) {
267 // Lower type index placeholder for a CALL_INDIRECT instruction
270
271 const MachineRegisterInfo &MRI =
272 MI->getParent()->getParent()->getRegInfo();
273 for (const MachineOperand &MO : MI->defs())
275 MRI.getRegClass(MO.getReg())->getID()));
276 for (const MachineOperand &MO : MI->explicit_uses())
277 if (MO.isReg())
279 MRI.getRegClass(MO.getReg())->getID()));
280
281 // call_indirect instructions have a callee operand at the end which
282 // doesn't count as a param.
283 if (WebAssembly::isCallIndirect(MI->getOpcode()))
284 Params.pop_back();
285
286 // return_call_indirect instructions have the return type of the
287 // caller
288 if (MI->getOpcode() == WebAssembly::RET_CALL_INDIRECT)
289 getFunctionReturns(MI, Returns);
290
291 MCOp = lowerTypeIndexOperand(std::move(Returns), std::move(Params));
292 break;
293 }
294 if (Info.OperandType == WebAssembly::OPERAND_SIGNATURE) {
295 // Lower type index placeholder for blocks
296 auto BT = static_cast<WebAssembly::BlockType>(MO.getImm());
300 // Multivalue blocks are emitted in two cases:
301 // 1. When the blocks will never be exited and are at the ends of
302 // functions (see
303 // WebAssemblyCFGStackify::fixEndsAtEndOfFunction). In this case
304 // the exact multivalue signature can always be inferred from the
305 // return type of the parent function.
306 // 2. (catch_ref ...) clause in try_table instruction. Currently all
307 // tags we support (cpp_exception and c_longjmp) throws a single
308 // pointer, so the multivalue signature for this case will be
309 // (ptr, exnref). Having MO_CATCH_BLOCK_SIG target flags means
310 // this is a destination of a catch_ref.
312 Returns = {PtrTy, wasm::ValType::EXNREF};
313 } else
314 getFunctionReturns(MI, Returns);
315 MCOp = lowerTypeIndexOperand(std::move(Returns),
317 break;
318 }
319 }
320 }
321 MCOp = MCOperand::createImm(MO.getImm());
322 break;
323 }
325 const ConstantFP *Imm = MO.getFPImm();
326 const uint64_t BitPattern =
327 Imm->getValueAPF().bitcastToAPInt().getZExtValue();
328 if (Imm->getType()->isFloatTy())
329 MCOp = MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern));
330 else if (Imm->getType()->isDoubleTy())
331 MCOp = MCOperand::createDFPImm(BitPattern);
332 else
333 llvm_unreachable("unknown floating point immediate type");
334 break;
335 }
337 MCOp = lowerSymbolOperand(
338 MO, GetGlobalAddressSymbol(*MO.getGlobal(), MI->getDebugLoc()));
339 break;
341 MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
342 break;
344 assert(MO.getTargetFlags() == 0 &&
345 "WebAssembly does not use target flags on MCSymbol");
346 MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
347 break;
348 }
349
350 OutMI.addOperand(MCOp);
351 }
352
353 if (!Printer.getSubtarget().getCLOpts().keep_registers)
355 else if (Desc.variadicOpsAreDefs())
356 OutMI.insert(OutMI.begin(), MCOperand::createImm(MI->getNumExplicitDefs()));
357}
358
359static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
360 // Remove all uses of stackified registers to bring the instruction format
361 // into its final stack form used throughout MC, and transition opcodes to
362 // their _S variant.
363 // We do this separate from the above code that still may need these
364 // registers for e.g. call_indirect signatures.
365 // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
366 // details.
367 // TODO: the code above creates new registers which are then removed here.
368 // That code could be slightly simplified by not doing that, though maybe
369 // it is simpler conceptually to keep the code above in "register mode"
370 // until this transition point.
371 // FIXME: we are not processing inline assembly, which contains register
372 // operands, because it is used by later target generic code.
373 if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
374 return;
375
376 // Transform to _S instruction.
377 auto RegOpcode = OutMI.getOpcode();
378 auto StackOpcode = WebAssembly::getStackOpcode(RegOpcode);
379 assert(StackOpcode != -1 && "Failed to stackify instruction");
380 OutMI.setOpcode(StackOpcode);
381
382 // Remove register operands.
383 for (auto I = OutMI.getNumOperands(); I; --I) {
384 auto &MO = OutMI.getOperand(I - 1);
385 if (MO.isReg()) {
386 OutMI.erase(&MO);
387 }
388 }
389}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t Imm
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BitTracker BT
This file contains the declarations for the subclasses of Constant, which represent the different fla...
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
MachineRegisterInfo & MRI
SI Fold Operands
This file defines the SmallVector class.
This file contains the declaration of the WebAssemblyMCAsmInfo class.
static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI)
static std::optional< bool > getWasmGlobalMutable(const GlobalValue *Global, const Function &CurrentFunc, const DiagnosticLocation &DL)
static void getFunctionReturns(const MachineInstr *MI, SmallVectorImpl< wasm::ValType > &Returns)
This file declares the class to lower WebAssembly MachineInstrs to their corresponding MCInst records...
This file provides WebAssembly-specific target descriptions.
This file contains the declaration of the WebAssembly-specific type parsing utility functions.
This file declares WebAssembly-specific per-machine-function information.
This file registers the WebAssembly target.
This file contains the declaration of the WebAssembly-specific type parsing utility functions.
This file contains the declaration of the WebAssembly-specific utility functions.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:517
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1515
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A debug info location.
Definition DebugLoc.h:127
Diagnostic information for unsupported feature in backend.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void erase(iterator I)
Definition MCInst.h:224
unsigned getNumOperands() const
Definition MCInst.h:212
unsigned getOpcode() const
Definition MCInst.h:202
iterator insert(iterator I, const MCOperand &Op)
Definition MCInst.h:232
void addOperand(const MCOperand Op)
Definition MCInst.h:215
iterator begin()
Definition MCInst.h:227
void setOpcode(unsigned Op)
Definition MCInst.h:201
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:210
Describe properties that are true of each instruction in the target description file.
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
static MCOperand createSFPImm(uint32_t Val)
Definition MCInst.h:152
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
static MCOperand createDFPImm(uint64_t Val)
Definition MCInst.h:159
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
const ConstantInt * getCImm() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
unsigned getTargetFlags() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_CImmediate
Immediate >64bit operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_FPImmediate
Floating-point immediate operand.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Primary interface to the complete machine description for the target machine.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
void lower(const MachineInstr *MI, MCInst &OutMI) const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isCallIndirect(unsigned Opc)
wasm::ValType regClassToValType(unsigned RC)
int32_t getStackOpcode(uint32_t Opcode)
BlockType
Used as immediate MachineOperands for block signatures.
void wasmSymbolSetType(MCSymbolWasm *Sym, const Type *GlobalVT, ArrayRef< MVT > VTs, bool Mutable)
Sets a Wasm Symbol Type.
@ OPERAND_TYPEINDEX
type signature immediate for call_indirect.
@ OPERAND_SIGNATURE
signature immediate for block/loop.
bool isWasmVarAddressSpace(unsigned AS)
@ WASM_SYMBOL_TYPE_FUNCTION
Definition Wasm.h:231
This is an optimization pass for GlobalISel generic memory operations.
void computeSignatureVTs(const FunctionType *Ty, const Function *TargetFunc, const Function &ContextFunc, const TargetMachine &TM, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Op::Description Desc
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
void valTypesFromMVTs(ArrayRef< MVT > In, SmallVectorImpl< wasm::ValType > &Out)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
wasm::WasmSignature * signatureFromMVTs(MCContext &Ctx, const SmallVectorImpl< MVT > &Results, const SmallVectorImpl< MVT > &Params)
void computeLegalValueVTs(const WebAssemblyTargetLowering &TLI, LLVMContext &Ctx, const DataLayout &DL, Type *Ty, SmallVectorImpl< MVT > &ValueVTs)