1 //=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Print MCInst instructions to wasm format.
13 //===----------------------------------------------------------------------===//
15 #include "InstPrinter/WebAssemblyInstPrinter.h"
16 #include "WebAssembly.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCInstrInfo.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
28 #define DEBUG_TYPE "asm-printer"
30 #include "WebAssemblyGenAsmWriter.inc"
32 WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
33 const MCInstrInfo &MII,
34 const MCRegisterInfo &MRI)
35 : MCInstPrinter(MAI, MII, MRI) {}
37 void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
38 unsigned RegNo) const {
39 // FIXME: Revisit whether we actually print the get_local explicitly.
40 OS << "(get_local " << RegNo << ")";
43 void WebAssemblyInstPrinter::printInst(const MCInst *MI, raw_ostream &OS,
45 const MCSubtargetInfo &STI) {
46 printInstruction(MI, OS);
48 const MCInstrDesc &Desc = MII.get(MI->getOpcode());
49 if (Desc.isVariadic())
50 for (unsigned i = Desc.getNumOperands(), e = MI->getNumOperands(); i < e;
53 printOperand(MI, i, OS);
56 printAnnotation(OS, Annot);
58 unsigned NumDefs = MII.get(MI->getOpcode()).getNumDefs();
59 assert(NumDefs <= 1 &&
60 "Instructions with multiple result values not implemented");
62 // FIXME: Revisit whether we actually print the set_local explicitly.
65 "\t" "set_local " << MI->getOperand(0).getReg() << ", $pop";
68 static std::string toString(const APFloat &FP) {
69 static const size_t BufBytes = 128;
72 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
74 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
75 "convertToHexString handles neither SNaN nor NaN payloads");
76 // Use C99's hexadecimal floating-point representation.
77 auto Written = FP.convertToHexString(
78 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
81 assert(Written < BufBytes);
85 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
87 const MCOperand &Op = MI->getOperand(OpNo);
89 if (OpNo < MII.get(MI->getOpcode()).getNumDefs())
92 printRegName(O, Op.getReg());
93 } else if (Op.isImm())
95 else if (Op.isFPImm())
96 O << toString(APFloat(Op.getFPImm()));
98 assert(Op.isExpr() && "unknown operand kind in printOperand");
99 Op.getExpr()->print(O, &MAI);