LLVM  6.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 /// \brief 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), ControlFlowCounter(0) {}
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 &&
61  (MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID ||
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  switch (MI->getOpcode()) {
74  default:
75  break;
76  case WebAssembly::LOOP: {
77  printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
78  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
79  break;
80  }
81  case WebAssembly::BLOCK:
82  ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
83  break;
84  case WebAssembly::END_LOOP:
85  ControlFlowStack.pop_back();
86  break;
89  OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
90  break;
91  }
92 
93  // Annotate any control flow label references.
94  unsigned NumFixedOperands = Desc.NumOperands;
95  SmallSet<uint64_t, 8> Printed;
96  for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
97  if (!(i < NumFixedOperands
98  ? (Desc.OpInfo[i].OperandType ==
101  continue;
102  uint64_t Depth = MI->getOperand(i).getImm();
103  if (!Printed.insert(Depth).second)
104  continue;
105  const auto &Pair = ControlFlowStack.rbegin()[Depth];
106  printAnnotation(OS, utostr(Depth) + ": " + (Pair.second ? "up" : "down") +
107  " to label" + utostr(Pair.first));
108  }
109  }
110 }
111 
112 static std::string toString(const APFloat &FP) {
113  // Print NaNs with custom payloads specially.
114  if (FP.isNaN() &&
116  !FP.bitwiseIsEqual(
117  APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
118  APInt AI = FP.bitcastToAPInt();
119  return
120  std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
121  utohexstr(AI.getZExtValue() &
122  (AI.getBitWidth() == 32 ? INT64_C(0x007fffff) :
123  INT64_C(0x000fffffffffffff)),
124  /*LowerCase=*/true);
125  }
126 
127  // Use C99's hexadecimal floating-point representation.
128  static const size_t BufBytes = 128;
129  char buf[BufBytes];
130  auto Written = FP.convertToHexString(
131  buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
132  (void)Written;
133  assert(Written != 0);
134  assert(Written < BufBytes);
135  return buf;
136 }
137 
138 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
139  raw_ostream &O) {
140  const MCOperand &Op = MI->getOperand(OpNo);
141  if (Op.isReg()) {
142  assert((OpNo < MII.get(MI->getOpcode()).getNumOperands() ||
143  MII.get(MI->getOpcode()).TSFlags == 0) &&
144  "WebAssembly variable_ops register ops don't use TSFlags");
145  unsigned WAReg = Op.getReg();
146  if (int(WAReg) >= 0)
147  printRegName(O, WAReg);
148  else if (OpNo >= MII.get(MI->getOpcode()).getNumDefs())
149  O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
150  else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
151  O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
152  else
153  O << "$drop";
154  // Add a '=' suffix if this is a def.
155  if (OpNo < MII.get(MI->getOpcode()).getNumDefs())
156  O << '=';
157  } else if (Op.isImm()) {
158  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
159  assert((OpNo < Desc.getNumOperands() ||
161  "WebAssemblyII::VariableOpIsImmediate should be set for "
162  "variable_ops immediate ops");
163  (void)Desc;
164  // TODO: (MII.get(MI->getOpcode()).TSFlags &
165  // WebAssemblyII::VariableOpImmediateIsLabel)
166  // can tell us whether this is an immediate referencing a label in the
167  // control flow stack, and it may be nice to pretty-print.
168  O << Op.getImm();
169  } else if (Op.isFPImm()) {
170  const MCInstrDesc &Desc = MII.get(MI->getOpcode());
171  assert(OpNo < Desc.getNumOperands() &&
172  "Unexpected floating-point immediate as a non-fixed operand");
173  assert(Desc.TSFlags == 0 &&
174  "WebAssembly variable_ops floating point ops don't use TSFlags");
175  const MCOperandInfo &Info = Desc.OpInfo[OpNo];
177  // TODO: MC converts all floating point immediate operands to double.
178  // This is fine for numeric values, but may cause NaNs to change bits.
179  O << toString(APFloat(float(Op.getFPImm())));
180  } else {
182  O << toString(APFloat(Op.getFPImm()));
183  }
184  } else {
185  assert((OpNo < MII.get(MI->getOpcode()).getNumOperands() ||
186  (MII.get(MI->getOpcode()).TSFlags &
188  "WebAssemblyII::VariableOpIsImmediate should be set for "
189  "variable_ops expr ops");
190  assert(Op.isExpr() && "unknown operand kind in printOperand");
191  Op.getExpr()->print(O, &MAI);
192  }
193 }
194 
195 void
197  unsigned OpNo,
198  raw_ostream &O) {
199  int64_t Imm = MI->getOperand(OpNo).getImm();
200  if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
201  return;
202  O << ":p2align=" << Imm;
203 }
204 
205 void
207  unsigned OpNo,
208  raw_ostream &O) {
209  int64_t Imm = MI->getOperand(OpNo).getImm();
210  switch (WebAssembly::ExprType(Imm)) {
211  case WebAssembly::ExprType::Void: break;
212  case WebAssembly::ExprType::I32: O << "i32"; break;
213  case WebAssembly::ExprType::I64: O << "i64"; break;
214  case WebAssembly::ExprType::F32: O << "f32"; break;
215  case WebAssembly::ExprType::F64: O << "f64"; break;
216  case WebAssembly::ExprType::I8x16: O << "i8x16"; break;
217  case WebAssembly::ExprType::I16x8: O << "i16x8"; break;
218  case WebAssembly::ExprType::I32x4: O << "i32x4"; break;
219  case WebAssembly::ExprType::F32x4: O << "f32x4"; break;
220  case WebAssembly::ExprType::B8x16: O << "b8x16"; break;
221  case WebAssembly::ExprType::B16x8: O << "b16x8"; break;
222  case WebAssembly::ExprType::B32x4: O << "b32x4"; break;
223  }
224 }
225 
227  switch (Ty.SimpleTy) {
228  case MVT::i32:
229  return "i32";
230  case MVT::i64:
231  return "i64";
232  case MVT::f32:
233  return "f32";
234  case MVT::f64:
235  return "f64";
236  case MVT::v16i8:
237  case MVT::v8i16:
238  case MVT::v4i32:
239  case MVT::v4f32:
240  return "v128";
241  default:
242  llvm_unreachable("unsupported type");
243  }
244 }
245 
247  switch (Type) {
248  case wasm::ValType::I32:
249  return "i32";
250  case wasm::ValType::I64:
251  return "i64";
252  case wasm::ValType::F32:
253  return "f32";
254  case wasm::ValType::F64:
255  return "f64";
256  }
257  llvm_unreachable("unsupported type");
258 }
32-bit floating-point immediates.
void printWebAssemblySignatureOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void push_back(const T &Elt)
Definition: SmallVector.h:212
bool isImm() const
Definition: MCInst.h:59
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1542
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
const char * TypeToString(MVT Ty)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
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:163
void printWebAssemblyP2AlignOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
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:1488
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:947
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
SimpleValueType SimpleTy
ExprType
This is used to indicate block signatures.
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:65
uint8_t OperandType
Information about the type of the operand.
Definition: MCInstrDesc.h:82
const MCExpr * getExpr() const
Definition: MCInst.h:96
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:159
unsigned short NumOperands
Definition: MCInstrDesc.h:166
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:357
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:40
unsigned const MachineRegisterInfo * MRI
Machine Value Type.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:234
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:36
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:182
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:81
#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:180
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:385
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
Definition: MCInstPrinter.h:46
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:174
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:1137
const MCAsmInfo & MAI
Definition: MCInstPrinter.h:47
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:41
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.
MCSubtargetInfo - Generic base class for all target subtargets.
const MCInstrInfo & MII
Definition: MCInstPrinter.h:48
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:174
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
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:70
unsigned getOpcode() const
Definition: MCInst.h:172
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:76
static unsigned getWARegStackId(unsigned Reg)