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 "MCTargetDesc/WebAssemblyMCTypeUtilities.h" 17 #include "WebAssembly.h" 18 #include "llvm/ADT/APFloat.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/MC/MCExpr.h" 22 #include "llvm/MC/MCInst.h" 23 #include "llvm/MC/MCInstrInfo.h" 24 #include "llvm/MC/MCSubtargetInfo.h" 25 #include "llvm/MC/MCSymbol.h" 26 #include "llvm/MC/MCSymbolWasm.h" 27 #include "llvm/Support/Casting.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/FormattedStream.h" 30 using namespace llvm; 31 32 #define DEBUG_TYPE "asm-printer" 33 34 #include "WebAssemblyGenAsmWriter.inc" 35 36 WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI, 37 const MCInstrInfo &MII, 38 const MCRegisterInfo &MRI) 39 : MCInstPrinter(MAI, MII, MRI) {} 40 41 void WebAssemblyInstPrinter::printRegName(raw_ostream &OS, 42 MCRegister Reg) const { 43 assert(Reg.id() != WebAssembly::UnusedReg); 44 // Note that there's an implicit local.get/local.set here! 45 OS << "$" << Reg.id(); 46 } 47 48 void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address, 49 StringRef Annot, 50 const MCSubtargetInfo &STI, 51 raw_ostream &OS) { 52 switch (MI->getOpcode()) { 53 case WebAssembly::CALL_INDIRECT_S: 54 case WebAssembly::RET_CALL_INDIRECT_S: { 55 // A special case for call_indirect (and ret_call_indirect), if the table 56 // operand is a symbol: the order of the type and table operands is inverted 57 // in the text format relative to the binary format. Otherwise if table the 58 // operand isn't a symbol, then we have an MVP compilation unit, and the 59 // table shouldn't appear in the output. 60 OS << "\t"; 61 OS << getMnemonic(MI).first; 62 OS << " "; 63 64 assert(MI->getNumOperands() == 2); 65 const unsigned TypeOperand = 0; 66 const unsigned TableOperand = 1; 67 if (MI->getOperand(TableOperand).isExpr()) { 68 printOperand(MI, TableOperand, OS); 69 OS << ", "; 70 } else { 71 assert(MI->getOperand(TableOperand).getImm() == 0); 72 } 73 printOperand(MI, TypeOperand, OS); 74 break; 75 } 76 default: 77 // Print the instruction (this uses the AsmStrings from the .td files). 78 printInstruction(MI, Address, OS); 79 break; 80 } 81 82 // Print any additional variadic operands. 83 const MCInstrDesc &Desc = MII.get(MI->getOpcode()); 84 if (Desc.isVariadic()) { 85 if ((Desc.getNumOperands() == 0 && MI->getNumOperands() > 0) || 86 Desc.variadicOpsAreDefs()) 87 OS << "\t"; 88 unsigned Start = Desc.getNumOperands(); 89 unsigned NumVariadicDefs = 0; 90 if (Desc.variadicOpsAreDefs()) { 91 // The number of variadic defs is encoded in an immediate by MCInstLower 92 NumVariadicDefs = MI->getOperand(0).getImm(); 93 Start = 1; 94 } 95 bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs(); 96 for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) { 97 if (MI->getOpcode() == WebAssembly::CALL_INDIRECT && 98 I - Start == NumVariadicDefs) { 99 // Skip type and table arguments when printing for tests. 100 ++I; 101 continue; 102 } 103 if (NeedsComma) 104 OS << ", "; 105 printOperand(MI, I, OS, I - Start < NumVariadicDefs); 106 NeedsComma = true; 107 } 108 } 109 110 // Print any added annotation. 111 printAnnotation(OS, Annot); 112 113 if (CommentStream) { 114 // Observe any effects on the control flow stack, for use in annotating 115 // control flow label references. 116 unsigned Opc = MI->getOpcode(); 117 switch (Opc) { 118 default: 119 break; 120 121 case WebAssembly::LOOP: 122 case WebAssembly::LOOP_S: 123 printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':'); 124 ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true)); 125 return; 126 127 case WebAssembly::BLOCK: 128 case WebAssembly::BLOCK_S: 129 ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false)); 130 return; 131 132 case WebAssembly::TRY: 133 case WebAssembly::TRY_S: 134 ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false)); 135 TryStack.push_back(ControlFlowCounter++); 136 EHInstStack.push_back(TRY); 137 return; 138 139 case WebAssembly::END_LOOP: 140 case WebAssembly::END_LOOP_S: 141 if (ControlFlowStack.empty()) { 142 printAnnotation(OS, "End marker mismatch!"); 143 } else { 144 ControlFlowStack.pop_back(); 145 } 146 return; 147 148 case WebAssembly::END_BLOCK: 149 case WebAssembly::END_BLOCK_S: 150 if (ControlFlowStack.empty()) { 151 printAnnotation(OS, "End marker mismatch!"); 152 } else { 153 printAnnotation( 154 OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':'); 155 } 156 return; 157 158 case WebAssembly::END_TRY: 159 case WebAssembly::END_TRY_S: 160 if (ControlFlowStack.empty() || EHInstStack.empty()) { 161 printAnnotation(OS, "End marker mismatch!"); 162 } else { 163 printAnnotation( 164 OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':'); 165 EHInstStack.pop_back(); 166 } 167 return; 168 169 case WebAssembly::CATCH_LEGACY: 170 case WebAssembly::CATCH_LEGACY_S: 171 case WebAssembly::CATCH_ALL_LEGACY: 172 case WebAssembly::CATCH_ALL_LEGACY_S: 173 // There can be multiple catch instructions for one try instruction, so 174 // we print a label only for the first 'catch' label. 175 if (EHInstStack.empty()) { 176 printAnnotation(OS, "try-catch mismatch!"); 177 } else if (EHInstStack.back() == CATCH_ALL_LEGACY) { 178 printAnnotation(OS, "catch/catch_all cannot occur after catch_all"); 179 } else if (EHInstStack.back() == TRY) { 180 if (TryStack.empty()) { 181 printAnnotation(OS, "try-catch mismatch!"); 182 } else { 183 printAnnotation(OS, "catch" + utostr(TryStack.pop_back_val()) + ':'); 184 } 185 EHInstStack.pop_back(); 186 if (Opc == WebAssembly::CATCH_LEGACY || 187 Opc == WebAssembly::CATCH_LEGACY_S) { 188 EHInstStack.push_back(CATCH_LEGACY); 189 } else { 190 EHInstStack.push_back(CATCH_ALL_LEGACY); 191 } 192 } 193 return; 194 195 case WebAssembly::RETHROW: 196 case WebAssembly::RETHROW_S: 197 // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If 198 // there's no enclosing catch scope, it throws up to the caller. 199 if (TryStack.empty()) { 200 printAnnotation(OS, "to caller"); 201 } else { 202 printAnnotation(OS, "down to catch" + utostr(TryStack.back())); 203 } 204 return; 205 206 case WebAssembly::DELEGATE: 207 case WebAssembly::DELEGATE_S: 208 if (ControlFlowStack.empty() || TryStack.empty() || EHInstStack.empty()) { 209 printAnnotation(OS, "try-delegate mismatch!"); 210 } else { 211 // 'delegate' is 212 // 1. A marker for the end of block label 213 // 2. A destination for throwing instructions 214 // 3. An instruction that itself rethrows to another 'catch' 215 assert(ControlFlowStack.back().first == TryStack.back()); 216 std::string Label = "label/catch" + 217 utostr(ControlFlowStack.pop_back_val().first) + 218 ": "; 219 TryStack.pop_back(); 220 EHInstStack.pop_back(); 221 uint64_t Depth = MI->getOperand(0).getImm(); 222 if (Depth >= ControlFlowStack.size()) { 223 Label += "to caller"; 224 } else { 225 const auto &Pair = ControlFlowStack.rbegin()[Depth]; 226 if (Pair.second) 227 printAnnotation(OS, "delegate cannot target a loop"); 228 else 229 Label += "down to catch" + utostr(Pair.first); 230 } 231 printAnnotation(OS, Label); 232 } 233 return; 234 } 235 236 // Annotate any control flow label references. 237 238 unsigned NumFixedOperands = Desc.NumOperands; 239 SmallSet<uint64_t, 8> Printed; 240 for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) { 241 // See if this operand denotes a basic block target. 242 if (I < NumFixedOperands) { 243 // A non-variable_ops operand, check its type. 244 if (Desc.operands()[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK) 245 continue; 246 } else { 247 // A variable_ops operand, which currently can be immediates (used in 248 // br_table) which are basic block targets, or for call instructions 249 // when using -wasm-keep-registers (in which case they are registers, 250 // and should not be processed). 251 if (!MI->getOperand(I).isImm()) 252 continue; 253 } 254 uint64_t Depth = MI->getOperand(I).getImm(); 255 if (!Printed.insert(Depth).second) 256 continue; 257 if (Depth >= ControlFlowStack.size()) { 258 printAnnotation(OS, "Invalid depth argument!"); 259 } else { 260 const auto &Pair = ControlFlowStack.rbegin()[Depth]; 261 printAnnotation(OS, utostr(Depth) + ": " + 262 (Pair.second ? "up" : "down") + " to label" + 263 utostr(Pair.first)); 264 } 265 } 266 } 267 } 268 269 static std::string toString(const APFloat &FP) { 270 // Print NaNs with custom payloads specially. 271 if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) && 272 !FP.bitwiseIsEqual( 273 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) { 274 APInt AI = FP.bitcastToAPInt(); 275 return std::string(AI.isNegative() ? "-" : "") + "nan:0x" + 276 utohexstr(AI.getZExtValue() & 277 (AI.getBitWidth() == 32 ? INT64_C(0x007fffff) 278 : INT64_C(0x000fffffffffffff)), 279 /*LowerCase=*/true); 280 } 281 282 // Use C99's hexadecimal floating-point representation. 283 static const size_t BufBytes = 128; 284 char Buf[BufBytes]; 285 auto Written = FP.convertToHexString( 286 Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven); 287 (void)Written; 288 assert(Written != 0); 289 assert(Written < BufBytes); 290 return Buf; 291 } 292 293 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, 294 raw_ostream &O, bool IsVariadicDef) { 295 const MCOperand &Op = MI->getOperand(OpNo); 296 if (Op.isReg()) { 297 const MCInstrDesc &Desc = MII.get(MI->getOpcode()); 298 unsigned WAReg = Op.getReg(); 299 if (int(WAReg) >= 0) 300 printRegName(O, WAReg); 301 else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef) 302 O << "$pop" << WebAssembly::getWARegStackId(WAReg); 303 else if (WAReg != WebAssembly::UnusedReg) 304 O << "$push" << WebAssembly::getWARegStackId(WAReg); 305 else 306 O << "$drop"; 307 // Add a '=' suffix if this is a def. 308 if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef) 309 O << '='; 310 } else if (Op.isImm()) { 311 O << Op.getImm(); 312 } else if (Op.isSFPImm()) { 313 O << ::toString(APFloat(APFloat::IEEEsingle(), APInt(32, Op.getSFPImm()))); 314 } else if (Op.isDFPImm()) { 315 O << ::toString(APFloat(APFloat::IEEEdouble(), APInt(64, Op.getDFPImm()))); 316 } else { 317 assert(Op.isExpr() && "unknown operand kind in printOperand"); 318 // call_indirect instructions have a TYPEINDEX operand that we print 319 // as a signature here, such that the assembler can recover this 320 // information. 321 auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr()); 322 if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) { 323 auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol()); 324 O << WebAssembly::signatureToString(Sym.getSignature()); 325 } else { 326 Op.getExpr()->print(O, &MAI); 327 } 328 } 329 } 330 331 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo, 332 raw_ostream &O) { 333 O << "{"; 334 for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) { 335 if (I != OpNo) 336 O << ", "; 337 O << MI->getOperand(I).getImm(); 338 } 339 O << "}"; 340 } 341 342 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI, 343 unsigned OpNo, 344 raw_ostream &O) { 345 int64_t Imm = MI->getOperand(OpNo).getImm(); 346 if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode())) 347 return; 348 O << ":p2align=" << Imm; 349 } 350 351 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI, 352 unsigned OpNo, 353 raw_ostream &O) { 354 const MCOperand &Op = MI->getOperand(OpNo); 355 if (Op.isImm()) { 356 auto Imm = static_cast<unsigned>(Op.getImm()); 357 if (Imm != wasm::WASM_TYPE_NORESULT) 358 O << WebAssembly::anyTypeToString(Imm); 359 } else { 360 auto Expr = cast<MCSymbolRefExpr>(Op.getExpr()); 361 auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol()); 362 if (Sym->getSignature()) { 363 O << WebAssembly::signatureToString(Sym->getSignature()); 364 } else { 365 // Disassembler does not currently produce a signature 366 O << "unknown_type"; 367 } 368 } 369 } 370