]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/MC/WasmObjectWriter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / MC / WasmObjectWriter.cpp
1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Wasm object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/BinaryFormat/Wasm.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixupKindInfo.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/MC/MCWasmObjectWriter.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/StringSaver.h"
35 #include <vector>
36
37 using namespace llvm;
38
39 #undef DEBUG_TYPE
40 #define DEBUG_TYPE "reloc-info"
41
42 namespace {
43
44 // For patching purposes, we need to remember where each section starts, both
45 // for patching up the section size field, and for patching up references to
46 // locations within the section.
47 struct SectionBookkeeping {
48   // Where the size of the section is written.
49   uint64_t SizeOffset;
50   // Where the contents of the section starts (after the header).
51   uint64_t ContentsOffset;
52 };
53
54 // The signature of a wasm function, in a struct capable of being used as a
55 // DenseMap key.
56 struct WasmFunctionType {
57   // Support empty and tombstone instances, needed by DenseMap.
58   enum { Plain, Empty, Tombstone } State;
59
60   // The return types of the function.
61   SmallVector<wasm::ValType, 1> Returns;
62
63   // The parameter types of the function.
64   SmallVector<wasm::ValType, 4> Params;
65
66   WasmFunctionType() : State(Plain) {}
67
68   bool operator==(const WasmFunctionType &Other) const {
69     return State == Other.State && Returns == Other.Returns &&
70            Params == Other.Params;
71   }
72 };
73
74 // Traits for using WasmFunctionType in a DenseMap.
75 struct WasmFunctionTypeDenseMapInfo {
76   static WasmFunctionType getEmptyKey() {
77     WasmFunctionType FuncTy;
78     FuncTy.State = WasmFunctionType::Empty;
79     return FuncTy;
80   }
81   static WasmFunctionType getTombstoneKey() {
82     WasmFunctionType FuncTy;
83     FuncTy.State = WasmFunctionType::Tombstone;
84     return FuncTy;
85   }
86   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
87     uintptr_t Value = FuncTy.State;
88     for (wasm::ValType Ret : FuncTy.Returns)
89       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
90     for (wasm::ValType Param : FuncTy.Params)
91       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
92     return Value;
93   }
94   static bool isEqual(const WasmFunctionType &LHS,
95                       const WasmFunctionType &RHS) {
96     return LHS == RHS;
97   }
98 };
99
100 // A wasm import to be written into the import section.
101 struct WasmImport {
102   StringRef ModuleName;
103   StringRef FieldName;
104   unsigned Kind;
105   int32_t Type;
106 };
107
108 // A wasm function to be written into the function section.
109 struct WasmFunction {
110   int32_t Type;
111   const MCSymbolWasm *Sym;
112 };
113
114 // A wasm export to be written into the export section.
115 struct WasmExport {
116   StringRef FieldName;
117   unsigned Kind;
118   uint32_t Index;
119 };
120
121 // A wasm global to be written into the global section.
122 struct WasmGlobal {
123   wasm::ValType Type;
124   bool IsMutable;
125   bool HasImport;
126   uint64_t InitialValue;
127   uint32_t ImportIndex;
128 };
129
130 // Information about a single relocation.
131 struct WasmRelocationEntry {
132   uint64_t Offset;                  // Where is the relocation.
133   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
134   int64_t Addend;                   // A value to add to the symbol.
135   unsigned Type;                    // The type of the relocation.
136   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
137
138   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
139                       int64_t Addend, unsigned Type,
140                       const MCSectionWasm *FixupSection)
141       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
142         FixupSection(FixupSection) {}
143
144   bool hasAddend() const {
145     switch (Type) {
146     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
147     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
148     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
149       return true;
150     default:
151       return false;
152     }
153   }
154
155   void print(raw_ostream &Out) const {
156     Out << "Off=" << Offset << ", Sym=" << Symbol << ", Addend=" << Addend
157         << ", Type=" << Type << ", FixupSection=" << FixupSection;
158   }
159
160 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
161   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
162 #endif
163 };
164
165 #if !defined(NDEBUG)
166 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
167   Rel.print(OS);
168   return OS;
169 }
170 #endif
171
172 class WasmObjectWriter : public MCObjectWriter {
173   /// Helper struct for containing some precomputed information on symbols.
174   struct WasmSymbolData {
175     const MCSymbolWasm *Symbol;
176     StringRef Name;
177
178     // Support lexicographic sorting.
179     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
180   };
181
182   /// The target specific Wasm writer instance.
183   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
184
185   // Relocations for fixing up references in the code section.
186   std::vector<WasmRelocationEntry> CodeRelocations;
187
188   // Relocations for fixing up references in the data section.
189   std::vector<WasmRelocationEntry> DataRelocations;
190
191   // Index values to use for fixing up call_indirect type indices.
192   // Maps function symbols to the index of the type of the function
193   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194   // Maps function symbols to the table element index space. Used
195   // for TABLE_INDEX relocation types (i.e. address taken functions).
196   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
197   // Maps function/global symbols to the function/global index space.
198   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
199
200   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
201       FunctionTypeIndices;
202
203   // TargetObjectWriter wrappers.
204   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
205   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
206     return TargetObjectWriter->getRelocType(Target, Fixup);
207   }
208
209   void startSection(SectionBookkeeping &Section, unsigned SectionId,
210                     const char *Name = nullptr);
211   void endSection(SectionBookkeeping &Section);
212
213 public:
214   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
215       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
216
217 private:
218   ~WasmObjectWriter() override;
219
220   void reset() override {
221     CodeRelocations.clear();
222     DataRelocations.clear();
223     TypeIndices.clear();
224     SymbolIndices.clear();
225     IndirectSymbolIndices.clear();
226     FunctionTypeIndices.clear();
227     MCObjectWriter::reset();
228   }
229
230   void writeHeader(const MCAssembler &Asm);
231
232   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
233                         const MCFragment *Fragment, const MCFixup &Fixup,
234                         MCValue Target, bool &IsPCRel,
235                         uint64_t &FixedValue) override;
236
237   void executePostLayoutBinding(MCAssembler &Asm,
238                                 const MCAsmLayout &Layout) override;
239
240   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
241
242   void writeString(const StringRef Str) {
243     encodeULEB128(Str.size(), getStream());
244     writeBytes(Str);
245   }
246
247   void writeValueType(wasm::ValType Ty) {
248     encodeSLEB128(int32_t(Ty), getStream());
249   }
250
251   void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
252   void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
253   void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
254   void writeTableSection(uint32_t NumElements);
255   void writeMemorySection(const SmallVector<char, 0> &DataBytes);
256   void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
257   void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
258   void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
259   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
260                         const SmallVector<WasmFunction, 4> &Functions);
261   uint64_t
262   writeDataSection(const SmallVector<char, 0> &DataBytes);
263   void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
264                         const SmallVector<WasmImport, 4> &Imports,
265                         uint32_t NumFuncImports);
266   void writeCodeRelocSection();
267   void writeDataRelocSection(uint64_t DataSectionHeaderSize);
268   void writeLinkingMetaDataSection(ArrayRef<StringRef> WeakSymbols,
269                                    bool HasStackPointer,
270                                    uint32_t StackPointerGlobal);
271
272   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
273                         uint64_t ContentsOffset);
274
275   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
276                         uint64_t HeaderSize);
277   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
278 };
279
280 } // end anonymous namespace
281
282 WasmObjectWriter::~WasmObjectWriter() {}
283
284 // Return the padding size to write a 32-bit value into a 5-byte ULEB128.
285 static unsigned PaddingFor5ByteULEB128(uint32_t X) {
286   return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
287 }
288
289 // Return the padding size to write a 32-bit value into a 5-byte SLEB128.
290 static unsigned PaddingFor5ByteSLEB128(int32_t X) {
291   return 5 - getSLEB128Size(X);
292 }
293
294 // Write out a section header and a patchable section size field.
295 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
296                                     unsigned SectionId,
297                                     const char *Name) {
298   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
299          "Only custom sections can have names");
300
301   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
302   encodeULEB128(SectionId, getStream());
303
304   Section.SizeOffset = getStream().tell();
305
306   // The section size. We don't know the size yet, so reserve enough space
307   // for any 32-bit value; we'll patch it later.
308   encodeULEB128(UINT32_MAX, getStream());
309
310   // The position where the section starts, for measuring its size.
311   Section.ContentsOffset = getStream().tell();
312
313   // Custom sections in wasm also have a string identifier.
314   if (SectionId == wasm::WASM_SEC_CUSTOM) {
315     assert(Name);
316     writeString(StringRef(Name));
317   }
318 }
319
320 // Now that the section is complete and we know how big it is, patch up the
321 // section size field at the start of the section.
322 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
323   uint64_t Size = getStream().tell() - Section.ContentsOffset;
324   if (uint32_t(Size) != Size)
325     report_fatal_error("section size does not fit in a uint32_t");
326
327   DEBUG(dbgs() << "endSection size=" << Size << "\n");
328   unsigned Padding = PaddingFor5ByteULEB128(Size);
329
330   // Write the final section size to the payload_len field, which follows
331   // the section id byte.
332   uint8_t Buffer[16];
333   unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
334   assert(SizeLen == 5);
335   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
336 }
337
338 // Emit the Wasm header.
339 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
340   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
341   writeLE32(wasm::WasmVersion);
342 }
343
344 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
345                                                 const MCAsmLayout &Layout) {
346 }
347
348 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
349                                         const MCAsmLayout &Layout,
350                                         const MCFragment *Fragment,
351                                         const MCFixup &Fixup, MCValue Target,
352                                         bool &IsPCRel, uint64_t &FixedValue) {
353   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
354   uint64_t C = Target.getConstant();
355   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
356   MCContext &Ctx = Asm.getContext();
357
358   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
359     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
360            "Should not have constructed this");
361
362     // Let A, B and C being the components of Target and R be the location of
363     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
364     // If it is pcrel, we want to compute (A - B + C - R).
365
366     // In general, Wasm has no relocations for -B. It can only represent (A + C)
367     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
368     // replace B to implement it: (A - R - K + C)
369     if (IsPCRel) {
370       Ctx.reportError(
371           Fixup.getLoc(),
372           "No relocation available to represent this relative expression");
373       return;
374     }
375
376     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
377
378     if (SymB.isUndefined()) {
379       Ctx.reportError(Fixup.getLoc(),
380                       Twine("symbol '") + SymB.getName() +
381                           "' can not be undefined in a subtraction expression");
382       return;
383     }
384
385     assert(!SymB.isAbsolute() && "Should have been folded");
386     const MCSection &SecB = SymB.getSection();
387     if (&SecB != &FixupSection) {
388       Ctx.reportError(Fixup.getLoc(),
389                       "Cannot represent a difference across sections");
390       return;
391     }
392
393     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
394     uint64_t K = SymBOffset - FixupOffset;
395     IsPCRel = true;
396     C -= K;
397   }
398
399   // We either rejected the fixup or folded B into C at this point.
400   const MCSymbolRefExpr *RefA = Target.getSymA();
401   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
402
403   bool ViaWeakRef = false;
404   if (SymA && SymA->isVariable()) {
405     const MCExpr *Expr = SymA->getVariableValue();
406     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
407       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
408         SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
409         ViaWeakRef = true;
410       }
411     }
412   }
413
414   // Put any constant offset in an addend. Offsets can be negative, and
415   // LLVM expects wrapping, in contrast to wasm's immediates which can't
416   // be negative and don't wrap.
417   FixedValue = 0;
418
419   if (SymA) {
420     if (ViaWeakRef)
421       llvm_unreachable("weakref used in reloc not yet implemented");
422     else
423       SymA->setUsedInReloc();
424   }
425
426   assert(!IsPCRel);
427   assert(SymA);
428
429   unsigned Type = getRelocType(Target, Fixup);
430
431   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
432   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
433
434   if (FixupSection.hasInstructions())
435     CodeRelocations.push_back(Rec);
436   else
437     DataRelocations.push_back(Rec);
438 }
439
440 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
441 // to allow patching.
442 static void
443 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
444   uint8_t Buffer[5];
445   unsigned Padding = PaddingFor5ByteULEB128(X);
446   unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
447   assert(SizeLen == 5);
448   Stream.pwrite((char *)Buffer, SizeLen, Offset);
449 }
450
451 // Write X as an signed LEB value at offset Offset in Stream, padded
452 // to allow patching.
453 static void
454 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
455   uint8_t Buffer[5];
456   unsigned Padding = PaddingFor5ByteSLEB128(X);
457   unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
458   assert(SizeLen == 5);
459   Stream.pwrite((char *)Buffer, SizeLen, Offset);
460 }
461
462 // Write X as a plain integer value at offset Offset in Stream.
463 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
464   uint8_t Buffer[4];
465   support::endian::write32le(Buffer, X);
466   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
467 }
468
469 // Compute a value to write into the code at the location covered
470 // by RelEntry. This value isn't used by the static linker, since
471 // we have addends; it just serves to make the code more readable
472 // and to make standalone wasm modules directly usable.
473 static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
474   const MCSymbolWasm *Sym = RelEntry.Symbol;
475
476   // For undefined symbols, use a hopefully invalid value.
477   if (!Sym->isDefined(/*SetUsed=*/false))
478     return UINT32_MAX;
479
480   const auto &Section = cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
481   uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
482
483   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
484   uint32_t Value = Address;
485
486   return Value;
487 }
488
489 uint32_t WasmObjectWriter::getRelocationIndexValue(
490     const WasmRelocationEntry &RelEntry) {
491   switch (RelEntry.Type) {
492   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
493   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
494     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
495       report_fatal_error("symbol not found table index space:" +
496                          RelEntry.Symbol->getName());
497     return IndirectSymbolIndices[RelEntry.Symbol];
498   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
499   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
500   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
501   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
502   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
503     if (!SymbolIndices.count(RelEntry.Symbol))
504       report_fatal_error("symbol not found function/global index space:" +
505                          RelEntry.Symbol->getName());
506     return SymbolIndices[RelEntry.Symbol];
507   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
508     if (!TypeIndices.count(RelEntry.Symbol))
509       report_fatal_error("symbol not found in type index space:" +
510                          RelEntry.Symbol->getName());
511     return TypeIndices[RelEntry.Symbol];
512   default:
513     llvm_unreachable("invalid relocation type");
514   }
515 }
516
517 // Apply the portions of the relocation records that we can handle ourselves
518 // directly.
519 void WasmObjectWriter::applyRelocations(
520     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
521   raw_pwrite_stream &Stream = getStream();
522   for (const WasmRelocationEntry &RelEntry : Relocations) {
523     uint64_t Offset = ContentsOffset +
524                       RelEntry.FixupSection->getSectionOffset() +
525                       RelEntry.Offset;
526
527     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
528     switch (RelEntry.Type) {
529     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
530     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
531     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
532     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
533       uint32_t Index = getRelocationIndexValue(RelEntry);
534       WritePatchableSLEB(Stream, Index, Offset);
535       break;
536     }
537     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
538       uint32_t Index = getRelocationIndexValue(RelEntry);
539       WriteI32(Stream, Index, Offset);
540       break;
541     }
542     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
543       uint32_t Value = ProvisionalValue(RelEntry);
544       WritePatchableSLEB(Stream, Value, Offset);
545       break;
546     }
547     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
548       uint32_t Value = ProvisionalValue(RelEntry);
549       WritePatchableLEB(Stream, Value, Offset);
550       break;
551     }
552     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
553       uint32_t Value = ProvisionalValue(RelEntry);
554       WriteI32(Stream, Value, Offset);
555       break;
556     }
557     default:
558       llvm_unreachable("invalid relocation type");
559     }
560   }
561 }
562
563 // Write out the portions of the relocation records that the linker will
564 // need to handle.
565 void WasmObjectWriter::writeRelocations(
566     ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
567   raw_pwrite_stream &Stream = getStream();
568   for (const WasmRelocationEntry& RelEntry : Relocations) {
569
570     uint64_t Offset = RelEntry.Offset +
571                       RelEntry.FixupSection->getSectionOffset() + HeaderSize;
572     uint32_t Index = getRelocationIndexValue(RelEntry);
573
574     encodeULEB128(RelEntry.Type, Stream);
575     encodeULEB128(Offset, Stream);
576     encodeULEB128(Index, Stream);
577     if (RelEntry.hasAddend())
578       encodeSLEB128(RelEntry.Addend, Stream);
579   }
580 }
581
582 void WasmObjectWriter::writeTypeSection(
583     const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
584   if (FunctionTypes.empty())
585     return;
586
587   SectionBookkeeping Section;
588   startSection(Section, wasm::WASM_SEC_TYPE);
589
590   encodeULEB128(FunctionTypes.size(), getStream());
591
592   for (const WasmFunctionType &FuncTy : FunctionTypes) {
593     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
594     encodeULEB128(FuncTy.Params.size(), getStream());
595     for (wasm::ValType Ty : FuncTy.Params)
596       writeValueType(Ty);
597     encodeULEB128(FuncTy.Returns.size(), getStream());
598     for (wasm::ValType Ty : FuncTy.Returns)
599       writeValueType(Ty);
600   }
601
602   endSection(Section);
603 }
604
605
606 void WasmObjectWriter::writeImportSection(
607     const SmallVector<WasmImport, 4> &Imports) {
608   if (Imports.empty())
609     return;
610
611   SectionBookkeeping Section;
612   startSection(Section, wasm::WASM_SEC_IMPORT);
613
614   encodeULEB128(Imports.size(), getStream());
615   for (const WasmImport &Import : Imports) {
616     writeString(Import.ModuleName);
617     writeString(Import.FieldName);
618
619     encodeULEB128(Import.Kind, getStream());
620
621     switch (Import.Kind) {
622     case wasm::WASM_EXTERNAL_FUNCTION:
623       encodeULEB128(Import.Type, getStream());
624       break;
625     case wasm::WASM_EXTERNAL_GLOBAL:
626       encodeSLEB128(int32_t(Import.Type), getStream());
627       encodeULEB128(0, getStream()); // mutability
628       break;
629     default:
630       llvm_unreachable("unsupported import kind");
631     }
632   }
633
634   endSection(Section);
635 }
636
637 void WasmObjectWriter::writeFunctionSection(
638     const SmallVector<WasmFunction, 4> &Functions) {
639   if (Functions.empty())
640     return;
641
642   SectionBookkeeping Section;
643   startSection(Section, wasm::WASM_SEC_FUNCTION);
644
645   encodeULEB128(Functions.size(), getStream());
646   for (const WasmFunction &Func : Functions)
647     encodeULEB128(Func.Type, getStream());
648
649   endSection(Section);
650 }
651
652 void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
653   // For now, always emit the table section, since indirect calls are not
654   // valid without it. In the future, we could perhaps be more clever and omit
655   // it if there are no indirect calls.
656
657   SectionBookkeeping Section;
658   startSection(Section, wasm::WASM_SEC_TABLE);
659
660   encodeULEB128(1, getStream());                       // The number of tables.
661                                                        // Fixed to 1 for now.
662   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
663   encodeULEB128(0, getStream());                       // flags
664   encodeULEB128(NumElements, getStream());             // initial
665
666   endSection(Section);
667 }
668
669 void WasmObjectWriter::writeMemorySection(
670     const SmallVector<char, 0> &DataBytes) {
671   // For now, always emit the memory section, since loads and stores are not
672   // valid without it. In the future, we could perhaps be more clever and omit
673   // it if there are no loads or stores.
674   SectionBookkeeping Section;
675   uint32_t NumPages =
676       (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
677
678   startSection(Section, wasm::WASM_SEC_MEMORY);
679   encodeULEB128(1, getStream()); // number of memory spaces
680
681   encodeULEB128(0, getStream()); // flags
682   encodeULEB128(NumPages, getStream()); // initial
683
684   endSection(Section);
685 }
686
687 void WasmObjectWriter::writeGlobalSection(
688     const SmallVector<WasmGlobal, 4> &Globals) {
689   if (Globals.empty())
690     return;
691
692   SectionBookkeeping Section;
693   startSection(Section, wasm::WASM_SEC_GLOBAL);
694
695   encodeULEB128(Globals.size(), getStream());
696   for (const WasmGlobal &Global : Globals) {
697     writeValueType(Global.Type);
698     write8(Global.IsMutable);
699
700     if (Global.HasImport) {
701       assert(Global.InitialValue == 0);
702       write8(wasm::WASM_OPCODE_GET_GLOBAL);
703       encodeULEB128(Global.ImportIndex, getStream());
704     } else {
705       assert(Global.ImportIndex == 0);
706       write8(wasm::WASM_OPCODE_I32_CONST);
707       encodeSLEB128(Global.InitialValue, getStream()); // offset
708     }
709     write8(wasm::WASM_OPCODE_END);
710   }
711
712   endSection(Section);
713 }
714
715 void WasmObjectWriter::writeExportSection(
716     const SmallVector<WasmExport, 4> &Exports) {
717   if (Exports.empty())
718     return;
719
720   SectionBookkeeping Section;
721   startSection(Section, wasm::WASM_SEC_EXPORT);
722
723   encodeULEB128(Exports.size(), getStream());
724   for (const WasmExport &Export : Exports) {
725     writeString(Export.FieldName);
726     encodeSLEB128(Export.Kind, getStream());
727     encodeULEB128(Export.Index, getStream());
728   }
729
730   endSection(Section);
731 }
732
733 void WasmObjectWriter::writeElemSection(
734     const SmallVector<uint32_t, 4> &TableElems) {
735   if (TableElems.empty())
736     return;
737
738   SectionBookkeeping Section;
739   startSection(Section, wasm::WASM_SEC_ELEM);
740
741   encodeULEB128(1, getStream()); // number of "segments"
742   encodeULEB128(0, getStream()); // the table index
743
744   // init expr for starting offset
745   write8(wasm::WASM_OPCODE_I32_CONST);
746   encodeSLEB128(0, getStream());
747   write8(wasm::WASM_OPCODE_END);
748
749   encodeULEB128(TableElems.size(), getStream());
750   for (uint32_t Elem : TableElems)
751     encodeULEB128(Elem, getStream());
752
753   endSection(Section);
754 }
755
756 void WasmObjectWriter::writeCodeSection(
757     const MCAssembler &Asm, const MCAsmLayout &Layout,
758     const SmallVector<WasmFunction, 4> &Functions) {
759   if (Functions.empty())
760     return;
761
762   SectionBookkeeping Section;
763   startSection(Section, wasm::WASM_SEC_CODE);
764
765   encodeULEB128(Functions.size(), getStream());
766
767   for (const WasmFunction &Func : Functions) {
768     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
769
770     int64_t Size = 0;
771     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
772       report_fatal_error(".size expression must be evaluatable");
773
774     encodeULEB128(Size, getStream());
775
776     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
777
778     Asm.writeSectionData(&FuncSection, Layout);
779   }
780
781   // Apply fixups.
782   applyRelocations(CodeRelocations, Section.ContentsOffset);
783
784   endSection(Section);
785 }
786
787 uint64_t WasmObjectWriter::writeDataSection(
788     const SmallVector<char, 0> &DataBytes) {
789   if (DataBytes.empty())
790     return 0;
791
792   SectionBookkeeping Section;
793   startSection(Section, wasm::WASM_SEC_DATA);
794
795   encodeULEB128(1, getStream()); // count
796   encodeULEB128(0, getStream()); // memory index
797   write8(wasm::WASM_OPCODE_I32_CONST);
798   encodeSLEB128(0, getStream()); // offset
799   write8(wasm::WASM_OPCODE_END);
800   encodeULEB128(DataBytes.size(), getStream()); // size
801   uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
802   writeBytes(DataBytes); // data
803
804   // Apply fixups.
805   applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
806
807   endSection(Section);
808   return HeaderSize;
809 }
810
811 void WasmObjectWriter::writeNameSection(
812     const SmallVector<WasmFunction, 4> &Functions,
813     const SmallVector<WasmImport, 4> &Imports,
814     unsigned NumFuncImports) {
815   uint32_t TotalFunctions = NumFuncImports + Functions.size();
816   if (TotalFunctions == 0)
817     return;
818
819   SectionBookkeeping Section;
820   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
821   SectionBookkeeping SubSection;
822   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
823
824   encodeULEB128(TotalFunctions, getStream());
825   uint32_t Index = 0;
826   for (const WasmImport &Import : Imports) {
827     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
828       encodeULEB128(Index, getStream());
829       writeString(Import.FieldName);
830       ++Index;
831     }
832   }
833   for (const WasmFunction &Func : Functions) {
834     encodeULEB128(Index, getStream());
835     writeString(Func.Sym->getName());
836     ++Index;
837   }
838
839   endSection(SubSection);
840   endSection(Section);
841 }
842
843 void WasmObjectWriter::writeCodeRelocSection() {
844   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
845   // for descriptions of the reloc sections.
846
847   if (CodeRelocations.empty())
848     return;
849
850   SectionBookkeeping Section;
851   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
852
853   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
854   encodeULEB128(CodeRelocations.size(), getStream());
855
856   writeRelocations(CodeRelocations, 0);
857
858   endSection(Section);
859 }
860
861 void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
862   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
863   // for descriptions of the reloc sections.
864
865   if (DataRelocations.empty())
866     return;
867
868   SectionBookkeeping Section;
869   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
870
871   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
872   encodeULEB128(DataRelocations.size(), getStream());
873
874   writeRelocations(DataRelocations, DataSectionHeaderSize);
875
876   endSection(Section);
877 }
878
879 void WasmObjectWriter::writeLinkingMetaDataSection(
880     ArrayRef<StringRef> WeakSymbols, bool HasStackPointer,
881     uint32_t StackPointerGlobal) {
882   if (!HasStackPointer && WeakSymbols.empty())
883     return;
884
885   SectionBookkeeping Section;
886   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
887   SectionBookkeeping SubSection;
888
889   if (HasStackPointer) {
890     startSection(SubSection, wasm::WASM_STACK_POINTER);
891     encodeULEB128(StackPointerGlobal, getStream()); // id
892     endSection(SubSection);
893   }
894
895   if (WeakSymbols.size() != 0) {
896     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
897     encodeULEB128(WeakSymbols.size(), getStream());
898     for (const StringRef Export: WeakSymbols) {
899       writeString(Export);
900       encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
901     }
902     endSection(SubSection);
903   }
904
905   endSection(Section);
906 }
907
908 void WasmObjectWriter::writeObject(MCAssembler &Asm,
909                                    const MCAsmLayout &Layout) {
910   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
911   MCContext &Ctx = Asm.getContext();
912   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
913
914   // Collect information from the available symbols.
915   SmallVector<WasmFunctionType, 4> FunctionTypes;
916   SmallVector<WasmFunction, 4> Functions;
917   SmallVector<uint32_t, 4> TableElems;
918   SmallVector<WasmGlobal, 4> Globals;
919   SmallVector<WasmImport, 4> Imports;
920   SmallVector<WasmExport, 4> Exports;
921   SmallVector<StringRef, 4> WeakSymbols;
922   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
923   unsigned NumFuncImports = 0;
924   unsigned NumGlobalImports = 0;
925   SmallVector<char, 0> DataBytes;
926   uint32_t StackPointerGlobal = 0;
927   bool HasStackPointer = false;
928
929   // Populate the IsAddressTaken set.
930   for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
931     switch (RelEntry.Type) {
932     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
933     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
934       IsAddressTaken.insert(RelEntry.Symbol);
935       break;
936     default:
937       break;
938     }
939   }
940   for (const WasmRelocationEntry &RelEntry : DataRelocations) {
941     switch (RelEntry.Type) {
942     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
943     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
944       IsAddressTaken.insert(RelEntry.Symbol);
945       break;
946     default:
947       break;
948     }
949   }
950
951   // Populate the Imports set.
952   for (const MCSymbol &S : Asm.symbols()) {
953     const auto &WS = static_cast<const MCSymbolWasm &>(S);
954     int32_t Type;
955
956     if (WS.isFunction()) {
957       // Prepare the function's type, if we haven't seen it yet.
958       WasmFunctionType F;
959       F.Returns = WS.getReturns();
960       F.Params = WS.getParams();
961       auto Pair =
962           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
963       if (Pair.second)
964         FunctionTypes.push_back(F);
965
966       Type = Pair.first->second;
967     } else {
968       Type = int32_t(PtrType);
969     }
970
971     // If the symbol is not defined in this translation unit, import it.
972     if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
973       WasmImport Import;
974       Import.ModuleName = WS.getModuleName();
975       Import.FieldName = WS.getName();
976
977       if (WS.isFunction()) {
978         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
979         Import.Type = Type;
980         SymbolIndices[&WS] = NumFuncImports;
981         ++NumFuncImports;
982       } else {
983         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
984         Import.Type = Type;
985         SymbolIndices[&WS] = NumGlobalImports;
986         ++NumGlobalImports;
987       }
988
989       Imports.push_back(Import);
990     }
991   }
992
993   // In the special .global_variables section, we've encoded global
994   // variables used by the function. Translate them into the Globals
995   // list.
996   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
997   if (!GlobalVars->getFragmentList().empty()) {
998     if (GlobalVars->getFragmentList().size() != 1)
999       report_fatal_error("only one .global_variables fragment supported");
1000     const MCFragment &Frag = *GlobalVars->begin();
1001     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1002       report_fatal_error("only data supported in .global_variables");
1003     const auto &DataFrag = cast<MCDataFragment>(Frag);
1004     if (!DataFrag.getFixups().empty())
1005       report_fatal_error("fixups not supported in .global_variables");
1006     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1007     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1008                      *end = (const uint8_t *)Contents.data() + Contents.size();
1009          p != end; ) {
1010       WasmGlobal G;
1011       if (end - p < 3)
1012         report_fatal_error("truncated global variable encoding");
1013       G.Type = wasm::ValType(int8_t(*p++));
1014       G.IsMutable = bool(*p++);
1015       G.HasImport = bool(*p++);
1016       if (G.HasImport) {
1017         G.InitialValue = 0;
1018
1019         WasmImport Import;
1020         Import.ModuleName = (const char *)p;
1021         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1022         if (!nul)
1023           report_fatal_error("global module name must be nul-terminated");
1024         p = nul + 1;
1025         nul = (const uint8_t *)memchr(p, '\0', end - p);
1026         if (!nul)
1027           report_fatal_error("global base name must be nul-terminated");
1028         Import.FieldName = (const char *)p;
1029         p = nul + 1;
1030
1031         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1032         Import.Type = int32_t(G.Type);
1033
1034         G.ImportIndex = NumGlobalImports;
1035         ++NumGlobalImports;
1036
1037         Imports.push_back(Import);
1038       } else {
1039         unsigned n;
1040         G.InitialValue = decodeSLEB128(p, &n);
1041         G.ImportIndex = 0;
1042         if ((ptrdiff_t)n > end - p)
1043           report_fatal_error("global initial value must be valid SLEB128");
1044         p += n;
1045       }
1046       Globals.push_back(G);
1047     }
1048   }
1049
1050   // In the special .stack_pointer section, we've encoded the stack pointer
1051   // index.
1052   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1053   if (!StackPtr->getFragmentList().empty()) {
1054     if (StackPtr->getFragmentList().size() != 1)
1055       report_fatal_error("only one .stack_pointer fragment supported");
1056     const MCFragment &Frag = *StackPtr->begin();
1057     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1058       report_fatal_error("only data supported in .stack_pointer");
1059     const auto &DataFrag = cast<MCDataFragment>(Frag);
1060     if (!DataFrag.getFixups().empty())
1061       report_fatal_error("fixups not supported in .stack_pointer");
1062     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1063     if (Contents.size() != 4)
1064       report_fatal_error("only one entry supported in .stack_pointer");
1065     HasStackPointer = true;
1066     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1067   }
1068
1069   // Handle regular defined and undefined symbols.
1070   for (const MCSymbol &S : Asm.symbols()) {
1071     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1072     // or used in relocations.
1073     if (S.isTemporary() && S.getName().empty())
1074       continue;
1075
1076     // Variable references (weak references) are handled in a second pass
1077     if (S.isVariable())
1078       continue;
1079
1080     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1081     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1082                  << " isDefined=" << S.isDefined() << " isExternal="
1083                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1084                  << " isFunction=" << WS.isFunction()
1085                  << " isWeak=" << WS.isWeak()
1086                  << " isVariable=" << WS.isVariable() << "\n");
1087
1088     if (WS.isWeak())
1089       WeakSymbols.push_back(WS.getName());
1090
1091     unsigned Index;
1092
1093     if (WS.isFunction()) {
1094       // Prepare the function's type, if we haven't seen it yet.
1095       WasmFunctionType F;
1096       F.Returns = WS.getReturns();
1097       F.Params = WS.getParams();
1098       auto Pair =
1099           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1100       if (Pair.second)
1101         FunctionTypes.push_back(F);
1102
1103       int32_t Type = Pair.first->second;
1104
1105       if (WS.isDefined(/*SetUsed=*/false)) {
1106         if (WS.getOffset() != 0)
1107           report_fatal_error(
1108               "function sections must contain one function each");
1109
1110         if (WS.getSize() == 0)
1111           report_fatal_error(
1112               "function symbols must have a size set with .size");
1113
1114         // A definition. Take the next available index.
1115         Index = NumFuncImports + Functions.size();
1116
1117         // Prepare the function.
1118         WasmFunction Func;
1119         Func.Type = Type;
1120         Func.Sym = &WS;
1121         SymbolIndices[&WS] = Index;
1122         Functions.push_back(Func);
1123       } else {
1124         // Should be no such thing as weak undefined symbol
1125         assert(!WS.isVariable());
1126
1127         // An import; the index was assigned above.
1128         Index = SymbolIndices.find(&WS)->second;
1129       }
1130
1131       // If needed, prepare the function to be called indirectly.
1132       if (IsAddressTaken.count(&WS)) {
1133         IndirectSymbolIndices[&WS] = TableElems.size();
1134         TableElems.push_back(Index);
1135       }
1136     } else {
1137       if (WS.isTemporary() && !WS.getSize())
1138         continue;
1139
1140       if (!WS.isDefined(/*SetUsed=*/false))
1141         continue;
1142
1143       if (WS.getOffset() != 0)
1144         report_fatal_error("data sections must contain one variable each: " +
1145                            WS.getName());
1146       if (!WS.getSize())
1147         report_fatal_error("data symbols must have a size set with .size: " +
1148                            WS.getName());
1149
1150       int64_t Size = 0;
1151       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1152         report_fatal_error(".size expression must be evaluatable");
1153
1154       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1155
1156       if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1157         report_fatal_error("data sections must contain at most one variable");
1158
1159       DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1160
1161       DataSection.setSectionOffset(DataBytes.size());
1162
1163       for (const MCFragment &Frag : DataSection) {
1164         if (Frag.hasInstructions())
1165           report_fatal_error("only data supported in data sections");
1166
1167         if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1168           if (Align->getValueSize() != 1)
1169             report_fatal_error("only byte values supported for alignment");
1170           // If nops are requested, use zeros, as this is the data section.
1171           uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1172           uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1173                                                      Align->getAlignment()),
1174                                              DataBytes.size() +
1175                                                  Align->getMaxBytesToEmit());
1176           DataBytes.resize(Size, Value);
1177         } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
1178           DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1179         } else {
1180           const auto &DataFrag = cast<MCDataFragment>(Frag);
1181           const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1182
1183           DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1184         }
1185       }
1186
1187       // For each global, prepare a corresponding wasm global holding its
1188       // address.  For externals these will also be named exports.
1189       Index = NumGlobalImports + Globals.size();
1190
1191       WasmGlobal Global;
1192       Global.Type = PtrType;
1193       Global.IsMutable = false;
1194       Global.HasImport = false;
1195       Global.InitialValue = DataSection.getSectionOffset();
1196       Global.ImportIndex = 0;
1197       SymbolIndices[&WS] = Index;
1198       Globals.push_back(Global);
1199     }
1200
1201     // If the symbol is visible outside this translation unit, export it.
1202     if (WS.isExternal() && WS.isDefined(/*SetUsed=*/false)) {
1203       WasmExport Export;
1204       Export.FieldName = WS.getName();
1205       Export.Index = Index;
1206       if (WS.isFunction())
1207         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1208       else
1209         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1210       Exports.push_back(Export);
1211     }
1212   }
1213
1214   // Handle weak aliases
1215   for (const MCSymbol &S : Asm.symbols()) {
1216     if (!S.isVariable())
1217       continue;
1218     assert(S.isExternal());
1219     assert(S.isDefined(/*SetUsed=*/false));
1220
1221     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1222
1223     // Find the target symbol of this weak alias
1224     const MCExpr *Expr = WS.getVariableValue();
1225     auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
1226     const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
1227     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1228     DEBUG(dbgs() << "Weak alias: '" << WS << "' -> '" << ResolvedSym << "' = " << Index << "\n");
1229     SymbolIndices[&WS] = Index;
1230
1231     WasmExport Export;
1232     Export.FieldName = WS.getName();
1233     Export.Index = Index;
1234     if (WS.isFunction())
1235       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1236     else
1237       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1238     WeakSymbols.push_back(Export.FieldName);
1239     Exports.push_back(Export);
1240   }
1241
1242   // Add types for indirect function calls.
1243   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1244     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1245       continue;
1246
1247     WasmFunctionType F;
1248     F.Returns = Fixup.Symbol->getReturns();
1249     F.Params = Fixup.Symbol->getParams();
1250     auto Pair =
1251         FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1252     if (Pair.second)
1253       FunctionTypes.push_back(F);
1254
1255     TypeIndices[Fixup.Symbol] = Pair.first->second;
1256   }
1257
1258   // Write out the Wasm header.
1259   writeHeader(Asm);
1260
1261   writeTypeSection(FunctionTypes);
1262   writeImportSection(Imports);
1263   writeFunctionSection(Functions);
1264   writeTableSection(TableElems.size());
1265   writeMemorySection(DataBytes);
1266   writeGlobalSection(Globals);
1267   writeExportSection(Exports);
1268   // TODO: Start Section
1269   writeElemSection(TableElems);
1270   writeCodeSection(Asm, Layout, Functions);
1271   uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
1272   writeNameSection(Functions, Imports, NumFuncImports);
1273   writeCodeRelocSection();
1274   writeDataRelocSection(DataSectionHeaderSize);
1275   writeLinkingMetaDataSection(WeakSymbols, HasStackPointer, StackPointerGlobal);
1276
1277   // TODO: Translate the .comment section to the output.
1278   // TODO: Translate debug sections to the output.
1279 }
1280
1281 MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1282                                              raw_pwrite_stream &OS) {
1283   return new WasmObjectWriter(MOTW, OS);
1284 }