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

source code of llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp