1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===// 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 /// This file contains a printer that converts from our internal 11 /// representation of machine-dependent LLVM code to the WebAssembly assembly 12 /// language. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "WebAssemblyAsmPrinter.h" 17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 18 #include "MCTargetDesc/WebAssemblyTargetStreamer.h" 19 #include "TargetInfo/WebAssemblyTargetInfo.h" 20 #include "Utils/WebAssemblyTypeUtilities.h" 21 #include "Utils/WebAssemblyUtilities.h" 22 #include "WebAssembly.h" 23 #include "WebAssemblyMCInstLower.h" 24 #include "WebAssemblyMachineFunctionInfo.h" 25 #include "WebAssemblyRegisterInfo.h" 26 #include "WebAssemblyRuntimeLibcallSignatures.h" 27 #include "WebAssemblyTargetMachine.h" 28 #include "llvm/ADT/SmallSet.h" 29 #include "llvm/ADT/StringExtras.h" 30 #include "llvm/BinaryFormat/Wasm.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AsmPrinter.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineInstr.h" 35 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/GlobalVariable.h" 39 #include "llvm/IR/Metadata.h" 40 #include "llvm/MC/MCContext.h" 41 #include "llvm/MC/MCSectionWasm.h" 42 #include "llvm/MC/MCStreamer.h" 43 #include "llvm/MC/MCSymbol.h" 44 #include "llvm/MC/MCSymbolWasm.h" 45 #include "llvm/MC/TargetRegistry.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/raw_ostream.h" 48 49 using namespace llvm; 50 51 #define DEBUG_TYPE "asm-printer" 52 53 extern cl::opt<bool> WasmKeepRegisters; 54 55 //===----------------------------------------------------------------------===// 56 // Helpers. 57 //===----------------------------------------------------------------------===// 58 59 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const { 60 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 61 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo); 62 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16, 63 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64}) 64 if (TRI->isTypeLegalForClass(*TRC, T)) 65 return T; 66 LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo); 67 llvm_unreachable("Unknown register type"); 68 return MVT::Other; 69 } 70 71 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) { 72 Register RegNo = MO.getReg(); 73 assert(Register::isVirtualRegister(RegNo) && 74 "Unlowered physical register encountered during assembly printing"); 75 assert(!MFI->isVRegStackified(RegNo)); 76 unsigned WAReg = MFI->getWAReg(RegNo); 77 assert(WAReg != WebAssemblyFunctionInfo::UnusedReg); 78 return '$' + utostr(WAReg); 79 } 80 81 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() { 82 MCTargetStreamer *TS = OutStreamer->getTargetStreamer(); 83 return static_cast<WebAssemblyTargetStreamer *>(TS); 84 } 85 86 // Emscripten exception handling helpers 87 // 88 // This converts invoke names generated by LowerEmscriptenEHSjLj to real names 89 // that are expected by JavaScript glue code. The invoke names generated by 90 // Emscripten JS glue code are based on their argument and return types; for 91 // example, for a function that takes an i32 and returns nothing, it is 92 // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass 93 // contains a mangled string generated from their IR types, for example, 94 // "__invoke_void_%struct.mystruct*_int", because final wasm types are not 95 // available in the IR pass. So we convert those names to the form that 96 // Emscripten JS code expects. 97 // 98 // Refer to LowerEmscriptenEHSjLj pass for more details. 99 100 // Returns true if the given function name is an invoke name generated by 101 // LowerEmscriptenEHSjLj pass. 102 static bool isEmscriptenInvokeName(StringRef Name) { 103 if (Name.front() == '"' && Name.back() == '"') 104 Name = Name.substr(1, Name.size() - 2); 105 return Name.startswith("__invoke_"); 106 } 107 108 // Returns a character that represents the given wasm value type in invoke 109 // signatures. 110 static char getInvokeSig(wasm::ValType VT) { 111 switch (VT) { 112 case wasm::ValType::I32: 113 return 'i'; 114 case wasm::ValType::I64: 115 return 'j'; 116 case wasm::ValType::F32: 117 return 'f'; 118 case wasm::ValType::F64: 119 return 'd'; 120 case wasm::ValType::V128: 121 return 'V'; 122 case wasm::ValType::FUNCREF: 123 return 'F'; 124 case wasm::ValType::EXTERNREF: 125 return 'X'; 126 } 127 llvm_unreachable("Unhandled wasm::ValType enum"); 128 } 129 130 // Given the wasm signature, generate the invoke name in the format JS glue code 131 // expects. 132 static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) { 133 assert(Sig->Returns.size() <= 1); 134 std::string Ret = "invoke_"; 135 if (!Sig->Returns.empty()) 136 for (auto VT : Sig->Returns) 137 Ret += getInvokeSig(VT); 138 else 139 Ret += 'v'; 140 // Invokes' first argument is a pointer to the original function, so skip it 141 for (unsigned I = 1, E = Sig->Params.size(); I < E; I++) 142 Ret += getInvokeSig(Sig->Params[I]); 143 return Ret; 144 } 145 146 //===----------------------------------------------------------------------===// 147 // WebAssemblyAsmPrinter Implementation. 148 //===----------------------------------------------------------------------===// 149 150 MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction( 151 const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig, 152 bool &InvokeDetected) { 153 MCSymbolWasm *WasmSym = nullptr; 154 if (EnableEmEH && isEmscriptenInvokeName(F->getName())) { 155 assert(Sig); 156 InvokeDetected = true; 157 if (Sig->Returns.size() > 1) { 158 std::string Msg = 159 "Emscripten EH/SjLj does not support multivalue returns: " + 160 std::string(F->getName()) + ": " + 161 WebAssembly::signatureToString(Sig); 162 report_fatal_error(Twine(Msg)); 163 } 164 WasmSym = cast<MCSymbolWasm>( 165 GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig))); 166 } else { 167 WasmSym = cast<MCSymbolWasm>(getSymbol(F)); 168 } 169 return WasmSym; 170 } 171 172 void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 173 if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) { 174 AsmPrinter::emitGlobalVariable(GV); 175 return; 176 } 177 178 assert(!GV->isThreadLocal()); 179 180 MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV)); 181 182 if (!Sym->getType()) { 183 SmallVector<MVT, 1> VTs; 184 Type *GlobalVT = GV->getValueType(); 185 if (Subtarget) { 186 // Subtarget is only set when a function is defined, because 187 // each function can declare a different subtarget. For example, 188 // on ARM a compilation unit might have a function on ARM and 189 // another on Thumb. Therefore only if Subtarget is non-null we 190 // can actually calculate the legal VTs. 191 const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering(); 192 computeLegalValueVTs(TLI, GV->getParent()->getContext(), 193 GV->getParent()->getDataLayout(), GlobalVT, VTs); 194 } 195 WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs); 196 } 197 198 emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration()); 199 emitSymbolType(Sym); 200 if (GV->hasInitializer()) { 201 assert(getSymbolPreferLocal(*GV) == Sym); 202 emitLinkage(GV, Sym); 203 OutStreamer->emitLabel(Sym); 204 // TODO: Actually emit the initializer value. Otherwise the global has the 205 // default value for its type (0, ref.null, etc). 206 OutStreamer->AddBlankLine(); 207 } 208 } 209 210 MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) { 211 auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name)); 212 213 // May be called multiple times, so early out. 214 if (WasmSym->getType().hasValue()) 215 return WasmSym; 216 217 const WebAssemblySubtarget &Subtarget = getSubtarget(); 218 219 // Except for certain known symbols, all symbols used by CodeGen are 220 // functions. It's OK to hardcode knowledge of specific symbols here; this 221 // method is precisely there for fetching the signatures of known 222 // Clang-provided symbols. 223 if (Name == "__stack_pointer" || Name == "__tls_base" || 224 Name == "__memory_base" || Name == "__table_base" || 225 Name == "__tls_size" || Name == "__tls_align") { 226 bool Mutable = 227 Name == "__stack_pointer" || Name == "__tls_base"; 228 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); 229 WasmSym->setGlobalType(wasm::WasmGlobalType{ 230 uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64 231 : wasm::WASM_TYPE_I32), 232 Mutable}); 233 return WasmSym; 234 } 235 236 if (Name.startswith("GCC_except_table")) { 237 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA); 238 return WasmSym; 239 } 240 241 SmallVector<wasm::ValType, 4> Returns; 242 SmallVector<wasm::ValType, 4> Params; 243 if (Name == "__cpp_exception" || Name == "__c_longjmp") { 244 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG); 245 // In static linking we define tag symbols in WasmException::endModule(). 246 // But we may have multiple objects to be linked together, each of which 247 // defines the tag symbols. To resolve them, we declare them as weak. In 248 // dynamic linking we make tag symbols undefined in the backend, define it 249 // in JS, and feed them to each importing module. 250 if (!isPositionIndependent()) 251 WasmSym->setWeak(true); 252 WasmSym->setExternal(true); 253 254 // Currently both C++ exceptions and C longjmps have a single pointer type 255 // param. For C++ exceptions it is a pointer to an exception object, and for 256 // C longjmps it is pointer to a struct that contains a setjmp buffer and a 257 // longjmp return value. We may consider using multiple value parameters for 258 // longjmps later when multivalue support is ready. 259 wasm::ValType AddrType = 260 Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32; 261 Params.push_back(AddrType); 262 } else { // Function symbols 263 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 264 getLibcallSignature(Subtarget, Name, Returns, Params); 265 } 266 auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns), 267 std::move(Params)); 268 WasmSym->setSignature(Signature.get()); 269 addSignature(std::move(Signature)); 270 271 return WasmSym; 272 } 273 274 void WebAssemblyAsmPrinter::emitSymbolType(const MCSymbolWasm *Sym) { 275 Optional<wasm::WasmSymbolType> WasmTy = Sym->getType(); 276 if (!WasmTy) 277 return; 278 279 switch (WasmTy.getValue()) { 280 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 281 getTargetStreamer()->emitGlobalType(Sym); 282 break; 283 case wasm::WASM_SYMBOL_TYPE_TAG: 284 getTargetStreamer()->emitTagType(Sym); 285 break; 286 case wasm::WASM_SYMBOL_TYPE_TABLE: 287 getTargetStreamer()->emitTableType(Sym); 288 break; 289 default: 290 break; // We only handle globals, tags and tables here 291 } 292 } 293 294 void WebAssemblyAsmPrinter::emitExternalDecls(const Module &M) { 295 if (signaturesEmitted) 296 return; 297 signaturesEmitted = true; 298 299 // Normally symbols for globals get discovered as the MI gets lowered, 300 // but we need to know about them ahead of time. This will however, 301 // only find symbols that have been used. Unused symbols from globals will 302 // not be found here. 303 MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>(); 304 for (const auto &Name : MMIW.MachineSymbolsUsed) { 305 auto *WasmSym = cast<MCSymbolWasm>(getOrCreateWasmSymbol(Name.getKey())); 306 if (WasmSym->isFunction()) { 307 // TODO(wvo): is there any case where this overlaps with the call to 308 // emitFunctionType in the loop below? 309 getTargetStreamer()->emitFunctionType(WasmSym); 310 } 311 } 312 313 for (auto &It : OutContext.getSymbols()) { 314 // Emit .globaltype, .tagtype, or .tabletype declarations for extern 315 // declarations, i.e. those that have only been declared (but not defined) 316 // in the current module 317 auto Sym = cast<MCSymbolWasm>(It.getValue()); 318 if (!Sym->isDefined()) 319 emitSymbolType(Sym); 320 } 321 322 DenseSet<MCSymbol *> InvokeSymbols; 323 for (const auto &F : M) { 324 if (F.isIntrinsic()) 325 continue; 326 327 // Emit function type info for all undefined functions 328 if (F.isDeclarationForLinker()) { 329 SmallVector<MVT, 4> Results; 330 SmallVector<MVT, 4> Params; 331 computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results); 332 // At this point these MCSymbols may or may not have been created already 333 // and thus also contain a signature, but we need to get the signature 334 // anyway here in case it is an invoke that has not yet been created. We 335 // will discard it later if it turns out not to be necessary. 336 auto Signature = signatureFromMVTs(Results, Params); 337 bool InvokeDetected = false; 338 auto *Sym = getMCSymbolForFunction( 339 &F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj, 340 Signature.get(), InvokeDetected); 341 342 // Multiple functions can be mapped to the same invoke symbol. For 343 // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32' 344 // are both mapped to '__invoke_vi'. We keep them in a set once we emit an 345 // Emscripten EH symbol so we don't emit the same symbol twice. 346 if (InvokeDetected && !InvokeSymbols.insert(Sym).second) 347 continue; 348 349 Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 350 if (!Sym->getSignature()) { 351 Sym->setSignature(Signature.get()); 352 addSignature(std::move(Signature)); 353 } else { 354 // This symbol has already been created and had a signature. Discard it. 355 Signature.reset(); 356 } 357 358 getTargetStreamer()->emitFunctionType(Sym); 359 360 if (F.hasFnAttribute("wasm-import-module")) { 361 StringRef Name = 362 F.getFnAttribute("wasm-import-module").getValueAsString(); 363 Sym->setImportModule(storeName(Name)); 364 getTargetStreamer()->emitImportModule(Sym, Name); 365 } 366 if (F.hasFnAttribute("wasm-import-name")) { 367 // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use 368 // the original function name but the converted symbol name. 369 StringRef Name = 370 InvokeDetected 371 ? Sym->getName() 372 : F.getFnAttribute("wasm-import-name").getValueAsString(); 373 Sym->setImportName(storeName(Name)); 374 getTargetStreamer()->emitImportName(Sym, Name); 375 } 376 } 377 378 if (F.hasFnAttribute("wasm-export-name")) { 379 auto *Sym = cast<MCSymbolWasm>(getSymbol(&F)); 380 StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString(); 381 Sym->setExportName(storeName(Name)); 382 getTargetStreamer()->emitExportName(Sym, Name); 383 } 384 } 385 } 386 387 void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) { 388 // This is required to emit external declarations (like .functypes) when 389 // no functions are defined in the compilation unit and therefore, 390 // emitExternalDecls() is not called until now. 391 emitExternalDecls(M); 392 393 // When a function's address is taken, a TABLE_INDEX relocation is emitted 394 // against the function symbol at the use site. However the relocation 395 // doesn't explicitly refer to the table. In the future we may want to 396 // define a new kind of reloc against both the function and the table, so 397 // that the linker can see that the function symbol keeps the table alive, 398 // but for now manually mark the table as live. 399 for (const auto &F : M) { 400 if (!F.isIntrinsic() && F.hasAddressTaken()) { 401 MCSymbolWasm *FunctionTable = 402 WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget); 403 OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip); 404 break; 405 } 406 } 407 408 for (const auto &G : M.globals()) { 409 if (!G.hasInitializer() && G.hasExternalLinkage() && 410 !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) && 411 G.getValueType()->isSized()) { 412 uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType()); 413 OutStreamer->emitELFSize(getSymbol(&G), 414 MCConstantExpr::create(Size, OutContext)); 415 } 416 } 417 418 if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) { 419 for (const Metadata *MD : Named->operands()) { 420 const auto *Tuple = dyn_cast<MDTuple>(MD); 421 if (!Tuple || Tuple->getNumOperands() != 2) 422 continue; 423 const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0)); 424 const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1)); 425 if (!Name || !Contents) 426 continue; 427 428 OutStreamer->PushSection(); 429 std::string SectionName = (".custom_section." + Name->getString()).str(); 430 MCSectionWasm *MySection = 431 OutContext.getWasmSection(SectionName, SectionKind::getMetadata()); 432 OutStreamer->SwitchSection(MySection); 433 OutStreamer->emitBytes(Contents->getString()); 434 OutStreamer->PopSection(); 435 } 436 } 437 438 EmitProducerInfo(M); 439 EmitTargetFeatures(M); 440 } 441 442 void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) { 443 llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages; 444 if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) { 445 llvm::SmallSet<StringRef, 4> SeenLanguages; 446 for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) { 447 const auto *CU = cast<DICompileUnit>(Debug->getOperand(I)); 448 StringRef Language = dwarf::LanguageString(CU->getSourceLanguage()); 449 Language.consume_front("DW_LANG_"); 450 if (SeenLanguages.insert(Language).second) 451 Languages.emplace_back(Language.str(), ""); 452 } 453 } 454 455 llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools; 456 if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) { 457 llvm::SmallSet<StringRef, 4> SeenTools; 458 for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) { 459 const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0)); 460 std::pair<StringRef, StringRef> Field = S->getString().split("version"); 461 StringRef Name = Field.first.trim(); 462 StringRef Version = Field.second.trim(); 463 if (SeenTools.insert(Name).second) 464 Tools.emplace_back(Name.str(), Version.str()); 465 } 466 } 467 468 int FieldCount = int(!Languages.empty()) + int(!Tools.empty()); 469 if (FieldCount != 0) { 470 MCSectionWasm *Producers = OutContext.getWasmSection( 471 ".custom_section.producers", SectionKind::getMetadata()); 472 OutStreamer->PushSection(); 473 OutStreamer->SwitchSection(Producers); 474 OutStreamer->emitULEB128IntValue(FieldCount); 475 for (auto &Producers : {std::make_pair("language", &Languages), 476 std::make_pair("processed-by", &Tools)}) { 477 if (Producers.second->empty()) 478 continue; 479 OutStreamer->emitULEB128IntValue(strlen(Producers.first)); 480 OutStreamer->emitBytes(Producers.first); 481 OutStreamer->emitULEB128IntValue(Producers.second->size()); 482 for (auto &Producer : *Producers.second) { 483 OutStreamer->emitULEB128IntValue(Producer.first.size()); 484 OutStreamer->emitBytes(Producer.first); 485 OutStreamer->emitULEB128IntValue(Producer.second.size()); 486 OutStreamer->emitBytes(Producer.second); 487 } 488 } 489 OutStreamer->PopSection(); 490 } 491 } 492 493 void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) { 494 struct FeatureEntry { 495 uint8_t Prefix; 496 std::string Name; 497 }; 498 499 // Read target features and linkage policies from module metadata 500 SmallVector<FeatureEntry, 4> EmittedFeatures; 501 auto EmitFeature = [&](std::string Feature) { 502 std::string MDKey = (StringRef("wasm-feature-") + Feature).str(); 503 Metadata *Policy = M.getModuleFlag(MDKey); 504 if (Policy == nullptr) 505 return; 506 507 FeatureEntry Entry; 508 Entry.Prefix = 0; 509 Entry.Name = Feature; 510 511 if (auto *MD = cast<ConstantAsMetadata>(Policy)) 512 if (auto *I = cast<ConstantInt>(MD->getValue())) 513 Entry.Prefix = I->getZExtValue(); 514 515 // Silently ignore invalid metadata 516 if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED && 517 Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED && 518 Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED) 519 return; 520 521 EmittedFeatures.push_back(Entry); 522 }; 523 524 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 525 EmitFeature(KV.Key); 526 } 527 // This pseudo-feature tells the linker whether shared memory would be safe 528 EmitFeature("shared-mem"); 529 530 // This is an "architecture", not a "feature", but we emit it as such for 531 // the benefit of tools like Binaryen and consistency with other producers. 532 // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ? 533 if (M.getDataLayout().getPointerSize() == 8) { 534 // Can't use EmitFeature since "wasm-feature-memory64" is not a module 535 // flag. 536 EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"}); 537 } 538 539 if (EmittedFeatures.size() == 0) 540 return; 541 542 // Emit features and linkage policies into the "target_features" section 543 MCSectionWasm *FeaturesSection = OutContext.getWasmSection( 544 ".custom_section.target_features", SectionKind::getMetadata()); 545 OutStreamer->PushSection(); 546 OutStreamer->SwitchSection(FeaturesSection); 547 548 OutStreamer->emitULEB128IntValue(EmittedFeatures.size()); 549 for (auto &F : EmittedFeatures) { 550 OutStreamer->emitIntValue(F.Prefix, 1); 551 OutStreamer->emitULEB128IntValue(F.Name.size()); 552 OutStreamer->emitBytes(F.Name); 553 } 554 555 OutStreamer->PopSection(); 556 } 557 558 void WebAssemblyAsmPrinter::emitConstantPool() { 559 emitExternalDecls(*MMI->getModule()); 560 assert(MF->getConstantPool()->getConstants().empty() && 561 "WebAssembly disables constant pools"); 562 } 563 564 void WebAssemblyAsmPrinter::emitJumpTableInfo() { 565 // Nothing to do; jump tables are incorporated into the instruction stream. 566 } 567 568 void WebAssemblyAsmPrinter::emitFunctionBodyStart() { 569 const Function &F = MF->getFunction(); 570 SmallVector<MVT, 1> ResultVTs; 571 SmallVector<MVT, 4> ParamVTs; 572 computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs); 573 574 auto Signature = signatureFromMVTs(ResultVTs, ParamVTs); 575 auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym); 576 WasmSym->setSignature(Signature.get()); 577 addSignature(std::move(Signature)); 578 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); 579 580 getTargetStreamer()->emitFunctionType(WasmSym); 581 582 // Emit the function index. 583 if (MDNode *Idx = F.getMetadata("wasm.index")) { 584 assert(Idx->getNumOperands() == 1); 585 586 getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant( 587 cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue())); 588 } 589 590 SmallVector<wasm::ValType, 16> Locals; 591 valTypesFromMVTs(MFI->getLocals(), Locals); 592 getTargetStreamer()->emitLocal(Locals); 593 594 AsmPrinter::emitFunctionBodyStart(); 595 } 596 597 void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) { 598 LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n'); 599 600 switch (MI->getOpcode()) { 601 case WebAssembly::ARGUMENT_i32: 602 case WebAssembly::ARGUMENT_i32_S: 603 case WebAssembly::ARGUMENT_i64: 604 case WebAssembly::ARGUMENT_i64_S: 605 case WebAssembly::ARGUMENT_f32: 606 case WebAssembly::ARGUMENT_f32_S: 607 case WebAssembly::ARGUMENT_f64: 608 case WebAssembly::ARGUMENT_f64_S: 609 case WebAssembly::ARGUMENT_v16i8: 610 case WebAssembly::ARGUMENT_v16i8_S: 611 case WebAssembly::ARGUMENT_v8i16: 612 case WebAssembly::ARGUMENT_v8i16_S: 613 case WebAssembly::ARGUMENT_v4i32: 614 case WebAssembly::ARGUMENT_v4i32_S: 615 case WebAssembly::ARGUMENT_v2i64: 616 case WebAssembly::ARGUMENT_v2i64_S: 617 case WebAssembly::ARGUMENT_v4f32: 618 case WebAssembly::ARGUMENT_v4f32_S: 619 case WebAssembly::ARGUMENT_v2f64: 620 case WebAssembly::ARGUMENT_v2f64_S: 621 // These represent values which are live into the function entry, so there's 622 // no instruction to emit. 623 break; 624 case WebAssembly::FALLTHROUGH_RETURN: { 625 // These instructions represent the implicit return at the end of a 626 // function body. 627 if (isVerbose()) { 628 OutStreamer->AddComment("fallthrough-return"); 629 OutStreamer->AddBlankLine(); 630 } 631 break; 632 } 633 case WebAssembly::COMPILER_FENCE: 634 // This is a compiler barrier that prevents instruction reordering during 635 // backend compilation, and should not be emitted. 636 break; 637 default: { 638 WebAssemblyMCInstLower MCInstLowering(OutContext, *this); 639 MCInst TmpInst; 640 MCInstLowering.lower(MI, TmpInst); 641 EmitToStreamer(*OutStreamer, TmpInst); 642 break; 643 } 644 } 645 } 646 647 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI, 648 unsigned OpNo, 649 const char *ExtraCode, 650 raw_ostream &OS) { 651 // First try the generic code, which knows about modifiers like 'c' and 'n'. 652 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS)) 653 return false; 654 655 if (!ExtraCode) { 656 const MachineOperand &MO = MI->getOperand(OpNo); 657 switch (MO.getType()) { 658 case MachineOperand::MO_Immediate: 659 OS << MO.getImm(); 660 return false; 661 case MachineOperand::MO_Register: 662 // FIXME: only opcode that still contains registers, as required by 663 // MachineInstr::getDebugVariable(). 664 assert(MI->getOpcode() == WebAssembly::INLINEASM); 665 OS << regToString(MO); 666 return false; 667 case MachineOperand::MO_GlobalAddress: 668 PrintSymbolOperand(MO, OS); 669 return false; 670 case MachineOperand::MO_ExternalSymbol: 671 GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI); 672 printOffset(MO.getOffset(), OS); 673 return false; 674 case MachineOperand::MO_MachineBasicBlock: 675 MO.getMBB()->getSymbol()->print(OS, MAI); 676 return false; 677 default: 678 break; 679 } 680 } 681 682 return true; 683 } 684 685 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, 686 unsigned OpNo, 687 const char *ExtraCode, 688 raw_ostream &OS) { 689 // The current approach to inline asm is that "r" constraints are expressed 690 // as local indices, rather than values on the operand stack. This simplifies 691 // using "r" as it eliminates the need to push and pop the values in a 692 // particular order, however it also makes it impossible to have an "m" 693 // constraint. So we don't support it. 694 695 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS); 696 } 697 698 // Force static initialization. 699 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() { 700 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32()); 701 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64()); 702 } 703