LLVM  10.0.0
WebAssemblyDisassembler.cpp
Go to the documentation of this file.
1 //==- WebAssemblyDisassembler.cpp - Disassembler for WebAssembly -*- C++ -*-==//
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 /// This file is part of the WebAssembly Disassembler.
11 ///
12 /// It contains code to translate the data produced by the decoder into
13 /// MCInsts.
14 ///
15 //===----------------------------------------------------------------------===//
16 
20 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/LEB128.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm-disassembler"
35 
37 
38 #include "WebAssemblyGenDisassemblerTables.inc"
39 
40 namespace {
41 static constexpr int WebAssemblyInstructionTableSize = 256;
42 
43 class WebAssemblyDisassembler final : public MCDisassembler {
44  std::unique_ptr<const MCInstrInfo> MCII;
45 
46  DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
47  ArrayRef<uint8_t> Bytes, uint64_t Address,
48  raw_ostream &CStream) const override;
49  DecodeStatus onSymbolStart(StringRef Name, uint64_t &Size,
50  ArrayRef<uint8_t> Bytes, uint64_t Address,
51  raw_ostream &CStream) const override;
52 
53 public:
54  WebAssemblyDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
55  std::unique_ptr<const MCInstrInfo> MCII)
56  : MCDisassembler(STI, Ctx), MCII(std::move(MCII)) {}
57 };
58 } // end anonymous namespace
59 
61  const MCSubtargetInfo &STI,
62  MCContext &Ctx) {
63  std::unique_ptr<const MCInstrInfo> MCII(T.createMCInstrInfo());
64  return new WebAssemblyDisassembler(STI, Ctx, std::move(MCII));
65 }
66 
67 extern "C" LLVM_EXTERNAL_VISIBILITY void
69  // Register the disassembler for each target.
74 }
75 
76 static int nextByte(ArrayRef<uint8_t> Bytes, uint64_t &Size) {
77  if (Size >= Bytes.size())
78  return -1;
79  auto V = Bytes[Size];
80  Size++;
81  return V;
82 }
83 
84 static bool nextLEB(int64_t &Val, ArrayRef<uint8_t> Bytes, uint64_t &Size,
85  bool Signed) {
86  unsigned N = 0;
87  const char *Error = nullptr;
88  Val = Signed ? decodeSLEB128(Bytes.data() + Size, &N,
89  Bytes.data() + Bytes.size(), &Error)
90  : static_cast<int64_t>(decodeULEB128(Bytes.data() + Size, &N,
91  Bytes.data() + Bytes.size(),
92  &Error));
93  if (Error)
94  return false;
95  Size += N;
96  return true;
97 }
98 
99 static bool parseLEBImmediate(MCInst &MI, uint64_t &Size,
100  ArrayRef<uint8_t> Bytes, bool Signed) {
101  int64_t Val;
102  if (!nextLEB(Val, Bytes, Size, Signed))
103  return false;
105  return true;
106 }
107 
108 template <typename T>
109 bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes) {
110  if (Size + sizeof(T) > Bytes.size())
111  return false;
112  T Val = support::endian::read<T, support::endianness::little, 1>(
113  Bytes.data() + Size);
114  Size += sizeof(T);
115  if (std::is_floating_point<T>::value) {
116  MI.addOperand(MCOperand::createFPImm(static_cast<double>(Val)));
117  } else {
118  MI.addOperand(MCOperand::createImm(static_cast<int64_t>(Val)));
119  }
120  return true;
121 }
122 
123 MCDisassembler::DecodeStatus WebAssemblyDisassembler::onSymbolStart(
124  StringRef Name, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t Address,
125  raw_ostream &CStream) const {
126  Size = 0;
127  if (Address == 0) {
128  // Start of a code section: we're parsing only the function count.
129  int64_t FunctionCount;
130  if (!nextLEB(FunctionCount, Bytes, Size, false))
131  return MCDisassembler::Fail;
132  outs() << " # " << FunctionCount << " functions in section.";
133  } else {
134  // Parse the start of a single function.
135  int64_t BodySize, LocalEntryCount;
136  if (!nextLEB(BodySize, Bytes, Size, false) ||
137  !nextLEB(LocalEntryCount, Bytes, Size, false))
138  return MCDisassembler::Fail;
139  if (LocalEntryCount) {
140  outs() << " .local ";
141  for (int64_t I = 0; I < LocalEntryCount; I++) {
142  int64_t Count, Type;
143  if (!nextLEB(Count, Bytes, Size, false) ||
144  !nextLEB(Type, Bytes, Size, false))
145  return MCDisassembler::Fail;
146  for (int64_t J = 0; J < Count; J++) {
147  if (I || J)
148  outs() << ", ";
150  }
151  }
152  }
153  }
154  outs() << "\n";
156 }
157 
158 MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
159  MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
160  raw_ostream &CS) const {
161  CommentStream = &CS;
162  Size = 0;
163  int Opc = nextByte(Bytes, Size);
164  if (Opc < 0)
165  return MCDisassembler::Fail;
166  const auto *WasmInst = &InstructionTable0[Opc];
167  // If this is a prefix byte, indirect to another table.
168  if (WasmInst->ET == ET_Prefix) {
169  WasmInst = nullptr;
170  // Linear search, so far only 2 entries.
171  for (auto PT = PrefixTable; PT->Table; PT++) {
172  if (PT->Prefix == Opc) {
173  WasmInst = PT->Table;
174  break;
175  }
176  }
177  if (!WasmInst)
178  return MCDisassembler::Fail;
179  int64_t PrefixedOpc;
180  if (!nextLEB(PrefixedOpc, Bytes, Size, false))
181  return MCDisassembler::Fail;
182  if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
183  return MCDisassembler::Fail;
184  WasmInst += PrefixedOpc;
185  }
186  if (WasmInst->ET == ET_Unused)
187  return MCDisassembler::Fail;
188  // At this point we must have a valid instruction to decode.
189  assert(WasmInst->ET == ET_Instruction);
190  MI.setOpcode(WasmInst->Opcode);
191  // Parse any operands.
192  for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
193  auto OT = OperandTable[WasmInst->OperandStart + OPI];
194  switch (OT) {
195  // ULEB operands:
205  if (!parseLEBImmediate(MI, Size, Bytes, false))
206  return MCDisassembler::Fail;
207  break;
208  }
209  // SLEB operands:
212  if (!parseLEBImmediate(MI, Size, Bytes, true))
213  return MCDisassembler::Fail;
214  break;
215  }
216  // block_type operands:
218  int64_t Val;
219  uint64_t PrevSize = Size;
220  if (!nextLEB(Val, Bytes, Size, true))
221  return MCDisassembler::Fail;
222  if (Val < 0) {
223  // Negative values are single septet value types or empty types
224  if (Size != PrevSize + 1) {
225  MI.addOperand(
227  } else {
228  MI.addOperand(MCOperand::createImm(Val & 0x7f));
229  }
230  } else {
231  // We don't have access to the signature, so create a symbol without one
232  MCSymbol *Sym = getContext().createTempSymbol("typeindex", true);
233  auto *WasmSym = cast<MCSymbolWasm>(Sym);
234  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
235  const MCExpr *Expr = MCSymbolRefExpr::create(
236  WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, getContext());
238  }
239  break;
240  }
241  // FP operands.
243  if (!parseImmediate<float>(MI, Size, Bytes))
244  return MCDisassembler::Fail;
245  break;
246  }
248  if (!parseImmediate<double>(MI, Size, Bytes))
249  return MCDisassembler::Fail;
250  break;
251  }
252  // Vector lane operands (not LEB encoded).
254  if (!parseImmediate<uint8_t>(MI, Size, Bytes))
255  return MCDisassembler::Fail;
256  break;
257  }
259  if (!parseImmediate<uint16_t>(MI, Size, Bytes))
260  return MCDisassembler::Fail;
261  break;
262  }
264  if (!parseImmediate<uint32_t>(MI, Size, Bytes))
265  return MCDisassembler::Fail;
266  break;
267  }
269  if (!parseImmediate<uint64_t>(MI, Size, Bytes))
270  return MCDisassembler::Fail;
271  break;
272  }
274  int64_t TargetTableLen;
275  if (!nextLEB(TargetTableLen, Bytes, Size, false))
276  return MCDisassembler::Fail;
277  for (int64_t I = 0; I < TargetTableLen; I++) {
278  if (!parseLEBImmediate(MI, Size, Bytes, false))
279  return MCDisassembler::Fail;
280  }
281  // Default case.
282  if (!parseLEBImmediate(MI, Size, Bytes, false))
283  return MCDisassembler::Fail;
284  break;
285  }
287  // The tablegen header currently does not have any register operands since
288  // we use only the stack (_S) instructions.
289  // If you hit this that probably means a bad instruction definition in
290  // tablegen.
291  llvm_unreachable("Register operand in WebAssemblyDisassembler");
292  default:
293  llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
294  }
295  }
297 }
32-bit floating-point immediates.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:329
This class represents lattice values for constants.
Definition: AllocatorList.h:23
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
DecodeStatus
Ternary decode status.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:136
Superclass for all disassemblers.
This class prints an WebAssembly MCInst to wasm file syntax.
32-bit unsigned memory offsets.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Basic block label in a branch construct.
const char * anyTypeToString(unsigned Ty)
static void RegisterMCDisassembler(Target &T, Target::MCDisassemblerCtorTy Fn)
RegisterMCDisassembler - Register a MCDisassembler implementation for the given target.
A list of branch targets for br_list.
This file registers the WebAssembly target.
signature immediate for block/loop.
int64_t decodeSLEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a SLEB128 value.
Definition: LEB128.h:161
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
Context object for machine code objects.
Definition: MCContext.h:65
static int nextByte(ArrayRef< uint8_t > Bytes, uint64_t &Size)
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
This file provides WebAssembly-specific target descriptions.
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:128
type signature immediate for call_indirect.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const T * data() const
Definition: ArrayRef.h:155
static bool nextLEB(int64_t &Val, ArrayRef< uint8_t > Bytes, uint64_t &Size, bool Signed)
void setOpcode(unsigned Op)
Definition: MCInst.h:171
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:130
static MCOperand createFPImm(double Val)
Definition: MCInst.h:129
Target - Wrapper for Target specific information.
64-bit floating-point immediates.
32-bit unsigned function indices.
static MCDisassembler * createWebAssemblyDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx)
p2align immediate for load and store address alignment.
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyDisassembler()
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Generic base class for all target subtargets.
static bool parseLEBImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes, bool Signed)
uint32_t Size
Definition: Profile.cpp:46
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
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
void addOperand(const MCOperand &Op)
Definition: MCInst.h:184
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
Target & getTheWebAssemblyTarget32()
Target & getTheWebAssemblyTarget64()
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:122
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)