LLVM  10.0.0
WebAssemblyInstPrinter.cpp
Go to the documentation of this file.
1 //=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
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 /// Print MCInst instructions to wasm format.
11 ///
12 //===----------------------------------------------------------------------===//
13 
16 #include "WebAssembly.h"
18 #include "WebAssemblyUtilities.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSymbol.h"
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "asm-printer"
32 
33 #include "WebAssemblyGenAsmWriter.inc"
34 
36  const MCInstrInfo &MII,
37  const MCRegisterInfo &MRI)
38  : MCInstPrinter(MAI, MII, MRI) {}
39 
41  unsigned RegNo) const {
43  // Note that there's an implicit local.get/local.set here!
44  OS << "$" << RegNo;
45 }
46 
48  StringRef Annot,
49  const MCSubtargetInfo &STI,
50  raw_ostream &OS) {
51  // Print the instruction (this uses the AsmStrings from the .td files).
52  printInstruction(MI, Address, OS);
53 
54  // Print any additional variadic operands.
55  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
56  if (Desc.isVariadic()) {
57  if (Desc.getNumOperands() == 0 && MI->getNumOperands() > 0)
58  OS << "\t";
59  for (auto I = Desc.getNumOperands(), E = MI->getNumOperands(); I < E; ++I) {
60  // FIXME: For CALL_INDIRECT_VOID, don't print a leading comma, because
61  // we have an extra flags operand which is not currently printed, for
62  // compatiblity reasons.
63  if (I != 0 && ((MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID &&
64  MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID_S) ||
65  I != Desc.getNumOperands()))
66  OS << ", ";
67  printOperand(MI, I, OS);
68  }
69  }
70 
71  // Print any added annotation.
72  printAnnotation(OS, Annot);
73 
74  if (CommentStream) {
75  // Observe any effects on the control flow stack, for use in annotating
76  // control flow label references.
77  unsigned Opc = MI->getOpcode();
78  switch (Opc) {
79  default:
80  break;
81 
82  case WebAssembly::LOOP:
83  case WebAssembly::LOOP_S:
84  printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
85  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
86  break;
87 
88  case WebAssembly::BLOCK:
89  case WebAssembly::BLOCK_S:
90  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
91  break;
92 
93  case WebAssembly::TRY:
94  case WebAssembly::TRY_S:
95  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
96  EHPadStack.push_back(EHPadStackCounter++);
97  LastSeenEHInst = TRY;
98  break;
99 
100  case WebAssembly::END_LOOP:
101  case WebAssembly::END_LOOP_S:
102  if (ControlFlowStack.empty()) {
103  printAnnotation(OS, "End marker mismatch!");
104  } else {
105  ControlFlowStack.pop_back();
106  }
107  break;
108 
110  case WebAssembly::END_BLOCK_S:
111  if (ControlFlowStack.empty()) {
112  printAnnotation(OS, "End marker mismatch!");
113  } else {
115  OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
116  }
117  break;
118 
119  case WebAssembly::END_TRY:
120  case WebAssembly::END_TRY_S:
121  if (ControlFlowStack.empty()) {
122  printAnnotation(OS, "End marker mismatch!");
123  } else {
125  OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
126  LastSeenEHInst = END_TRY;
127  }
128  break;
129 
130  case WebAssembly::CATCH:
131  case WebAssembly::CATCH_S:
132  if (EHPadStack.empty()) {
133  printAnnotation(OS, "try-catch mismatch!");
134  } else {
135  printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
136  }
137  break;
138  }
139 
140  // Annotate any control flow label references.
141 
142  // rethrow instruction does not take any depth argument and rethrows to the
143  // nearest enclosing catch scope, if any. If there's no enclosing catch
144  // scope, it throws up to the caller.
145  if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
146  if (EHPadStack.empty()) {
147  printAnnotation(OS, "to caller");
148  } else {
149  printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
150  }
151 
152  } else {
153  unsigned NumFixedOperands = Desc.NumOperands;
154  SmallSet<uint64_t, 8> Printed;
155  for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
156  // See if this operand denotes a basic block target.
157  if (I < NumFixedOperands) {
158  // A non-variable_ops operand, check its type.
160  continue;
161  } else {
162  // A variable_ops operand, which currently can be immediates (used in
163  // br_table) which are basic block targets, or for call instructions
164  // when using -wasm-keep-registers (in which case they are registers,
165  // and should not be processed).
166  if (!MI->getOperand(I).isImm())
167  continue;
168  }
169  uint64_t Depth = MI->getOperand(I).getImm();
170  if (!Printed.insert(Depth).second)
171  continue;
172  if (Depth >= ControlFlowStack.size()) {
173  printAnnotation(OS, "Invalid depth argument!");
174  } else {
175  const auto &Pair = ControlFlowStack.rbegin()[Depth];
176  printAnnotation(OS, utostr(Depth) + ": " +
177  (Pair.second ? "up" : "down") + " to label" +
178  utostr(Pair.first));
179  }
180  }
181  }
182  }
183 }
184 
185 static std::string toString(const APFloat &FP) {
186  // Print NaNs with custom payloads specially.
187  if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
188  !FP.bitwiseIsEqual(
189  APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
190  APInt AI = FP.bitcastToAPInt();
191  return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
192  utohexstr(AI.getZExtValue() &
193  (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
194  : INT64_C(0x000fffffffffffff)),
195  /*LowerCase=*/true);
196  }
197 
198  // Use C99's hexadecimal floating-point representation.
199  static const size_t BufBytes = 128;
200  char Buf[BufBytes];
201  auto Written = FP.convertToHexString(
202  Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
203  (void)Written;
204  assert(Written != 0);
205  assert(Written < BufBytes);
206  return Buf;
207 }
208 
209 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
210  raw_ostream &O) {
211  const MCOperand &Op = MI->getOperand(OpNo);
212  if (Op.isReg()) {
213  unsigned WAReg = Op.getReg();
214  if (int(WAReg) >= 0)
215  printRegName(O, WAReg);
216  else if (OpNo >= MII.get(MI->getOpcode()).getNumDefs())
217  O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
218  else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
219  O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
220  else
221  O << "$drop";
222  // Add a '=' suffix if this is a def.
223  if (OpNo < MII.get(MI->getOpcode()).getNumDefs())
224  O << '=';
225  } else if (Op.isImm()) {
226  O << Op.getImm();
227  } else if (Op.isFPImm()) {
228  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
229  const MCOperandInfo &Info = Desc.OpInfo[OpNo];
231  // TODO: MC converts all floating point immediate operands to double.
232  // This is fine for numeric values, but may cause NaNs to change bits.
233  O << ::toString(APFloat(float(Op.getFPImm())));
234  } else {
236  O << ::toString(APFloat(Op.getFPImm()));
237  }
238  } else {
239  assert(Op.isExpr() && "unknown operand kind in printOperand");
240  // call_indirect instructions have a TYPEINDEX operand that we print
241  // as a signature here, such that the assembler can recover this
242  // information.
243  auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
244  if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
245  auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
246  O << WebAssembly::signatureToString(Sym.getSignature());
247  } else {
248  Op.getExpr()->print(O, &MAI);
249  }
250  }
251 }
252 
253 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
254  raw_ostream &O) {
255  O << "{";
256  for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
257  if (I != OpNo)
258  O << ", ";
259  O << MI->getOperand(I).getImm();
260  }
261  O << "}";
262 }
263 
265  unsigned OpNo,
266  raw_ostream &O) {
267  int64_t Imm = MI->getOperand(OpNo).getImm();
268  if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
269  return;
270  O << ":p2align=" << Imm;
271 }
272 
274  unsigned OpNo,
275  raw_ostream &O) {
276  const MCOperand &Op = MI->getOperand(OpNo);
277  if (Op.isImm()) {
278  auto Imm = static_cast<unsigned>(Op.getImm());
279  if (Imm != wasm::WASM_TYPE_NORESULT)
281  } else {
282  auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
283  auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
284  if (Sym->getSignature()) {
285  O << WebAssembly::signatureToString(Sym->getSignature());
286  } else {
287  // Disassembler does not currently produce a signature
288  O << "unknown_type";
289  }
290  }
291 }
292 
293 // We have various enums representing a subset of these types, use this
294 // function to convert any of them to text.
295 const char *WebAssembly::anyTypeToString(unsigned Ty) {
296  switch (Ty) {
297  case wasm::WASM_TYPE_I32:
298  return "i32";
299  case wasm::WASM_TYPE_I64:
300  return "i64";
301  case wasm::WASM_TYPE_F32:
302  return "f32";
303  case wasm::WASM_TYPE_F64:
304  return "f64";
306  return "v128";
308  return "funcref";
310  return "func";
312  return "exnref";
314  return "void";
315  default:
316  return "invalid_type";
317  }
318 }
319 
321  return anyTypeToString(static_cast<unsigned>(Ty));
322 }
323 
325  std::string S;
326  for (auto &Ty : List) {
327  if (&Ty != &List[0]) S += ", ";
328  S += WebAssembly::typeToString(Ty);
329  }
330  return S;
331 }
332 
334  std::string S("(");
335  S += typeListToString(Sig->Params);
336  S += ") -> (";
337  S += typeListToString(Sig->Returns);
338  S += ")";
339  return S;
340 }
32-bit floating-point immediates.
void printWebAssemblySignatureOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
bool isImm() const
Definition: MCInst.h:58
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1620
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void push_back(const T &Elt)
Definition: SmallVector.h:211
This class prints an WebAssembly MCInst to wasm file syntax.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:188
void printWebAssemblyP2AlignOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
unsigned GetDefaultP2Align(unsigned Opc)
bool isReg() const
Definition: MCInst.h:57
void printInstruction(const MCInst *MI, uint64_t Address, raw_ostream &O)
void printRegName(raw_ostream &OS, unsigned RegNo) const override
Print the assembler register name.
Basic block label in a branch construct.
const char * anyTypeToString(unsigned Ty)
const fltSemantics & getSemantics() const
Definition: APFloat.h:1175
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
WebAssemblyInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1566
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:986
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:235
SmallVector< ValType, 1 > Returns
Definition: Wasm.h:357
std::string signatureToString(const wasm::WasmSignature *Sig)
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:169
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:64
SmallVector< ValType, 4 > Params
Definition: Wasm.h:358
uint8_t OperandType
Information about the type of the operand.
Definition: MCInstrDesc.h:87
void printBrList(const MCInst *MI, unsigned OpNo, raw_ostream &O)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
const MCExpr * getExpr() const
Definition: MCInst.h:95
Analysis containing CSE Info
Definition: CSEInfo.cpp:25
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
unsigned short NumOperands
Definition: MCInstrDesc.h:191
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
This file contains the declaration of the WebAssembly-specific utility functions. ...
int64_t getImm() const
Definition: MCInst.h:75
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:363
void printInst(const MCInst *MI, uint64_t Address, StringRef Annot, const MCSubtargetInfo &STI, raw_ostream &OS) override
Print the specified MCInst to the specified raw_ostream.
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:42
unsigned const MachineRegisterInfo * MRI
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:263
bool isNaN() const
Definition: APFloat.h:1165
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
bool isFPImm() const
Definition: MCInst.h:59
This file provides WebAssembly-specific target descriptions.
std::string typeListToString(ArrayRef< wasm::ValType > List)
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:23
bool isExpr() const
Definition: MCInst.h:60
unsigned getNumOperands() const
Definition: MCInst.h:182
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
size_t size() const
Definition: SmallVector.h:52
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:180
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
Definition: MCInstPrinter.h:47
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
Class for arbitrary precision integers.
Definition: APInt.h:69
64-bit floating-point immediates.
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition: APFloat.h:1157
const MCAsmInfo & MAI
Definition: MCInstPrinter.h:48
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:42
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
const NodeList & List
Definition: RDFGraph.cpp:201
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares WebAssembly-specific per-machine-function information.
Generic base class for all target subtargets.
const MCInstrInfo & MII
Definition: MCInstPrinter.h:49
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
bool bitwiseIsEqual(const APFloat &RHS) const
Definition: APFloat.h:1132
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:199
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
APInt bitcastToAPInt() const
Definition: APFloat.h:1114
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:75
unsigned getOpcode() const
Definition: MCInst.h:172
const char * typeToString(wasm::ValType Ty)
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:34
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:906
double getFPImm() const
Definition: MCInst.h:85
std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:124
static unsigned getWARegStackId(unsigned Reg)