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