LLVM  8.0.0svn
WebAssemblyMCInstLower.cpp
Go to the documentation of this file.
1 // WebAssemblyMCInstLower.cpp - Convert WebAssembly MachineInstr to an MCInst //
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file contains code to lower WebAssembly MachineInstrs to their
12 /// corresponding MCInst records.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "WebAssemblyMCInstLower.h"
17 #include "WebAssemblyAsmPrinter.h"
20 #include "WebAssemblyUtilities.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"
31 using namespace llvm;
32 
33 // This disables the removal of registers when lowering into MC, as required
34 // by some current tests.
35 static 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 static unsigned regInstructionToStackInstruction(unsigned OpCode);
42 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI);
43 
44 MCSymbol *
45 WebAssemblyMCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
46  const GlobalValue *Global = MO.getGlobal();
47  MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Printer.getSymbol(Global));
48 
49  if (const auto *FuncTy = dyn_cast<FunctionType>(Global->getValueType())) {
50  const MachineFunction &MF = *MO.getParent()->getParent()->getParent();
51  const TargetMachine &TM = MF.getTarget();
52  const Function &CurrentFunc = MF.getFunction();
53 
54  SmallVector<MVT, 1> ResultMVTs;
55  SmallVector<MVT, 4> ParamMVTs;
56  ComputeSignatureVTs(FuncTy, CurrentFunc, TM, ParamMVTs, ResultMVTs);
57 
58  auto Signature = SignatureFromMVTs(ResultMVTs, ParamMVTs);
59  WasmSym->setSignature(Signature.get());
60  Printer.addSignature(std::move(Signature));
62  }
63 
64  return WasmSym;
65 }
66 
67 MCSymbol *WebAssemblyMCInstLower::GetExternalSymbolSymbol(
68  const MachineOperand &MO) const {
69  const char *Name = MO.getSymbolName();
70  MCSymbolWasm *WasmSym =
71  cast<MCSymbolWasm>(Printer.GetExternalSymbolSymbol(Name));
72  const WebAssemblySubtarget &Subtarget = Printer.getSubtarget();
73 
74  // __stack_pointer is a global variable; all other external symbols used by
75  // CodeGen are functions. It's OK to hardcode knowledge of specific symbols
76  // here; this method is precisely there for fetching the signatures of known
77  // Clang-provided symbols.
78  if (strcmp(Name, "__stack_pointer") == 0) {
81  uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
83  true});
84  return WasmSym;
85  }
86 
89  GetLibcallSignature(Subtarget, Name, Returns, Params);
90  auto Signature =
91  make_unique<wasm::WasmSignature>(std::move(Returns), std::move(Params));
92  WasmSym->setSignature(Signature.get());
93  Printer.addSignature(std::move(Signature));
95 
96  return WasmSym;
97 }
98 
99 MCOperand WebAssemblyMCInstLower::LowerSymbolOperand(MCSymbol *Sym,
100  int64_t Offset,
101  bool IsFunc,
102  bool IsGlob) const {
107 
108  const MCExpr *Expr = MCSymbolRefExpr::create(Sym, VK, Ctx);
109 
110  if (Offset != 0) {
111  if (IsFunc)
112  report_fatal_error("Function addresses with offsets not supported");
113  if (IsGlob)
114  report_fatal_error("Global indexes with offsets not supported");
115  Expr =
116  MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(Offset, Ctx), Ctx);
117  }
118 
119  return MCOperand::createExpr(Expr);
120 }
121 
122 // Return the WebAssembly type associated with the given register class.
124  if (RC == &WebAssembly::I32RegClass)
125  return wasm::ValType::I32;
126  if (RC == &WebAssembly::I64RegClass)
127  return wasm::ValType::I64;
128  if (RC == &WebAssembly::F32RegClass)
129  return wasm::ValType::F32;
130  if (RC == &WebAssembly::F64RegClass)
131  return wasm::ValType::F64;
132  if (RC == &WebAssembly::V128RegClass)
133  return wasm::ValType::V128;
134  llvm_unreachable("Unexpected register class");
135 }
136 
138  MCInst &OutMI) const {
139  OutMI.setOpcode(MI->getOpcode());
140 
141  const MCInstrDesc &Desc = MI->getDesc();
142  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
143  const MachineOperand &MO = MI->getOperand(i);
144 
145  MCOperand MCOp;
146  switch (MO.getType()) {
147  default:
148  MI->print(errs());
149  llvm_unreachable("unknown operand type");
151  MI->print(errs());
152  llvm_unreachable("MachineBasicBlock operand should have been rewritten");
154  // Ignore all implicit register operands.
155  if (MO.isImplicit())
156  continue;
157  const WebAssemblyFunctionInfo &MFI =
159  unsigned WAReg = MFI.getWAReg(MO.getReg());
160  MCOp = MCOperand::createReg(WAReg);
161  break;
162  }
164  if (i < Desc.NumOperands) {
165  const MCOperandInfo &Info = Desc.OpInfo[i];
167  MCSymbol *Sym = Printer.createTempSymbol("typeindex");
168 
171 
172  const MachineRegisterInfo &MRI =
173  MI->getParent()->getParent()->getRegInfo();
174  for (const MachineOperand &MO : MI->defs())
175  Returns.push_back(getType(MRI.getRegClass(MO.getReg())));
176  for (const MachineOperand &MO : MI->explicit_uses())
177  if (MO.isReg())
178  Params.push_back(getType(MRI.getRegClass(MO.getReg())));
179 
180  // call_indirect instructions have a callee operand at the end which
181  // doesn't count as a param.
183  Params.pop_back();
184 
185  MCSymbolWasm *WasmSym = cast<MCSymbolWasm>(Sym);
186  auto Signature = make_unique<wasm::WasmSignature>(std::move(Returns),
187  std::move(Params));
188  WasmSym->setSignature(Signature.get());
189  Printer.addSignature(std::move(Signature));
191 
192  const MCExpr *Expr = MCSymbolRefExpr::create(
194  MCOp = MCOperand::createExpr(Expr);
195  break;
196  }
197  }
198  MCOp = MCOperand::createImm(MO.getImm());
199  break;
201  // TODO: MC converts all floating point immediate operands to double.
202  // This is fine for numeric values, but may cause NaNs to change bits.
203  const ConstantFP *Imm = MO.getFPImm();
204  if (Imm->getType()->isFloatTy())
206  else if (Imm->getType()->isDoubleTy())
208  else
209  llvm_unreachable("unknown floating point immediate type");
210  break;
211  }
214  "WebAssembly does not use target flags on GlobalAddresses");
215  MCOp = LowerSymbolOperand(GetGlobalAddressSymbol(MO), MO.getOffset(),
217  false);
218  break;
220  // The target flag indicates whether this is a symbol for a
221  // variable or a function.
222  assert((MO.getTargetFlags() & ~WebAssemblyII::MO_SYMBOL_MASK) == 0 &&
223  "WebAssembly uses only symbol flags on ExternalSymbols");
224  MCOp = LowerSymbolOperand(
225  GetExternalSymbolSymbol(MO), /*Offset=*/0,
228  break;
229  }
230 
231  OutMI.addOperand(MCOp);
232  }
233 
234  if (!WasmKeepRegisters)
235  removeRegisterOperands(MI, OutMI);
236 }
237 
238 static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI) {
239  // Remove all uses of stackified registers to bring the instruction format
240  // into its final stack form used thruout MC, and transition opcodes to
241  // their _S variant.
242  // We do this seperate from the above code that still may need these
243  // registers for e.g. call_indirect signatures.
244  // See comments in lib/Target/WebAssembly/WebAssemblyInstrFormats.td for
245  // details.
246  // TODO: the code above creates new registers which are then removed here.
247  // That code could be slightly simplified by not doing that, though maybe
248  // it is simpler conceptually to keep the code above in "register mode"
249  // until this transition point.
250  // FIXME: we are not processing inline assembly, which contains register
251  // operands, because it is used by later target generic code.
252  if (MI->isDebugInstr() || MI->isLabel() || MI->isInlineAsm())
253  return;
254 
255  // Transform to _S instruction.
256  auto RegOpcode = OutMI.getOpcode();
257  auto StackOpcode = regInstructionToStackInstruction(RegOpcode);
258  OutMI.setOpcode(StackOpcode);
259 
260  // Remove register operands.
261  for (auto I = OutMI.getNumOperands(); I; --I) {
262  auto &MO = OutMI.getOperand(I - 1);
263  if (MO.isReg()) {
264  OutMI.erase(&MO);
265  }
266  }
267 }
268 
269 static unsigned regInstructionToStackInstruction(unsigned OpCode) {
270  // For most opcodes, this function could have been implemented as "return
271  // OpCode + 1", but since table-gen alphabetically sorts them, this cannot be
272  // guaranteed (see e.g. BR and BR_IF). Instead we use a giant switch statement
273  // generated by a custom TableGen backend (WebAssemblyStackifierEmitter.cpp)
274  // that emits switch cases of the form
275  //
276  // case WebAssembly::RegisterInstr: return WebAssembly::StackInstr;
277  //
278  // for every pair of equivalent register and stack instructions.
279  switch (OpCode) {
280  default:
282  "unknown WebAssembly instruction in WebAssemblyMCInstLower pass");
283 #include "WebAssemblyGenStackifier.inc"
284  }
285 }
unsigned getTargetFlags() const
void push_back(const T &Elt)
Definition: SmallVector.h:218
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isLabel() const
Returns true if the MachineInstr represents a label.
Definition: MachineInstr.h:986
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:322
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:137
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
unsigned getReg() const
getReg - Returns the register number.
void setGlobalType(wasm::WasmGlobalType GT)
Definition: MCSymbolWasm.h:68
bool isInlineAsm() const
This file declares the class to lower WebAssembly MachineInstrs to their corresponding MCInst records...
float convertToFloat() const
Definition: APFloat.h:1098
MachineBasicBlock reference.
static unsigned regInstructionToStackInstruction(unsigned OpCode)
static cl::opt< bool > WasmKeepRegisters("wasm-keep-registers", cl::Hidden, cl::desc("WebAssembly: output stack registers in" " instruction output for test purposes only."), cl::init(false))
amdgpu Simplify well known AMD library false Value Value const Twine & Name
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:116
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:412
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
void erase(iterator I)
Definition: MCInst.h:192
Name of external global symbol.
static void removeRegisterOperands(const MachineInstr *MI, MCInst &OutMI)
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:409
const char * getSymbolName() const
uint8_t OperandType
Information about the type of the operand.
Definition: MCInstrDesc.h:79
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:406
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:161
unsigned short NumOperands
Definition: MCInstrDesc.h:166
This file contains the declaration of the WebAssembly-specific utility functions. ...
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
Address of a global value.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
unsigned const MachineRegisterInfo * MRI
This file provides signature information for runtime libcalls.
const WebAssemblySubtarget & getSubtarget() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const GlobalValue * getGlobal() const
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
double convertToDouble() const
Definition: APFloat.h:1097
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
Definition: MachineInstr.h:481
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
std::unique_ptr< wasm::WasmSignature > SignatureFromMVTs(const SmallVectorImpl< MVT > &Results, const SmallVectorImpl< MVT > &Params)
unsigned getNumOperands() const
Definition: MCInst.h:184
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
type signature immediate for call_indirect.
static wasm::ValType getType(const TargetRegisterClass *RC)
bool isDebugInstr() const
Definition: MachineInstr.h:999
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setType(wasm::WasmSymbolType type)
Definition: MCSymbolWasm.h:46
iterator_range< mop_iterator > explicit_uses()
Definition: MachineInstr.h:499
void addSignature(std::unique_ptr< wasm::WasmSignature > &&Sig)
const APFloat & getValueAPF() const
Definition: Constants.h:299
void Lower(const MachineInstr *MI, MCInst &OutMI) const
void GetLibcallSignature(const WebAssemblySubtarget &Subtarget, RTLIB::Libcall LC, SmallVectorImpl< wasm::ValType > &Rets, SmallVectorImpl< wasm::ValType > &Params)
void setOpcode(unsigned Op)
Definition: MCInst.h:173
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:428
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:182
static MCOperand createFPImm(double Val)
Definition: MCInst.h:130
int64_t getImm() const
const Function & getFunction() const
Return the LLVM function that this machine code represents.
void ComputeSignatureVTs(const FunctionType *Ty, const Function &F, const TargetMachine &TM, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:254
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:64
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:215
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
int64_t getOffset() const
Return the offset from the symbol in this operand.
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares WebAssembly-specific per-machine-function information.
Type * getValueType() const
Definition: GlobalValue.h:276
unsigned getWAReg(unsigned VReg) const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void setSignature(wasm::WasmSignature *Sig)
Definition: MCSymbolWasm.h:61
Floating-point immediate operand.
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:174
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:59
IRTranslator LLVM IR MI
void addOperand(const MCOperand &Op)
Definition: MCInst.h:186
bool isCallIndirect(const MachineInstr &MI)
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:67
unsigned getOpcode() const
Definition: MCInst.h:174
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:35
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:150
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
MCSymbol * createTempSymbol(const Twine &Name) const
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:123
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:164
bool isImplicit() const