LLVM  8.0.0svn
WebAssemblyInstPrinter.cpp
Go to the documentation of this file.
1 //=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
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 /// Print MCInst instructions to wasm format.
12 ///
13 //===----------------------------------------------------------------------===//
14 
17 #include "WebAssembly.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 get_local/set_local here!
44  OS << "$" << RegNo;
45 }
46 
48  StringRef Annot,
49  const MCSubtargetInfo &STI) {
50  // Print the instruction (this uses the AsmStrings from the .td files).
51  printInstruction(MI, OS);
52 
53  // Print any additional variadic operands.
54  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
55  if (Desc.isVariadic())
56  for (auto i = Desc.getNumOperands(), e = MI->getNumOperands(); i < e; ++i) {
57  // FIXME: For CALL_INDIRECT_VOID, don't print a leading comma, because
58  // we have an extra flags operand which is not currently printed, for
59  // compatiblity reasons.
60  if (i != 0 && ((MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID &&
61  MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID_S) ||
62  i != Desc.getNumOperands()))
63  OS << ", ";
64  printOperand(MI, i, OS);
65  }
66 
67  // Print any added annotation.
68  printAnnotation(OS, Annot);
69 
70  if (CommentStream) {
71  // Observe any effects on the control flow stack, for use in annotating
72  // control flow label references.
73  unsigned Opc = MI->getOpcode();
74  switch (Opc) {
75  default:
76  break;
77 
78  case WebAssembly::LOOP:
79  case WebAssembly::LOOP_S:
80  printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
81  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
82  break;
83 
84  case WebAssembly::BLOCK:
85  case WebAssembly::BLOCK_S:
86  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
87  break;
88 
89  case WebAssembly::TRY:
90  case WebAssembly::TRY_S:
91  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
92  EHPadStack.push_back(EHPadStackCounter++);
93  LastSeenEHInst = TRY;
94  break;
95 
96  case WebAssembly::END_LOOP:
97  case WebAssembly::END_LOOP_S:
98  assert(!ControlFlowStack.empty() && "End marker mismatch!");
99  ControlFlowStack.pop_back();
100  break;
101 
103  case WebAssembly::END_BLOCK_S:
104  assert(!ControlFlowStack.empty() && "End marker mismatch!");
106  OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
107  break;
108 
109  case WebAssembly::END_TRY:
110  case WebAssembly::END_TRY_S:
111  assert(!ControlFlowStack.empty() && "End marker mismatch!");
113  OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
114  LastSeenEHInst = END_TRY;
115  break;
116 
117  case WebAssembly::CATCH_I32:
118  case WebAssembly::CATCH_I32_S:
119  case WebAssembly::CATCH_I64:
120  case WebAssembly::CATCH_I64_S:
121  case WebAssembly::CATCH_ALL:
122  case WebAssembly::CATCH_ALL_S:
123  // There can be multiple catch instructions for one try instruction, so we
124  // print a label only for the first 'catch' label.
125  if (LastSeenEHInst != CATCH) {
126  assert(!EHPadStack.empty() && "try-catch mismatch!");
127  printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
128  }
129  LastSeenEHInst = CATCH;
130  break;
131  }
132 
133  // Annotate any control flow label references.
134  unsigned NumFixedOperands = Desc.NumOperands;
135  SmallSet<uint64_t, 8> Printed;
136  for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
137  if (!(i < NumFixedOperands
138  ? (Desc.OpInfo[i].OperandType ==
141  continue;
142  uint64_t Depth = MI->getOperand(i).getImm();
143  if (!Printed.insert(Depth).second)
144  continue;
145 
146  if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
147  assert(Depth <= EHPadStack.size() && "Invalid depth argument!");
148  if (Depth == EHPadStack.size()) {
149  // This can happen when rethrow instruction breaks out of all nests
150  // and throws up to the current function's caller.
151  printAnnotation(OS, utostr(Depth) + ": " + "to caller");
152  } else {
153  uint64_t CatchNo = EHPadStack.rbegin()[Depth];
154  printAnnotation(OS, utostr(Depth) + ": " + "down to catch" +
155  utostr(CatchNo));
156  }
157 
158  } else {
159  assert(Depth < ControlFlowStack.size() && "Invalid depth argument!");
160  const auto &Pair = ControlFlowStack.rbegin()[Depth];
161  printAnnotation(OS, utostr(Depth) + ": " +
162  (Pair.second ? "up" : "down") + " to label" +
163  utostr(Pair.first));
164  }
165  }
166  }
167 }
168 
169 static std::string toString(const APFloat &FP) {
170  // Print NaNs with custom payloads specially.
171  if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
172  !FP.bitwiseIsEqual(
173  APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
174  APInt AI = FP.bitcastToAPInt();
175  return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
176  utohexstr(AI.getZExtValue() &
177  (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
178  : INT64_C(0x000fffffffffffff)),
179  /*LowerCase=*/true);
180  }
181 
182  // Use C99's hexadecimal floating-point representation.
183  static const size_t BufBytes = 128;
184  char buf[BufBytes];
185  auto Written = FP.convertToHexString(
186  buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
187  (void)Written;
188  assert(Written != 0);
189  assert(Written < BufBytes);
190  return buf;
191 }
192 
193 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
194  raw_ostream &O) {
195  const MCOperand &Op = MI->getOperand(OpNo);
196  if (Op.isReg()) {
197  assert((OpNo < MII.get(MI->getOpcode()).getNumOperands() ||
198  MII.get(MI->getOpcode()).TSFlags == 0) &&
199  "WebAssembly variable_ops register ops don't use TSFlags");
200  unsigned WAReg = Op.getReg();
201  if (int(WAReg) >= 0)
202  printRegName(O, WAReg);
203  else if (OpNo >= MII.get(MI->getOpcode()).getNumDefs())
204  O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
205  else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
206  O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
207  else
208  O << "$drop";
209  // Add a '=' suffix if this is a def.
210  if (OpNo < MII.get(MI->getOpcode()).getNumDefs())
211  O << '=';
212  } else if (Op.isImm()) {
213  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
214  assert((OpNo < Desc.getNumOperands() ||
216  "WebAssemblyII::VariableOpIsImmediate should be set for "
217  "variable_ops immediate ops");
218  (void)Desc;
219  // TODO: (MII.get(MI->getOpcode()).TSFlags &
220  // WebAssemblyII::VariableOpImmediateIsLabel)
221  // can tell us whether this is an immediate referencing a label in the
222  // control flow stack, and it may be nice to pretty-print.
223  O << Op.getImm();
224  } else if (Op.isFPImm()) {
225  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
226  assert(OpNo < Desc.getNumOperands() &&
227  "Unexpected floating-point immediate as a non-fixed operand");
228  assert(Desc.TSFlags == 0 &&
229  "WebAssembly variable_ops floating point ops don't use TSFlags");
230  const MCOperandInfo &Info = Desc.OpInfo[OpNo];
232  // TODO: MC converts all floating point immediate operands to double.
233  // This is fine for numeric values, but may cause NaNs to change bits.
234  O << ::toString(APFloat(float(Op.getFPImm())));
235  } else {
237  O << ::toString(APFloat(Op.getFPImm()));
238  }
239  } else {
240  assert((OpNo < MII.get(MI->getOpcode()).getNumOperands() ||
241  (MII.get(MI->getOpcode()).TSFlags &
243  "WebAssemblyII::VariableOpIsImmediate should be set for "
244  "variable_ops expr ops");
245  assert(Op.isExpr() && "unknown operand kind in printOperand");
246  Op.getExpr()->print(O, &MAI);
247  }
248 }
249 
251  unsigned OpNo,
252  raw_ostream &O) {
253  int64_t Imm = MI->getOperand(OpNo).getImm();
254  if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
255  return;
256  O << ":p2align=" << Imm;
257 }
258 
260  unsigned OpNo,
261  raw_ostream &O) {
262  int64_t Imm = MI->getOperand(OpNo).getImm();
263  switch (WebAssembly::ExprType(Imm)) {
265  break;
267  O << "i32";
268  break;
270  O << "i64";
271  break;
273  O << "f32";
274  break;
276  O << "f64";
277  break;
279  O << "v128";
280  break;
282  O << "except_ref";
283  break;
284  }
285 }
286 
288  switch (Ty) {
289  case wasm::ValType::I32:
290  return "i32";
291  case wasm::ValType::I64:
292  return "i64";
293  case wasm::ValType::F32:
294  return "f32";
295  case wasm::ValType::F64:
296  return "f64";
297  case wasm::ValType::V128:
298  return "v128";
300  return "except_ref";
301  }
302  llvm_unreachable("Unknown wasm::ValType");
303 }
32-bit floating-point immediates.
void printWebAssemblySignatureOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
bool isImm() const
Definition: MCInst.h:59
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1563
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void push_back(const T &Elt)
Definition: SmallVector.h:218
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:164
void printWebAssemblyP2AlignOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
const char * TypeToString(wasm::ValType Ty)
bool isReg() const
Definition: MCInst.h:58
void printRegName(raw_ostream &OS, unsigned RegNo) const override
Print the assembler register name.
Basic block label in a branch construct.
const fltSemantics & getSemantics() const
Definition: APFloat.h:1155
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:1509
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:967
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:211
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:65
uint8_t OperandType
Information about the type of the operand.
Definition: MCInstrDesc.h:79
const MCExpr * getExpr() const
Definition: MCInst.h:96
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:161
unsigned short NumOperands
Definition: MCInstrDesc.h:167
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
int64_t getImm() const
Definition: MCInst.h:76
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:364
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:235
bool isNaN() const
Definition: APFloat.h:1145
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
bool isFPImm() const
Definition: MCInst.h:60
This file provides WebAssembly-specific target descriptions.
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:24
bool isExpr() const
Definition: MCInst.h:61
unsigned getNumOperands() const
Definition: MCInst.h:184
unsigned GetDefaultP2Align(unsigned Opcode)
Return the default p2align value for a load or store with the given opcode.
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:181
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void printInst(const MCInst *MI, raw_ostream &OS, StringRef Annot, const MCSubtargetInfo &STI) override
Print the specified MCInst to the specified raw_ostream.
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:182
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
ExprType
This is used to indicate block signatures.
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
Definition: MCInstPrinter.h:45
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:224
Class for arbitrary precision integers.
Definition: APInt.h:70
64-bit floating-point immediates.
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition: APFloat.h:1137
const MCAsmInfo & MAI
Definition: MCInstPrinter.h:46
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:40
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
This file declares WebAssembly-specific per-machine-function information.
Generic base class for all target subtargets.
const MCInstrInfo & MII
Definition: MCInstPrinter.h:47
void printInstruction(const MCInst *MI, raw_ostream &O)
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:1112
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:175
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:49
APInt bitcastToAPInt() const
Definition: APFloat.h:1094
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
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:35
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:886
double getFPImm() const
Definition: MCInst.h:86
std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:125
static unsigned getWARegStackId(unsigned Reg)