WebAssemblyInstPrinter.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
  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. /// Print MCInst instructions to wasm format.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "MCTargetDesc/WebAssemblyInstPrinter.h"
  14. #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
  15. #include "WebAssembly.h"
  16. #include "WebAssemblyMachineFunctionInfo.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/CodeGen/TargetRegisterInfo.h"
  20. #include "llvm/MC/MCExpr.h"
  21. #include "llvm/MC/MCInst.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCSubtargetInfo.h"
  24. #include "llvm/MC/MCSymbol.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/FormattedStream.h"
  27. using namespace llvm;
  28. #define DEBUG_TYPE "asm-printer"
  29. #include "WebAssemblyGenAsmWriter.inc"
  30. WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
  31. const MCInstrInfo &MII,
  32. const MCRegisterInfo &MRI)
  33. : MCInstPrinter(MAI, MII, MRI) {}
  34. void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
  35. unsigned RegNo) const {
  36. assert(RegNo != WebAssemblyFunctionInfo::UnusedReg);
  37. // Note that there's an implicit local.get/local.set here!
  38. OS << "$" << RegNo;
  39. }
  40. void WebAssemblyInstPrinter::printInst(const MCInst *MI, raw_ostream &OS,
  41. StringRef Annot,
  42. const MCSubtargetInfo &STI) {
  43. // Print the instruction (this uses the AsmStrings from the .td files).
  44. printInstruction(MI, OS);
  45. // Print any additional variadic operands.
  46. const MCInstrDesc &Desc = MII.get(MI->getOpcode());
  47. if (Desc.isVariadic())
  48. for (auto I = Desc.getNumOperands(), E = MI->getNumOperands(); I < E; ++I) {
  49. // FIXME: For CALL_INDIRECT_VOID, don't print a leading comma, because
  50. // we have an extra flags operand which is not currently printed, for
  51. // compatiblity reasons.
  52. if (I != 0 && ((MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID &&
  53. MI->getOpcode() != WebAssembly::CALL_INDIRECT_VOID_S) ||
  54. I != Desc.getNumOperands()))
  55. OS << ", ";
  56. printOperand(MI, I, OS);
  57. }
  58. // Print any added annotation.
  59. printAnnotation(OS, Annot);
  60. if (CommentStream) {
  61. // Observe any effects on the control flow stack, for use in annotating
  62. // control flow label references.
  63. unsigned Opc = MI->getOpcode();
  64. switch (Opc) {
  65. default:
  66. break;
  67. case WebAssembly::LOOP:
  68. case WebAssembly::LOOP_S:
  69. printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
  70. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
  71. break;
  72. case WebAssembly::BLOCK:
  73. case WebAssembly::BLOCK_S:
  74. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
  75. break;
  76. case WebAssembly::TRY:
  77. case WebAssembly::TRY_S:
  78. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
  79. EHPadStack.push_back(EHPadStackCounter++);
  80. LastSeenEHInst = TRY;
  81. break;
  82. case WebAssembly::END_LOOP:
  83. case WebAssembly::END_LOOP_S:
  84. if (ControlFlowStack.empty()) {
  85. printAnnotation(OS, "End marker mismatch!");
  86. } else {
  87. ControlFlowStack.pop_back();
  88. }
  89. break;
  90. case WebAssembly::END_BLOCK:
  91. case WebAssembly::END_BLOCK_S:
  92. if (ControlFlowStack.empty()) {
  93. printAnnotation(OS, "End marker mismatch!");
  94. } else {
  95. printAnnotation(
  96. OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
  97. }
  98. break;
  99. case WebAssembly::END_TRY:
  100. case WebAssembly::END_TRY_S:
  101. if (ControlFlowStack.empty()) {
  102. printAnnotation(OS, "End marker mismatch!");
  103. } else {
  104. printAnnotation(
  105. OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
  106. LastSeenEHInst = END_TRY;
  107. }
  108. break;
  109. case WebAssembly::CATCH:
  110. case WebAssembly::CATCH_S:
  111. if (EHPadStack.empty()) {
  112. printAnnotation(OS, "try-catch mismatch!");
  113. } else {
  114. printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
  115. }
  116. break;
  117. }
  118. // Annotate any control flow label references.
  119. // rethrow instruction does not take any depth argument and rethrows to the
  120. // nearest enclosing catch scope, if any. If there's no enclosing catch
  121. // scope, it throws up to the caller.
  122. if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
  123. if (EHPadStack.empty()) {
  124. printAnnotation(OS, "to caller");
  125. } else {
  126. printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
  127. }
  128. } else {
  129. unsigned NumFixedOperands = Desc.NumOperands;
  130. SmallSet<uint64_t, 8> Printed;
  131. for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
  132. // See if this operand denotes a basic block target.
  133. if (I < NumFixedOperands) {
  134. // A non-variable_ops operand, check its type.
  135. if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
  136. continue;
  137. } else {
  138. // A variable_ops operand, which currently can be immediates (used in
  139. // br_table) which are basic block targets, or for call instructions
  140. // when using -wasm-keep-registers (in which case they are registers,
  141. // and should not be processed).
  142. if (!MI->getOperand(I).isImm())
  143. continue;
  144. }
  145. uint64_t Depth = MI->getOperand(I).getImm();
  146. if (!Printed.insert(Depth).second)
  147. continue;
  148. if (Depth >= ControlFlowStack.size()) {
  149. printAnnotation(OS, "Invalid depth argument!");
  150. } else {
  151. const auto &Pair = ControlFlowStack.rbegin()[Depth];
  152. printAnnotation(OS, utostr(Depth) + ": " +
  153. (Pair.second ? "up" : "down") + " to label" +
  154. utostr(Pair.first));
  155. }
  156. }
  157. }
  158. }
  159. }
  160. static std::string toString(const APFloat &FP) {
  161. // Print NaNs with custom payloads specially.
  162. if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
  163. !FP.bitwiseIsEqual(
  164. APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
  165. APInt AI = FP.bitcastToAPInt();
  166. return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
  167. utohexstr(AI.getZExtValue() &
  168. (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
  169. : INT64_C(0x000fffffffffffff)),
  170. /*LowerCase=*/true);
  171. }
  172. // Use C99's hexadecimal floating-point representation.
  173. static const size_t BufBytes = 128;
  174. char Buf[BufBytes];
  175. auto Written = FP.convertToHexString(
  176. Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
  177. (void)Written;
  178. assert(Written != 0);
  179. assert(Written < BufBytes);
  180. return Buf;
  181. }
  182. void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
  183. raw_ostream &O) {
  184. const MCOperand &Op = MI->getOperand(OpNo);
  185. if (Op.isReg()) {
  186. unsigned WAReg = Op.getReg();
  187. if (int(WAReg) >= 0)
  188. printRegName(O, WAReg);
  189. else if (OpNo >= MII.get(MI->getOpcode()).getNumDefs())
  190. O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
  191. else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
  192. O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
  193. else
  194. O << "$drop";
  195. // Add a '=' suffix if this is a def.
  196. if (OpNo < MII.get(MI->getOpcode()).getNumDefs())
  197. O << '=';
  198. } else if (Op.isImm()) {
  199. O << Op.getImm();
  200. } else if (Op.isFPImm()) {
  201. const MCInstrDesc &Desc = MII.get(MI->getOpcode());
  202. const MCOperandInfo &Info = Desc.OpInfo[OpNo];
  203. if (Info.OperandType == WebAssembly::OPERAND_F32IMM) {
  204. // TODO: MC converts all floating point immediate operands to double.
  205. // This is fine for numeric values, but may cause NaNs to change bits.
  206. O << ::toString(APFloat(float(Op.getFPImm())));
  207. } else {
  208. assert(Info.OperandType == WebAssembly::OPERAND_F64IMM);
  209. O << ::toString(APFloat(Op.getFPImm()));
  210. }
  211. } else {
  212. assert(Op.isExpr() && "unknown operand kind in printOperand");
  213. Op.getExpr()->print(O, &MAI);
  214. }
  215. }
  216. void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
  217. raw_ostream &O) {
  218. O << "{";
  219. for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
  220. if (I != OpNo)
  221. O << ", ";
  222. O << MI->getOperand(I).getImm();
  223. }
  224. O << "}";
  225. }
  226. void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
  227. unsigned OpNo,
  228. raw_ostream &O) {
  229. int64_t Imm = MI->getOperand(OpNo).getImm();
  230. if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
  231. return;
  232. O << ":p2align=" << Imm;
  233. }
  234. void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
  235. unsigned OpNo,
  236. raw_ostream &O) {
  237. auto Imm = static_cast<unsigned>(MI->getOperand(OpNo).getImm());
  238. if (Imm != wasm::WASM_TYPE_NORESULT)
  239. O << WebAssembly::anyTypeToString(Imm);
  240. }
  241. // We have various enums representing a subset of these types, use this
  242. // function to convert any of them to text.
  243. const char *llvm::WebAssembly::anyTypeToString(unsigned Ty) {
  244. switch (Ty) {
  245. case wasm::WASM_TYPE_I32:
  246. return "i32";
  247. case wasm::WASM_TYPE_I64:
  248. return "i64";
  249. case wasm::WASM_TYPE_F32:
  250. return "f32";
  251. case wasm::WASM_TYPE_F64:
  252. return "f64";
  253. case wasm::WASM_TYPE_V128:
  254. return "v128";
  255. case wasm::WASM_TYPE_FUNCREF:
  256. return "funcref";
  257. case wasm::WASM_TYPE_FUNC:
  258. return "func";
  259. case wasm::WASM_TYPE_EXNREF:
  260. return "exnref";
  261. case wasm::WASM_TYPE_NORESULT:
  262. return "void";
  263. default:
  264. return "invalid_type";
  265. }
  266. }
  267. const char *llvm::WebAssembly::typeToString(wasm::ValType Ty) {
  268. return anyTypeToString(static_cast<unsigned>(Ty));
  269. }