• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
WebAssemblyInstPrinter(const MCAsmInfo & MAI,const MCInstrInfo & MII,const MCRegisterInfo & MRI)35 WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
36                                                const MCInstrInfo &MII,
37                                                const MCRegisterInfo &MRI)
38     : MCInstPrinter(MAI, MII, MRI) {}
39 
printRegName(raw_ostream & OS,unsigned RegNo) const40 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 
printInst(const MCInst * MI,uint64_t Address,StringRef Annot,const MCSubtargetInfo & STI,raw_ostream & OS)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       break;
98 
99     case WebAssembly::BLOCK:
100     case WebAssembly::BLOCK_S:
101       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
102       break;
103 
104     case WebAssembly::TRY:
105     case WebAssembly::TRY_S:
106       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
107       EHPadStack.push_back(EHPadStackCounter++);
108       LastSeenEHInst = TRY;
109       break;
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       break;
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       break;
129 
130     case WebAssembly::END_TRY:
131     case WebAssembly::END_TRY_S:
132       if (ControlFlowStack.empty()) {
133         printAnnotation(OS, "End marker mismatch!");
134       } else {
135         printAnnotation(
136             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
137         LastSeenEHInst = END_TRY;
138       }
139       break;
140 
141     case WebAssembly::CATCH:
142     case WebAssembly::CATCH_S:
143       if (EHPadStack.empty()) {
144         printAnnotation(OS, "try-catch mismatch!");
145       } else {
146         printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
147       }
148       break;
149     }
150 
151     // Annotate any control flow label references.
152 
153     // rethrow instruction does not take any depth argument and rethrows to the
154     // nearest enclosing catch scope, if any. If there's no enclosing catch
155     // scope, it throws up to the caller.
156     if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
157       if (EHPadStack.empty()) {
158         printAnnotation(OS, "to caller");
159       } else {
160         printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
161       }
162 
163     } else {
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 
toString(const APFloat & FP)196 static std::string toString(const APFloat &FP) {
197   // Print NaNs with custom payloads specially.
198   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
199       !FP.bitwiseIsEqual(
200           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
201     APInt AI = FP.bitcastToAPInt();
202     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
203            utohexstr(AI.getZExtValue() &
204                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
205                                                  : INT64_C(0x000fffffffffffff)),
206                      /*LowerCase=*/true);
207   }
208 
209   // Use C99's hexadecimal floating-point representation.
210   static const size_t BufBytes = 128;
211   char Buf[BufBytes];
212   auto Written = FP.convertToHexString(
213       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
214   (void)Written;
215   assert(Written != 0);
216   assert(Written < BufBytes);
217   return Buf;
218 }
219 
printOperand(const MCInst * MI,unsigned OpNo,raw_ostream & O,bool IsVariadicDef)220 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
221                                           raw_ostream &O, bool IsVariadicDef) {
222   const MCOperand &Op = MI->getOperand(OpNo);
223   if (Op.isReg()) {
224     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
225     unsigned WAReg = Op.getReg();
226     if (int(WAReg) >= 0)
227       printRegName(O, WAReg);
228     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
229       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
230     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
231       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
232     else
233       O << "$drop";
234     // Add a '=' suffix if this is a def.
235     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
236       O << '=';
237   } else if (Op.isImm()) {
238     O << Op.getImm();
239   } else if (Op.isFPImm()) {
240     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
241     const MCOperandInfo &Info = Desc.OpInfo[OpNo];
242     if (Info.OperandType == WebAssembly::OPERAND_F32IMM) {
243       // TODO: MC converts all floating point immediate operands to double.
244       // This is fine for numeric values, but may cause NaNs to change bits.
245       O << ::toString(APFloat(float(Op.getFPImm())));
246     } else {
247       assert(Info.OperandType == WebAssembly::OPERAND_F64IMM);
248       O << ::toString(APFloat(Op.getFPImm()));
249     }
250   } else {
251     assert(Op.isExpr() && "unknown operand kind in printOperand");
252     // call_indirect instructions have a TYPEINDEX operand that we print
253     // as a signature here, such that the assembler can recover this
254     // information.
255     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
256     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
257       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
258       O << WebAssembly::signatureToString(Sym.getSignature());
259     } else {
260       Op.getExpr()->print(O, &MAI);
261     }
262   }
263 }
264 
printBrList(const MCInst * MI,unsigned OpNo,raw_ostream & O)265 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
266                                          raw_ostream &O) {
267   O << "{";
268   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
269     if (I != OpNo)
270       O << ", ";
271     O << MI->getOperand(I).getImm();
272   }
273   O << "}";
274 }
275 
printWebAssemblyP2AlignOperand(const MCInst * MI,unsigned OpNo,raw_ostream & O)276 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
277                                                             unsigned OpNo,
278                                                             raw_ostream &O) {
279   int64_t Imm = MI->getOperand(OpNo).getImm();
280   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
281     return;
282   O << ":p2align=" << Imm;
283 }
284 
printWebAssemblySignatureOperand(const MCInst * MI,unsigned OpNo,raw_ostream & O)285 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
286                                                               unsigned OpNo,
287                                                               raw_ostream &O) {
288   const MCOperand &Op = MI->getOperand(OpNo);
289   if (Op.isImm()) {
290     auto Imm = static_cast<unsigned>(Op.getImm());
291     if (Imm != wasm::WASM_TYPE_NORESULT)
292       O << WebAssembly::anyTypeToString(Imm);
293   } else {
294     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
295     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
296     if (Sym->getSignature()) {
297       O << WebAssembly::signatureToString(Sym->getSignature());
298     } else {
299       // Disassembler does not currently produce a signature
300       O << "unknown_type";
301     }
302   }
303 }
304 
printWebAssemblyHeapTypeOperand(const MCInst * MI,unsigned OpNo,raw_ostream & O)305 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
306                                                              unsigned OpNo,
307                                                              raw_ostream &O) {
308   const MCOperand &Op = MI->getOperand(OpNo);
309   if (Op.isImm()) {
310     switch (Op.getImm()) {
311     case long(wasm::ValType::EXTERNREF):
312       O << "extern";
313       break;
314     case long(wasm::ValType::FUNCREF):
315       O << "func";
316       break;
317     default:
318       O << "unsupported_heap_type_value";
319       break;
320     }
321   } else {
322     // Typed function references and other subtypes of funcref and externref
323     // currently unimplemented.
324     O << "unsupported_heap_type_operand";
325   }
326 }
327 
328 // We have various enums representing a subset of these types, use this
329 // function to convert any of them to text.
anyTypeToString(unsigned Ty)330 const char *WebAssembly::anyTypeToString(unsigned Ty) {
331   switch (Ty) {
332   case wasm::WASM_TYPE_I32:
333     return "i32";
334   case wasm::WASM_TYPE_I64:
335     return "i64";
336   case wasm::WASM_TYPE_F32:
337     return "f32";
338   case wasm::WASM_TYPE_F64:
339     return "f64";
340   case wasm::WASM_TYPE_V128:
341     return "v128";
342   case wasm::WASM_TYPE_FUNCREF:
343     return "funcref";
344   case wasm::WASM_TYPE_EXTERNREF:
345     return "externref";
346   case wasm::WASM_TYPE_FUNC:
347     return "func";
348   case wasm::WASM_TYPE_EXNREF:
349     return "exnref";
350   case wasm::WASM_TYPE_NORESULT:
351     return "void";
352   default:
353     return "invalid_type";
354   }
355 }
356 
typeToString(wasm::ValType Ty)357 const char *WebAssembly::typeToString(wasm::ValType Ty) {
358   return anyTypeToString(static_cast<unsigned>(Ty));
359 }
360 
typeListToString(ArrayRef<wasm::ValType> List)361 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
362   std::string S;
363   for (auto &Ty : List) {
364     if (&Ty != &List[0]) S += ", ";
365     S += WebAssembly::typeToString(Ty);
366   }
367   return S;
368 }
369 
signatureToString(const wasm::WasmSignature * Sig)370 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
371   std::string S("(");
372   S += typeListToString(Sig->Params);
373   S += ") -> (";
374   S += typeListToString(Sig->Returns);
375   S += ")";
376   return S;
377 }
378