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 "WebAssemblyMachineFunctionInfo.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
29 #define DEBUG_TYPE "asm-printer"
31 #include "WebAssemblyGenAsmWriter.inc"
33 WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
34 const MCInstrInfo &MII,
35 const MCRegisterInfo &MRI)
36 : MCInstPrinter(MAI, MII, MRI) {}
38 void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
39 unsigned RegNo) const {
40 assert(RegNo != WebAssemblyFunctionInfo::UnusedReg);
41 // Note that there's an implicit get_local/set_local here!
45 void WebAssemblyInstPrinter::printInst(const MCInst *MI, raw_ostream &OS,
47 const MCSubtargetInfo &STI) {
48 printInstruction(MI, OS);
50 const MCInstrDesc &Desc = MII.get(MI->getOpcode());
51 if (Desc.isVariadic())
52 for (unsigned i = Desc.getNumOperands(), e = MI->getNumOperands(); i < e;
55 printOperand(MI, i, OS);
58 printAnnotation(OS, Annot);
61 static std::string toString(const APFloat &FP) {
62 static const size_t BufBytes = 128;
65 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
67 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
68 "convertToHexString handles neither SNaN nor NaN payloads");
69 // Use C99's hexadecimal floating-point representation.
70 auto Written = FP.convertToHexString(
71 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
74 assert(Written < BufBytes);
78 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
80 const MCOperand &Op = MI->getOperand(OpNo);
82 unsigned WAReg = Op.getReg();
84 printRegName(O, WAReg);
85 else if (OpNo >= MII.get(MI->getOpcode()).getNumDefs())
86 O << "$pop" << (WAReg & INT32_MAX);
87 else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
88 O << "$push" << (WAReg & INT32_MAX);
91 } else if (Op.isImm())
93 else if (Op.isFPImm())
94 O << toString(APFloat(Op.getFPImm()));
96 assert(Op.isExpr() && "unknown operand kind in printOperand");
97 Op.getExpr()->print(O, &MAI);