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       EHInstStack.push_back(TRY);
109       return;
110 
111     case WebAssembly::END_LOOP:
112     case WebAssembly::END_LOOP_S:
113       if (ControlFlowStack.empty()) {
114         printAnnotation(OS, "End marker mismatch!");
115       } else {
116         ControlFlowStack.pop_back();
117       }
118       return;
119 
120     case WebAssembly::END_BLOCK:
121     case WebAssembly::END_BLOCK_S:
122       if (ControlFlowStack.empty()) {
123         printAnnotation(OS, "End marker mismatch!");
124       } else {
125         printAnnotation(
126             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
127       }
128       return;
129 
130     case WebAssembly::END_TRY:
131     case WebAssembly::END_TRY_S:
132       if (ControlFlowStack.empty() || EHInstStack.empty()) {
133         printAnnotation(OS, "End marker mismatch!");
134       } else {
135         printAnnotation(
136             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
137         EHInstStack.pop_back();
138       }
139       return;
140 
141     case WebAssembly::CATCH:
142     case WebAssembly::CATCH_S:
143     case WebAssembly::CATCH_ALL:
144     case WebAssembly::CATCH_ALL_S:
145       // There can be multiple catch instructions for one try instruction, so
146       // we print a label only for the first 'catch' label.
147       if (EHInstStack.empty()) {
148         printAnnotation(OS, "try-catch mismatch!");
149       } else if (EHInstStack.back() == CATCH_ALL) {
150         printAnnotation(OS, "catch/catch_all cannot occur after catch_all");
151       } else if (EHInstStack.back() == TRY) {
152         if (EHPadStack.empty()) {
153           printAnnotation(OS, "try-catch mismatch!");
154         } else {
155           printAnnotation(OS,
156                           "catch" + utostr(EHPadStack.pop_back_val()) + ':');
157         }
158         EHInstStack.pop_back();
159         if (Opc == WebAssembly::CATCH || Opc == WebAssembly::CATCH_S) {
160           EHInstStack.push_back(CATCH);
161         } else {
162           EHInstStack.push_back(CATCH_ALL);
163         }
164       }
165       return;
166 
167     case WebAssembly::RETHROW:
168     case WebAssembly::RETHROW_S:
169       // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If
170       // there's no enclosing catch scope, it throws up to the caller.
171       if (EHPadStack.empty()) {
172         printAnnotation(OS, "to caller");
173       } else {
174         printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
175       }
176       return;
177 
178     case WebAssembly::DELEGATE:
179     case WebAssembly::DELEGATE_S:
180       if (ControlFlowStack.empty() || EHPadStack.empty() ||
181           EHInstStack.empty()) {
182         printAnnotation(OS, "try-delegate mismatch!");
183       } else {
184         // 'delegate' is
185         // 1. A marker for the end of block label
186         // 2. A destination for throwing instructions
187         // 3. An instruction that itself rethrows to another 'catch'
188         assert(ControlFlowStack.back().first == EHPadStack.back());
189         std::string Label = "label/catch" +
190                             utostr(ControlFlowStack.pop_back_val().first) +
191                             ": ";
192         EHPadStack.pop_back();
193         EHInstStack.pop_back();
194         uint64_t Depth = MI->getOperand(0).getImm();
195         if (Depth >= ControlFlowStack.size()) {
196           Label += "to caller";
197         } else {
198           const auto &Pair = ControlFlowStack.rbegin()[Depth];
199           if (Pair.second)
200             printAnnotation(OS, "delegate cannot target a loop");
201           else
202             Label += "down to catch" + utostr(Pair.first);
203         }
204         printAnnotation(OS, Label);
205       }
206       return;
207     }
208 
209     // Annotate any control flow label references.
210 
211     unsigned NumFixedOperands = Desc.NumOperands;
212     SmallSet<uint64_t, 8> Printed;
213     for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
214       // See if this operand denotes a basic block target.
215       if (I < NumFixedOperands) {
216         // A non-variable_ops operand, check its type.
217         if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
218           continue;
219       } else {
220         // A variable_ops operand, which currently can be immediates (used in
221         // br_table) which are basic block targets, or for call instructions
222         // when using -wasm-keep-registers (in which case they are registers,
223         // and should not be processed).
224         if (!MI->getOperand(I).isImm())
225           continue;
226       }
227       uint64_t Depth = MI->getOperand(I).getImm();
228       if (!Printed.insert(Depth).second)
229         continue;
230       if (Depth >= ControlFlowStack.size()) {
231         printAnnotation(OS, "Invalid depth argument!");
232       } else {
233         const auto &Pair = ControlFlowStack.rbegin()[Depth];
234         printAnnotation(OS, utostr(Depth) + ": " +
235                                 (Pair.second ? "up" : "down") + " to label" +
236                                 utostr(Pair.first));
237       }
238     }
239   }
240 }
241 
242 static std::string toString(const APFloat &FP) {
243   // Print NaNs with custom payloads specially.
244   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
245       !FP.bitwiseIsEqual(
246           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
247     APInt AI = FP.bitcastToAPInt();
248     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
249            utohexstr(AI.getZExtValue() &
250                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
251                                                  : INT64_C(0x000fffffffffffff)),
252                      /*LowerCase=*/true);
253   }
254 
255   // Use C99's hexadecimal floating-point representation.
256   static const size_t BufBytes = 128;
257   char Buf[BufBytes];
258   auto Written = FP.convertToHexString(
259       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
260   (void)Written;
261   assert(Written != 0);
262   assert(Written < BufBytes);
263   return Buf;
264 }
265 
266 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
267                                           raw_ostream &O, bool IsVariadicDef) {
268   const MCOperand &Op = MI->getOperand(OpNo);
269   if (Op.isReg()) {
270     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
271     unsigned WAReg = Op.getReg();
272     if (int(WAReg) >= 0)
273       printRegName(O, WAReg);
274     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
275       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
276     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
277       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
278     else
279       O << "$drop";
280     // Add a '=' suffix if this is a def.
281     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
282       O << '=';
283   } else if (Op.isImm()) {
284     O << Op.getImm();
285   } else if (Op.isSFPImm()) {
286     O << ::toString(APFloat(bit_cast<float>(Op.getSFPImm())));
287   } else if (Op.isDFPImm()) {
288     O << ::toString(APFloat(bit_cast<double>(Op.getDFPImm())));
289   } else {
290     assert(Op.isExpr() && "unknown operand kind in printOperand");
291     // call_indirect instructions have a TYPEINDEX operand that we print
292     // as a signature here, such that the assembler can recover this
293     // information.
294     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
295     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
296       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
297       O << WebAssembly::signatureToString(Sym.getSignature());
298     } else {
299       Op.getExpr()->print(O, &MAI);
300     }
301   }
302 }
303 
304 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
305                                          raw_ostream &O) {
306   O << "{";
307   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
308     if (I != OpNo)
309       O << ", ";
310     O << MI->getOperand(I).getImm();
311   }
312   O << "}";
313 }
314 
315 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
316                                                             unsigned OpNo,
317                                                             raw_ostream &O) {
318   int64_t Imm = MI->getOperand(OpNo).getImm();
319   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
320     return;
321   O << ":p2align=" << Imm;
322 }
323 
324 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
325                                                               unsigned OpNo,
326                                                               raw_ostream &O) {
327   const MCOperand &Op = MI->getOperand(OpNo);
328   if (Op.isImm()) {
329     auto Imm = static_cast<unsigned>(Op.getImm());
330     if (Imm != wasm::WASM_TYPE_NORESULT)
331       O << WebAssembly::anyTypeToString(Imm);
332   } else {
333     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
334     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
335     if (Sym->getSignature()) {
336       O << WebAssembly::signatureToString(Sym->getSignature());
337     } else {
338       // Disassembler does not currently produce a signature
339       O << "unknown_type";
340     }
341   }
342 }
343 
344 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
345                                                              unsigned OpNo,
346                                                              raw_ostream &O) {
347   const MCOperand &Op = MI->getOperand(OpNo);
348   if (Op.isImm()) {
349     switch (Op.getImm()) {
350     case long(wasm::ValType::EXTERNREF):
351       O << "extern";
352       break;
353     case long(wasm::ValType::FUNCREF):
354       O << "func";
355       break;
356     default:
357       O << "unsupported_heap_type_value";
358       break;
359     }
360   } else {
361     // Typed function references and other subtypes of funcref and externref
362     // currently unimplemented.
363     O << "unsupported_heap_type_operand";
364   }
365 }
366 
367 // We have various enums representing a subset of these types, use this
368 // function to convert any of them to text.
369 const char *WebAssembly::anyTypeToString(unsigned Ty) {
370   switch (Ty) {
371   case wasm::WASM_TYPE_I32:
372     return "i32";
373   case wasm::WASM_TYPE_I64:
374     return "i64";
375   case wasm::WASM_TYPE_F32:
376     return "f32";
377   case wasm::WASM_TYPE_F64:
378     return "f64";
379   case wasm::WASM_TYPE_V128:
380     return "v128";
381   case wasm::WASM_TYPE_FUNCREF:
382     return "funcref";
383   case wasm::WASM_TYPE_EXTERNREF:
384     return "externref";
385   case wasm::WASM_TYPE_FUNC:
386     return "func";
387   case wasm::WASM_TYPE_NORESULT:
388     return "void";
389   default:
390     return "invalid_type";
391   }
392 }
393 
394 const char *WebAssembly::typeToString(wasm::ValType Ty) {
395   return anyTypeToString(static_cast<unsigned>(Ty));
396 }
397 
398 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
399   std::string S;
400   for (auto &Ty : List) {
401     if (&Ty != &List[0]) S += ", ";
402     S += WebAssembly::typeToString(Ty);
403   }
404   return S;
405 }
406 
407 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
408   std::string S("(");
409   S += typeListToString(Sig->Params);
410   S += ") -> (";
411   S += typeListToString(Sig->Returns);
412   S += ")";
413   return S;
414 }
415