1 // WebAssemblyMCInstLower.cpp - Convert WebAssembly MachineInstr to an MCInst //
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
7 //===----------------------------------------------------------------------===//
10 /// This file contains code to lower WebAssembly MachineInstrs to their
11 /// corresponding MCInst records.
13 //===----------------------------------------------------------------------===//
15 #include "WebAssemblyMCInstLower.h"
16 #include "TargetInfo/WebAssemblyTargetInfo.h"
17 #include "Utils/WebAssemblyTypeUtilities.h"
18 #include "Utils/WebAssemblyUtilities.h"
19 #include "WebAssemblyAsmPrinter.h"
20 #include "WebAssemblyISelLowering.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSymbolWasm.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
35 // This disables the removal of registers when lowering into MC, as required
36 // by some current tests.
38 WasmKeepRegisters("wasm-keep-registers", cl::Hidden
,
39 cl::desc("WebAssembly: output stack registers in"
40 " instruction output for test purposes only."),
43 static void removeRegisterOperands(const MachineInstr
*MI
, MCInst
&OutMI
);
46 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand
&MO
) const {
47 const GlobalValue
*Global
= MO
.getGlobal();
48 if (!isa
<Function
>(Global
)) {
49 auto *WasmSym
= cast
<MCSymbolWasm
>(Printer
.getSymbol(Global
));
50 // If the symbol doesn't have an explicit WasmSymbolType yet and the
51 // GlobalValue is actually a WebAssembly global, then ensure the symbol is a
52 // WASM_SYMBOL_TYPE_GLOBAL.
53 if (WebAssembly::isWasmVarAddressSpace(Global
->getAddressSpace()) &&
54 !WasmSym
->getType()) {
55 const MachineFunction
&MF
= *MO
.getParent()->getParent()->getParent();
56 const TargetMachine
&TM
= MF
.getTarget();
57 const Function
&CurrentFunc
= MF
.getFunction();
58 Type
*GlobalVT
= Global
->getValueType();
59 SmallVector
<MVT
, 1> VTs
;
60 computeLegalValueVTs(CurrentFunc
, TM
, GlobalVT
, VTs
);
62 WebAssembly::wasmSymbolSetType(WasmSym
, GlobalVT
, VTs
);
67 const auto *FuncTy
= cast
<FunctionType
>(Global
->getValueType());
68 const MachineFunction
&MF
= *MO
.getParent()->getParent()->getParent();
69 const TargetMachine
&TM
= MF
.getTarget();
70 const Function
&CurrentFunc
= MF
.getFunction();
72 SmallVector
<MVT
, 1> ResultMVTs
;
73 SmallVector
<MVT
, 4> ParamMVTs
;
74 const auto *const F
= dyn_cast
<Function
>(Global
);
75 computeSignatureVTs(FuncTy
, F
, CurrentFunc
, TM
, ParamMVTs
, ResultMVTs
);
76 auto Signature
= signatureFromMVTs(ResultMVTs
, ParamMVTs
);
78 bool InvokeDetected
= false;
79 auto *WasmSym
= Printer
.getMCSymbolForFunction(
80 F
, WebAssembly::WasmEnableEmEH
|| WebAssembly::WasmEnableEmSjLj
,
81 Signature
.get(), InvokeDetected
);
82 WasmSym
->setSignature(Signature
.get());
83 Printer
.addSignature(std::move(Signature
));
84 WasmSym
->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION
);
88 MCSymbol
*WebAssemblyMCInstLower::GetExternalSymbolSymbol(
89 const MachineOperand
&MO
) const {
90 return Printer
.getOrCreateWasmSymbol(MO
.getSymbolName());
93 MCOperand
WebAssemblyMCInstLower::lowerSymbolOperand(const MachineOperand
&MO
,
94 MCSymbol
*Sym
) const {
95 MCSymbolRefExpr::VariantKind Kind
= MCSymbolRefExpr::VK_None
;
96 unsigned TargetFlags
= MO
.getTargetFlags();
98 switch (TargetFlags
) {
99 case WebAssemblyII::MO_NO_FLAG
:
101 case WebAssemblyII::MO_GOT_TLS
:
102 Kind
= MCSymbolRefExpr::VK_WASM_GOT_TLS
;
104 case WebAssemblyII::MO_GOT
:
105 Kind
= MCSymbolRefExpr::VK_GOT
;
107 case WebAssemblyII::MO_MEMORY_BASE_REL
:
108 Kind
= MCSymbolRefExpr::VK_WASM_MBREL
;
110 case WebAssemblyII::MO_TLS_BASE_REL
:
111 Kind
= MCSymbolRefExpr::VK_WASM_TLSREL
;
113 case WebAssemblyII::MO_TABLE_BASE_REL
:
114 Kind
= MCSymbolRefExpr::VK_WASM_TBREL
;
117 llvm_unreachable("Unknown target flag on GV operand");
120 const MCExpr
*Expr
= MCSymbolRefExpr::create(Sym
, Kind
, Ctx
);
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");
135 Expr
= MCBinaryExpr::createAdd(
136 Expr
, MCConstantExpr::create(MO
.getOffset(), Ctx
), Ctx
);
139 return MCOperand::createExpr(Expr
);
142 MCOperand
WebAssemblyMCInstLower::lowerTypeIndexOperand(
143 SmallVector
<wasm::ValType
, 1> &&Returns
,
144 SmallVector
<wasm::ValType
, 4> &&Params
) const {
145 auto Signature
= std::make_unique
<wasm::WasmSignature
>(std::move(Returns
),
147 MCSymbol
*Sym
= Printer
.createTempSymbol("typeindex");
148 auto *WasmSym
= cast
<MCSymbolWasm
>(Sym
);
149 WasmSym
->setSignature(Signature
.get());
150 Printer
.addSignature(std::move(Signature
));
151 WasmSym
->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION
);
153 MCSymbolRefExpr::create(WasmSym
, MCSymbolRefExpr::VK_WASM_TYPEINDEX
, Ctx
);
154 return MCOperand::createExpr(Expr
);
157 // Return the WebAssembly type associated with the given register class.
158 static wasm::ValType
getType(const TargetRegisterClass
*RC
) {
159 if (RC
== &WebAssembly::I32RegClass
)
160 return wasm::ValType::I32
;
161 if (RC
== &WebAssembly::I64RegClass
)
162 return wasm::ValType::I64
;
163 if (RC
== &WebAssembly::F32RegClass
)
164 return wasm::ValType::F32
;
165 if (RC
== &WebAssembly::F64RegClass
)
166 return wasm::ValType::F64
;
167 if (RC
== &WebAssembly::V128RegClass
)
168 return wasm::ValType::V128
;
169 if (RC
== &WebAssembly::EXTERNREFRegClass
)
170 return wasm::ValType::EXTERNREF
;
171 if (RC
== &WebAssembly::FUNCREFRegClass
)
172 return wasm::ValType::FUNCREF
;
173 llvm_unreachable("Unexpected register class");
176 static void getFunctionReturns(const MachineInstr
*MI
,
177 SmallVectorImpl
<wasm::ValType
> &Returns
) {
178 const Function
&F
= MI
->getMF()->getFunction();
179 const TargetMachine
&TM
= MI
->getMF()->getTarget();
180 Type
*RetTy
= F
.getReturnType();
181 SmallVector
<MVT
, 4> CallerRetTys
;
182 computeLegalValueVTs(F
, TM
, RetTy
, CallerRetTys
);
183 valTypesFromMVTs(CallerRetTys
, Returns
);
186 void WebAssemblyMCInstLower::lower(const MachineInstr
*MI
,
187 MCInst
&OutMI
) const {
188 OutMI
.setOpcode(MI
->getOpcode());
190 const MCInstrDesc
&Desc
= MI
->getDesc();
191 unsigned NumVariadicDefs
= MI
->getNumExplicitDefs() - Desc
.getNumDefs();
192 for (unsigned I
= 0, E
= MI
->getNumOperands(); I
!= E
; ++I
) {
193 const MachineOperand
&MO
= MI
->getOperand(I
);
196 switch (MO
.getType()) {
199 llvm_unreachable("unknown operand type");
200 case MachineOperand::MO_MachineBasicBlock
:
202 llvm_unreachable("MachineBasicBlock operand should have been rewritten");
203 case MachineOperand::MO_Register
: {
204 // Ignore all implicit register operands.
207 const WebAssemblyFunctionInfo
&MFI
=
208 *MI
->getParent()->getParent()->getInfo
<WebAssemblyFunctionInfo
>();
209 unsigned WAReg
= MFI
.getWAReg(MO
.getReg());
210 MCOp
= MCOperand::createReg(WAReg
);
213 case MachineOperand::MO_Immediate
: {
214 unsigned DescIndex
= I
- NumVariadicDefs
;
215 if (DescIndex
< Desc
.NumOperands
) {
216 const MCOperandInfo
&Info
= Desc
.OpInfo
[DescIndex
];
217 if (Info
.OperandType
== WebAssembly::OPERAND_TYPEINDEX
) {
218 SmallVector
<wasm::ValType
, 4> Returns
;
219 SmallVector
<wasm::ValType
, 4> Params
;
221 const MachineRegisterInfo
&MRI
=
222 MI
->getParent()->getParent()->getRegInfo();
223 for (const MachineOperand
&MO
: MI
->defs())
224 Returns
.push_back(getType(MRI
.getRegClass(MO
.getReg())));
225 for (const MachineOperand
&MO
: MI
->explicit_uses())
227 Params
.push_back(getType(MRI
.getRegClass(MO
.getReg())));
229 // call_indirect instructions have a callee operand at the end which
230 // doesn't count as a param.
231 if (WebAssembly::isCallIndirect(MI
->getOpcode()))
234 // return_call_indirect instructions have the return type of the
236 if (MI
->getOpcode() == WebAssembly::RET_CALL_INDIRECT
)
237 getFunctionReturns(MI
, Returns
);
239 MCOp
= lowerTypeIndexOperand(std::move(Returns
), std::move(Params
));
241 } else if (Info
.OperandType
== WebAssembly::OPERAND_SIGNATURE
) {
242 auto BT
= static_cast<WebAssembly::BlockType
>(MO
.getImm());
243 assert(BT
!= WebAssembly::BlockType::Invalid
);
244 if (BT
== WebAssembly::BlockType::Multivalue
) {
245 SmallVector
<wasm::ValType
, 1> Returns
;
246 getFunctionReturns(MI
, Returns
);
247 MCOp
= lowerTypeIndexOperand(std::move(Returns
),
248 SmallVector
<wasm::ValType
, 4>());
253 MCOp
= MCOperand::createImm(MO
.getImm());
256 case MachineOperand::MO_FPImmediate
: {
257 const ConstantFP
*Imm
= MO
.getFPImm();
258 const uint64_t BitPattern
=
259 Imm
->getValueAPF().bitcastToAPInt().getZExtValue();
260 if (Imm
->getType()->isFloatTy())
261 MCOp
= MCOperand::createSFPImm(static_cast<uint32_t>(BitPattern
));
262 else if (Imm
->getType()->isDoubleTy())
263 MCOp
= MCOperand::createDFPImm(BitPattern
);
265 llvm_unreachable("unknown floating point immediate type");
268 case MachineOperand::MO_GlobalAddress
:
269 MCOp
= lowerSymbolOperand(MO
, GetGlobalAddressSymbol(MO
));
271 case MachineOperand::MO_ExternalSymbol
:
272 MCOp
= lowerSymbolOperand(MO
, GetExternalSymbolSymbol(MO
));
274 case MachineOperand::MO_MCSymbol
:
275 assert(MO
.getTargetFlags() == 0 &&
276 "WebAssembly does not use target flags on MCSymbol");
277 MCOp
= lowerSymbolOperand(MO
, MO
.getMCSymbol());
281 OutMI
.addOperand(MCOp
);
284 if (!WasmKeepRegisters
)
285 removeRegisterOperands(MI
, OutMI
);
286 else if (Desc
.variadicOpsAreDefs())
287 OutMI
.insert(OutMI
.begin(), MCOperand::createImm(MI
->getNumExplicitDefs()));
290 static void removeRegisterOperands(const MachineInstr
*MI
, MCInst
&OutMI
) {
291 // Remove all uses of stackified registers to bring the instruction format
292 // into its final stack form used thruout MC, and transition opcodes to
294 // We do this separate from the above code that still may need these
295 // registers for e.g. call_indirect signatures.
296 // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
298 // TODO: the code above creates new registers which are then removed here.
299 // That code could be slightly simplified by not doing that, though maybe
300 // it is simpler conceptually to keep the code above in "register mode"
301 // until this transition point.
302 // FIXME: we are not processing inline assembly, which contains register
303 // operands, because it is used by later target generic code.
304 if (MI
->isDebugInstr() || MI
->isLabel() || MI
->isInlineAsm())
307 // Transform to _S instruction.
308 auto RegOpcode
= OutMI
.getOpcode();
309 auto StackOpcode
= WebAssembly::getStackOpcode(RegOpcode
);
310 assert(StackOpcode
!= -1 && "Failed to stackify instruction");
311 OutMI
.setOpcode(StackOpcode
);
313 // Remove register operands.
314 for (auto I
= OutMI
.getNumOperands(); I
; --I
) {
315 auto &MO
= OutMI
.getOperand(I
- 1);