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         Desc.variadicOpsAreDefs())
59       OS << "\t";
60     unsigned Start = Desc.getNumOperands();
61     unsigned NumVariadicDefs = 0;
62     if (Desc.variadicOpsAreDefs()) {
63       // The number of variadic defs is encoded in an immediate by MCInstLower
64       NumVariadicDefs = MI->getOperand(0).getImm();
65       Start = 1;
66     }
67     bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs();
68     for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) {
69       if (MI->getOpcode() == WebAssembly::CALL_INDIRECT &&
70           I - Start == NumVariadicDefs) {
71         // Skip type and flags arguments when printing for tests
72         ++I;
73         continue;
74       }
75       if (NeedsComma)
76         OS << ", ";
77       printOperand(MI, I, OS, I - Start < NumVariadicDefs);
78       NeedsComma = true;
79     }
80   }
81 
82   // Print any added annotation.
83   printAnnotation(OS, Annot);
84 
85   if (CommentStream) {
86     // Observe any effects on the control flow stack, for use in annotating
87     // control flow label references.
88     unsigned Opc = MI->getOpcode();
89     switch (Opc) {
90     default:
91       break;
92 
93     case WebAssembly::LOOP:
94     case WebAssembly::LOOP_S:
95       printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
96       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
97       return;
98 
99     case WebAssembly::BLOCK:
100     case WebAssembly::BLOCK_S:
101       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
102       return;
103 
104     case WebAssembly::TRY:
105     case WebAssembly::TRY_S:
106       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));
107       EHPadStack.push_back(ControlFlowCounter++);
108       return;
109 
110     case WebAssembly::END_LOOP:
111     case WebAssembly::END_LOOP_S:
112       if (ControlFlowStack.empty()) {
113         printAnnotation(OS, "End marker mismatch!");
114       } else {
115         ControlFlowStack.pop_back();
116       }
117       return;
118 
119     case WebAssembly::END_BLOCK:
120     case WebAssembly::END_BLOCK_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       }
127       return;
128 
129     case WebAssembly::END_TRY:
130     case WebAssembly::END_TRY_S:
131       if (ControlFlowStack.empty()) {
132         printAnnotation(OS, "End marker mismatch!");
133       } else {
134         printAnnotation(
135             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
136       }
137       return;
138 
139     case WebAssembly::CATCH:
140     case WebAssembly::CATCH_S:
141     case WebAssembly::CATCH_ALL:
142     case WebAssembly::CATCH_ALL_S:
143       if (EHPadStack.empty()) {
144         printAnnotation(OS, "try-catch mismatch!");
145       } else {
146         printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
147       }
148       return;
149 
150     case WebAssembly::RETHROW:
151     case WebAssembly::RETHROW_S:
152       // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If
153       // there's no enclosing catch scope, it throws up to the caller.
154       if (EHPadStack.empty()) {
155         printAnnotation(OS, "to caller");
156       } else {
157         printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
158       }
159       return;
160     }
161 
162     // Annotate any control flow label references.
163 
164     unsigned NumFixedOperands = Desc.NumOperands;
165     SmallSet<uint64_t, 8> Printed;
166     for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
167       // See if this operand denotes a basic block target.
168       if (I < NumFixedOperands) {
169         // A non-variable_ops operand, check its type.
170         if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
171           continue;
172       } else {
173         // A variable_ops operand, which currently can be immediates (used in
174         // br_table) which are basic block targets, or for call instructions
175         // when using -wasm-keep-registers (in which case they are registers,
176         // and should not be processed).
177         if (!MI->getOperand(I).isImm())
178           continue;
179       }
180       uint64_t Depth = MI->getOperand(I).getImm();
181       if (!Printed.insert(Depth).second)
182         continue;
183       if (Depth >= ControlFlowStack.size()) {
184         printAnnotation(OS, "Invalid depth argument!");
185       } else {
186         const auto &Pair = ControlFlowStack.rbegin()[Depth];
187         printAnnotation(OS, utostr(Depth) + ": " +
188                                 (Pair.second ? "up" : "down") + " to label" +
189                                 utostr(Pair.first));
190       }
191     }
192   }
193 }
194 
195 static std::string toString(const APFloat &FP) {
196   // Print NaNs with custom payloads specially.
197   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
198       !FP.bitwiseIsEqual(
199           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
200     APInt AI = FP.bitcastToAPInt();
201     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
202            utohexstr(AI.getZExtValue() &
203                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
204                                                  : INT64_C(0x000fffffffffffff)),
205                      /*LowerCase=*/true);
206   }
207 
208   // Use C99's hexadecimal floating-point representation.
209   static const size_t BufBytes = 128;
210   char Buf[BufBytes];
211   auto Written = FP.convertToHexString(
212       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
213   (void)Written;
214   assert(Written != 0);
215   assert(Written < BufBytes);
216   return Buf;
217 }
218 
219 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
220                                           raw_ostream &O, bool IsVariadicDef) {
221   const MCOperand &Op = MI->getOperand(OpNo);
222   if (Op.isReg()) {
223     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
224     unsigned WAReg = Op.getReg();
225     if (int(WAReg) >= 0)
226       printRegName(O, WAReg);
227     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
228       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
229     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
230       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
231     else
232       O << "$drop";
233     // Add a '=' suffix if this is a def.
234     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
235       O << '=';
236   } else if (Op.isImm()) {
237     O << Op.getImm();
238   } else if (Op.isSFPImm()) {
239     O << ::toString(APFloat(bit_cast<float>(Op.getSFPImm())));
240   } else if (Op.isDFPImm()) {
241     O << ::toString(APFloat(bit_cast<double>(Op.getDFPImm())));
242   } else {
243     assert(Op.isExpr() && "unknown operand kind in printOperand");
244     // call_indirect instructions have a TYPEINDEX operand that we print
245     // as a signature here, such that the assembler can recover this
246     // information.
247     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
248     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
249       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
250       O << WebAssembly::signatureToString(Sym.getSignature());
251     } else {
252       Op.getExpr()->print(O, &MAI);
253     }
254   }
255 }
256 
257 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
258                                          raw_ostream &O) {
259   O << "{";
260   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
261     if (I != OpNo)
262       O << ", ";
263     O << MI->getOperand(I).getImm();
264   }
265   O << "}";
266 }
267 
268 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
269                                                             unsigned OpNo,
270                                                             raw_ostream &O) {
271   int64_t Imm = MI->getOperand(OpNo).getImm();
272   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
273     return;
274   O << ":p2align=" << Imm;
275 }
276 
277 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
278                                                               unsigned OpNo,
279                                                               raw_ostream &O) {
280   const MCOperand &Op = MI->getOperand(OpNo);
281   if (Op.isImm()) {
282     auto Imm = static_cast<unsigned>(Op.getImm());
283     if (Imm != wasm::WASM_TYPE_NORESULT)
284       O << WebAssembly::anyTypeToString(Imm);
285   } else {
286     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
287     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
288     if (Sym->getSignature()) {
289       O << WebAssembly::signatureToString(Sym->getSignature());
290     } else {
291       // Disassembler does not currently produce a signature
292       O << "unknown_type";
293     }
294   }
295 }
296 
297 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
298                                                              unsigned OpNo,
299                                                              raw_ostream &O) {
300   const MCOperand &Op = MI->getOperand(OpNo);
301   if (Op.isImm()) {
302     switch (Op.getImm()) {
303     case long(wasm::ValType::EXTERNREF):
304       O << "extern";
305       break;
306     case long(wasm::ValType::FUNCREF):
307       O << "func";
308       break;
309     default:
310       O << "unsupported_heap_type_value";
311       break;
312     }
313   } else {
314     // Typed function references and other subtypes of funcref and externref
315     // currently unimplemented.
316     O << "unsupported_heap_type_operand";
317   }
318 }
319 
320 // We have various enums representing a subset of these types, use this
321 // function to convert any of them to text.
322 const char *WebAssembly::anyTypeToString(unsigned Ty) {
323   switch (Ty) {
324   case wasm::WASM_TYPE_I32:
325     return "i32";
326   case wasm::WASM_TYPE_I64:
327     return "i64";
328   case wasm::WASM_TYPE_F32:
329     return "f32";
330   case wasm::WASM_TYPE_F64:
331     return "f64";
332   case wasm::WASM_TYPE_V128:
333     return "v128";
334   case wasm::WASM_TYPE_FUNCREF:
335     return "funcref";
336   case wasm::WASM_TYPE_EXTERNREF:
337     return "externref";
338   case wasm::WASM_TYPE_FUNC:
339     return "func";
340   case wasm::WASM_TYPE_NORESULT:
341     return "void";
342   default:
343     return "invalid_type";
344   }
345 }
346 
347 const char *WebAssembly::typeToString(wasm::ValType Ty) {
348   return anyTypeToString(static_cast<unsigned>(Ty));
349 }
350 
351 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
352   std::string S;
353   for (auto &Ty : List) {
354     if (&Ty != &List[0]) S += ", ";
355     S += WebAssembly::typeToString(Ty);
356   }
357   return S;
358 }
359 
360 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
361   std::string S("(");
362   S += typeListToString(Sig->Params);
363   S += ") -> (";
364   S += typeListToString(Sig->Returns);
365   S += ")";
366   return S;
367 }
368