118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
318eafb6cSDan Gohman //                     The LLVM Compiler Infrastructure
418eafb6cSDan Gohman //
518eafb6cSDan Gohman // This file is distributed under the University of Illinois Open Source
618eafb6cSDan Gohman // License. See LICENSE.TXT for details.
718eafb6cSDan Gohman //
818eafb6cSDan Gohman //===----------------------------------------------------------------------===//
918eafb6cSDan Gohman //
1018eafb6cSDan Gohman // This file implements Wasm object file writer information.
1118eafb6cSDan Gohman //
1218eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1318eafb6cSDan Gohman 
1418eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1518eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
16264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
31d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4330e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
51d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
52d934cb88SDan Gohman   uint64_t ContentsOffset;
53d934cb88SDan Gohman };
54d934cb88SDan Gohman 
559e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
569e15f359SSam Clegg // DenseMap key.
579e15f359SSam Clegg struct WasmFunctionType {
589e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
599e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
609e15f359SSam Clegg 
619e15f359SSam Clegg   // The return types of the function.
629e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
639e15f359SSam Clegg 
649e15f359SSam Clegg   // The parameter types of the function.
659e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
669e15f359SSam Clegg 
679e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
689e15f359SSam Clegg 
699e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
709e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
719e15f359SSam Clegg            Params == Other.Params;
729e15f359SSam Clegg   }
739e15f359SSam Clegg };
749e15f359SSam Clegg 
759e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
769e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
779e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
789e15f359SSam Clegg     WasmFunctionType FuncTy;
799e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
809e15f359SSam Clegg     return FuncTy;
819e15f359SSam Clegg   }
829e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
839e15f359SSam Clegg     WasmFunctionType FuncTy;
849e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
859e15f359SSam Clegg     return FuncTy;
869e15f359SSam Clegg   }
879e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
889e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
899e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
909e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
919e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
929e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
939e15f359SSam Clegg     return Value;
949e15f359SSam Clegg   }
959e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
969e15f359SSam Clegg                       const WasmFunctionType &RHS) {
979e15f359SSam Clegg     return LHS == RHS;
989e15f359SSam Clegg   }
999e15f359SSam Clegg };
1009e15f359SSam Clegg 
1017c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1027c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1037c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1047c395943SSam Clegg // wasm data segment.
1057c395943SSam Clegg struct WasmDataSegment {
1067c395943SSam Clegg   MCSectionWasm *Section;
107d95ed959SSam Clegg   StringRef Name;
1087c395943SSam Clegg   uint32_t Offset;
10963ebb813SSam Clegg   uint32_t Alignment;
11063ebb813SSam Clegg   uint32_t Flags;
1117c395943SSam Clegg   SmallVector<char, 4> Data;
1127c395943SSam Clegg };
1137c395943SSam Clegg 
1149e15f359SSam Clegg // A wasm import to be written into the import section.
1159e15f359SSam Clegg struct WasmImport {
1169e15f359SSam Clegg   StringRef ModuleName;
1179e15f359SSam Clegg   StringRef FieldName;
1189e15f359SSam Clegg   unsigned Kind;
1199e15f359SSam Clegg   int32_t Type;
12032ce5ca0SDan Gohman   bool IsMutable;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm function to be written into the function section.
1249e15f359SSam Clegg struct WasmFunction {
1259e15f359SSam Clegg   int32_t Type;
1269e15f359SSam Clegg   const MCSymbolWasm *Sym;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
1299e15f359SSam Clegg // A wasm export to be written into the export section.
1309e15f359SSam Clegg struct WasmExport {
1319e15f359SSam Clegg   StringRef FieldName;
1329e15f359SSam Clegg   unsigned Kind;
1339e15f359SSam Clegg   uint32_t Index;
1349e15f359SSam Clegg };
1359e15f359SSam Clegg 
1369e15f359SSam Clegg // A wasm global to be written into the global section.
1379e15f359SSam Clegg struct WasmGlobal {
1389e15f359SSam Clegg   wasm::ValType Type;
1399e15f359SSam Clegg   bool IsMutable;
1409e15f359SSam Clegg   bool HasImport;
1419e15f359SSam Clegg   uint64_t InitialValue;
1429e15f359SSam Clegg   uint32_t ImportIndex;
1439e15f359SSam Clegg };
1449e15f359SSam Clegg 
145ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
146ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
147ea7caceeSSam Clegg // WasmComdatEntry.
148ea7caceeSSam Clegg struct WasmComdatEntry {
149ea7caceeSSam Clegg   unsigned Kind;
150ea7caceeSSam Clegg   uint32_t Index;
151ea7caceeSSam Clegg };
152ea7caceeSSam Clegg 
1536dc65e91SSam Clegg // Information about a single relocation.
1546dc65e91SSam Clegg struct WasmRelocationEntry {
1556dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1566dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1576dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1586dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
159fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1606dc65e91SSam Clegg 
1616dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1626dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
163fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1646dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1656dc65e91SSam Clegg         FixupSection(FixupSection) {}
1666dc65e91SSam Clegg 
167acd7d2b0SSam Clegg   bool hasAddend() const {
168acd7d2b0SSam Clegg     switch (Type) {
16913a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
17013a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
17113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
172acd7d2b0SSam Clegg       return true;
173acd7d2b0SSam Clegg     default:
174acd7d2b0SSam Clegg       return false;
175acd7d2b0SSam Clegg     }
176acd7d2b0SSam Clegg   }
177acd7d2b0SSam Clegg 
1786dc65e91SSam Clegg   void print(raw_ostream &Out) const {
1799bf73c07SSam Clegg     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
180759631c7SSam Clegg         << ", Type=" << Type
181759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1826dc65e91SSam Clegg   }
183b7787fd0SSam Clegg 
184615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
185b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
186b7787fd0SSam Clegg #endif
1876dc65e91SSam Clegg };
1886dc65e91SSam Clegg 
1891fb8daa6SSam Clegg #if !defined(NDEBUG)
1907f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
191b7787fd0SSam Clegg   Rel.print(OS);
192b7787fd0SSam Clegg   return OS;
193b7787fd0SSam Clegg }
1941fb8daa6SSam Clegg #endif
195b7787fd0SSam Clegg 
19618eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
19718eafb6cSDan Gohman   /// Helper struct for containing some precomputed information on symbols.
19818eafb6cSDan Gohman   struct WasmSymbolData {
19918eafb6cSDan Gohman     const MCSymbolWasm *Symbol;
20018eafb6cSDan Gohman     StringRef Name;
20118eafb6cSDan Gohman 
20218eafb6cSDan Gohman     // Support lexicographic sorting.
20318eafb6cSDan Gohman     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
20418eafb6cSDan Gohman   };
20518eafb6cSDan Gohman 
20618eafb6cSDan Gohman   /// The target specific Wasm writer instance.
20718eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
20818eafb6cSDan Gohman 
209d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
210d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
211d934cb88SDan Gohman 
212d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
213d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
214d934cb88SDan Gohman 
215d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
216acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
217acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
218d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
219d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
220d99f6078SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
221d99f6078SSam Clegg   // Maps function/global symbols to the function/global index space.
222acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
223acd7d2b0SSam Clegg 
224acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
225acd7d2b0SSam Clegg       FunctionTypeIndices;
2265e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2277c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2289f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2297c395943SSam Clegg   unsigned NumGlobalImports = 0;
230d934cb88SDan Gohman 
23118eafb6cSDan Gohman   // TargetObjectWriter wrappers.
23218eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
233ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
234ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
23518eafb6cSDan Gohman   }
23618eafb6cSDan Gohman 
237d934cb88SDan Gohman   void startSection(SectionBookkeeping &Section, unsigned SectionId,
238d934cb88SDan Gohman                     const char *Name = nullptr);
239d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
240d934cb88SDan Gohman 
24118eafb6cSDan Gohman public:
2421301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2431301a878SLang Hames                    raw_pwrite_stream &OS)
2441301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2451301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
24618eafb6cSDan Gohman 
24718eafb6cSDan Gohman   ~WasmObjectWriter() override;
24818eafb6cSDan Gohman 
2490917c9e4SDan Gohman private:
250acd7d2b0SSam Clegg   void reset() override {
251acd7d2b0SSam Clegg     CodeRelocations.clear();
252acd7d2b0SSam Clegg     DataRelocations.clear();
253acd7d2b0SSam Clegg     TypeIndices.clear();
254acd7d2b0SSam Clegg     SymbolIndices.clear();
255d99f6078SSam Clegg     IndirectSymbolIndices.clear();
256acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2575e3d33a7SSam Clegg     FunctionTypes.clear();
2587c395943SSam Clegg     Globals.clear();
259acd7d2b0SSam Clegg     MCObjectWriter::reset();
2609f3fe42eSSam Clegg     NumFunctionImports = 0;
2617c395943SSam Clegg     NumGlobalImports = 0;
262acd7d2b0SSam Clegg   }
263acd7d2b0SSam Clegg 
26418eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
26518eafb6cSDan Gohman 
26618eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
26718eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
268ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
26918eafb6cSDan Gohman 
27018eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
27118eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
27218eafb6cSDan Gohman 
27318eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2749e15f359SSam Clegg 
275b7787fd0SSam Clegg   void writeString(const StringRef Str) {
276b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
277b7787fd0SSam Clegg     writeBytes(Str);
278b7787fd0SSam Clegg   }
279b7787fd0SSam Clegg 
2809e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
2819e15f359SSam Clegg     encodeSLEB128(int32_t(Ty), getStream());
2829e15f359SSam Clegg   }
2839e15f359SSam Clegg 
284457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
285f950b24aSSam Clegg   void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
286f950b24aSSam Clegg                           uint32_t NumElements);
287457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
2887c395943SSam Clegg   void writeGlobalSection();
289457fb0b4SSam Clegg   void writeExportSection(ArrayRef<WasmExport> Exports);
290457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
2919e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
292457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
293457fb0b4SSam Clegg   void writeDataSection(ArrayRef<WasmDataSegment> Segments);
294457fb0b4SSam Clegg   void writeNameSection(ArrayRef<WasmFunction> Functions,
2959f3fe42eSSam Clegg                         ArrayRef<WasmImport> Imports);
296acd7d2b0SSam Clegg   void writeCodeRelocSection();
2977c395943SSam Clegg   void writeDataRelocSection();
29831a2c809SSam Clegg   void writeLinkingMetaDataSection(
29931a2c809SSam Clegg       ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
300ea7caceeSSam Clegg       ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
301ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
302ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
303acd7d2b0SSam Clegg 
3047c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
305acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
306acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
307acd7d2b0SSam Clegg 
3087c395943SSam Clegg   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
309acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3105e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
3115e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
31218eafb6cSDan Gohman };
3139e15f359SSam Clegg 
31418eafb6cSDan Gohman } // end anonymous namespace
31518eafb6cSDan Gohman 
31618eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
31718eafb6cSDan Gohman 
318d934cb88SDan Gohman // Write out a section header and a patchable section size field.
319d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
320d934cb88SDan Gohman                                     unsigned SectionId,
321d934cb88SDan Gohman                                     const char *Name) {
322d934cb88SDan Gohman   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
323d934cb88SDan Gohman          "Only custom sections can have names");
324d934cb88SDan Gohman 
325b7787fd0SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
326e2688c43SDerek Schuff   encodeULEB128(SectionId, getStream());
327d934cb88SDan Gohman 
328d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
329d934cb88SDan Gohman 
330d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
331d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
332d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
333d934cb88SDan Gohman 
334d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
335d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
336d934cb88SDan Gohman 
337d934cb88SDan Gohman   // Custom sections in wasm also have a string identifier.
338d934cb88SDan Gohman   if (SectionId == wasm::WASM_SEC_CUSTOM) {
339b7787fd0SSam Clegg     assert(Name);
340b7787fd0SSam Clegg     writeString(StringRef(Name));
341d934cb88SDan Gohman   }
342d934cb88SDan Gohman }
343d934cb88SDan Gohman 
344d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
345d934cb88SDan Gohman // section size field at the start of the section.
346d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
347d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
348d934cb88SDan Gohman   if (uint32_t(Size) != Size)
349d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
350d934cb88SDan Gohman 
351b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
352d934cb88SDan Gohman 
353d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
354d934cb88SDan Gohman   // the section id byte.
355d934cb88SDan Gohman   uint8_t Buffer[16];
35666a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
357d934cb88SDan Gohman   assert(SizeLen == 5);
358d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
359d934cb88SDan Gohman }
360d934cb88SDan Gohman 
36118eafb6cSDan Gohman // Emit the Wasm header.
36218eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3637ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3647ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
36518eafb6cSDan Gohman }
36618eafb6cSDan Gohman 
36718eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
36818eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
36918eafb6cSDan Gohman }
37018eafb6cSDan Gohman 
37118eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
37218eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
37318eafb6cSDan Gohman                                         const MCFragment *Fragment,
37418eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
375ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
376ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
377ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
378ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
379fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
380d934cb88SDan Gohman   uint64_t C = Target.getConstant();
381d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
382d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
383d934cb88SDan Gohman 
384bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
385bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
386bafe6902SSam Clegg     return;
387bafe6902SSam Clegg 
388d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
389d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
390d934cb88SDan Gohman            "Should not have constructed this");
391d934cb88SDan Gohman 
392d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
393d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
394d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
395d934cb88SDan Gohman 
396d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
397d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
398d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
399d934cb88SDan Gohman     if (IsPCRel) {
400d934cb88SDan Gohman       Ctx.reportError(
401d934cb88SDan Gohman           Fixup.getLoc(),
402d934cb88SDan Gohman           "No relocation available to represent this relative expression");
403d934cb88SDan Gohman       return;
404d934cb88SDan Gohman     }
405d934cb88SDan Gohman 
406d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
407d934cb88SDan Gohman 
408d934cb88SDan Gohman     if (SymB.isUndefined()) {
409d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
410d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
411d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
412d934cb88SDan Gohman       return;
413d934cb88SDan Gohman     }
414d934cb88SDan Gohman 
415d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
416d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
417d934cb88SDan Gohman     if (&SecB != &FixupSection) {
418d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
419d934cb88SDan Gohman                       "Cannot represent a difference across sections");
420d934cb88SDan Gohman       return;
421d934cb88SDan Gohman     }
422d934cb88SDan Gohman 
423d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
424d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
425d934cb88SDan Gohman     IsPCRel = true;
426d934cb88SDan Gohman     C -= K;
427d934cb88SDan Gohman   }
428d934cb88SDan Gohman 
429d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
430d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
431d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
432d934cb88SDan Gohman 
433d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
434d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4356ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4366ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4376ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
438d934cb88SDan Gohman   }
439d934cb88SDan Gohman 
440d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
441d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
442d934cb88SDan Gohman   // be negative and don't wrap.
443d934cb88SDan Gohman   FixedValue = 0;
444d934cb88SDan Gohman 
4456ad8f190SSam Clegg   if (SymA)
446d934cb88SDan Gohman     SymA->setUsedInReloc();
447d934cb88SDan Gohman 
448ae03c1e7SSam Clegg   assert(!IsPCRel);
4499d24fb7fSSam Clegg   assert(SymA);
4509d24fb7fSSam Clegg 
451ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
452ae03c1e7SSam Clegg 
453d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
454b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
455d934cb88SDan Gohman 
45612fd3da9SSam Clegg   if (FixupSection.isWasmData())
457d934cb88SDan Gohman     DataRelocations.push_back(Rec);
45812fd3da9SSam Clegg   else if (FixupSection.getKind().isText())
45912fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
46012fd3da9SSam Clegg   else if (!FixupSection.getKind().isMetadata())
46112fd3da9SSam Clegg     // TODO(sbc): Add support for debug sections.
46212fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
463d934cb88SDan Gohman }
464d934cb88SDan Gohman 
465d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
466d934cb88SDan Gohman // to allow patching.
467d934cb88SDan Gohman static void
468d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
469d934cb88SDan Gohman   uint8_t Buffer[5];
47066a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
471d934cb88SDan Gohman   assert(SizeLen == 5);
472d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
473d934cb88SDan Gohman }
474d934cb88SDan Gohman 
475d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
476d934cb88SDan Gohman // to allow patching.
477d934cb88SDan Gohman static void
478d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
479d934cb88SDan Gohman   uint8_t Buffer[5];
48066a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
481d934cb88SDan Gohman   assert(SizeLen == 5);
482d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
483d934cb88SDan Gohman }
484d934cb88SDan Gohman 
485d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
486d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
487d934cb88SDan Gohman   uint8_t Buffer[4];
488d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
489d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
490d934cb88SDan Gohman }
491d934cb88SDan Gohman 
492aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
493aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
494aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
495aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
496aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
497aff1c4dfSSam Clegg   }
498aff1c4dfSSam Clegg   return &Symbol;
499aff1c4dfSSam Clegg }
500aff1c4dfSSam Clegg 
501d934cb88SDan Gohman // Compute a value to write into the code at the location covered
502*60ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
503*60ec3034SSam Clegg // to make the object format more readable and more likely to be directly
504*60ec3034SSam Clegg // useable.
5057c395943SSam Clegg uint32_t
5067c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
507d934cb88SDan Gohman 
508*60ec3034SSam Clegg   switch (RelEntry.Type) {
509*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
510*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
511*60ec3034SSam Clegg     // Provitional value is the indirect symbol index
512*60ec3034SSam Clegg     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
513*60ec3034SSam Clegg       report_fatal_error("symbol not found in table index space: " +
514*60ec3034SSam Clegg                          RelEntry.Symbol->getName());
515*60ec3034SSam Clegg     return IndirectSymbolIndices[RelEntry.Symbol];
516*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
517*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
518*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
519*60ec3034SSam Clegg     // Provitional value is function/type/global index itself
520*60ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
521*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
522*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
523*60ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
524*60ec3034SSam Clegg     // Provitional value is address of the global
525*60ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
526270ed1b3SSam Clegg     // For undefined symbols, use zero
527cd65f698SSam Clegg     if (!Sym->isDefined())
528270ed1b3SSam Clegg       return 0;
529d934cb88SDan Gohman 
5307c395943SSam Clegg     uint32_t GlobalIndex = SymbolIndices[Sym];
5317c395943SSam Clegg     const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
5327c395943SSam Clegg     uint64_t Address = Global.InitialValue + RelEntry.Addend;
533d934cb88SDan Gohman 
534d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
535*60ec3034SSam Clegg     return Address;
536*60ec3034SSam Clegg   }
537*60ec3034SSam Clegg   default:
538*60ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
539*60ec3034SSam Clegg   }
540d934cb88SDan Gohman }
541d934cb88SDan Gohman 
542759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
54363ebb813SSam Clegg                     MCSectionWasm &DataSection) {
544759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
545759631c7SSam Clegg 
54663ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
54763ebb813SSam Clegg 
548c55d13f4SSam Clegg   size_t LastFragmentSize = 0;
549759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
550759631c7SSam Clegg     if (Frag.hasInstructions())
551759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
552759631c7SSam Clegg 
553759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
554759631c7SSam Clegg       if (Align->getValueSize() != 1)
555759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
556759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
557759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
558759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
559759631c7SSam Clegg                                                  Align->getAlignment()),
560759631c7SSam Clegg                                          DataBytes.size() +
561759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
562759631c7SSam Clegg       DataBytes.resize(Size, Value);
563759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
564d707c370SRafael Espindola       int64_t Size;
565d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
566d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
567d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
568759631c7SSam Clegg     } else {
569759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
570759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
571759631c7SSam Clegg 
572759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
573c55d13f4SSam Clegg       LastFragmentSize = Contents.size();
574759631c7SSam Clegg     }
575759631c7SSam Clegg   }
576759631c7SSam Clegg 
577c55d13f4SSam Clegg   // Don't allow empty segments, or segments that end with zero-sized
578c55d13f4SSam Clegg   // fragment, otherwise the linker cannot map symbols to a unique
579c55d13f4SSam Clegg   // data segment.  This can be triggered by zero-sized structs
580c55d13f4SSam Clegg   // See: test/MC/WebAssembly/bss.ll
581c55d13f4SSam Clegg   if (LastFragmentSize == 0)
582c55d13f4SSam Clegg     DataBytes.resize(DataBytes.size() + 1);
583759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
584759631c7SSam Clegg }
585759631c7SSam Clegg 
586*60ec3034SSam Clegg uint32_t
587*60ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
588*60ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
589b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
590b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
591b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
592acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
593acd7d2b0SSam Clegg   }
594*60ec3034SSam Clegg 
595*60ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
596*60ec3034SSam Clegg     report_fatal_error("symbol not found in function/global index space: " +
597*60ec3034SSam Clegg                        RelEntry.Symbol->getName());
598*60ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
599acd7d2b0SSam Clegg }
600acd7d2b0SSam Clegg 
601d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
602d934cb88SDan Gohman // directly.
603acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
604acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
605acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
606d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
607d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
608d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
609d934cb88SDan Gohman                       RelEntry.Offset;
610d934cb88SDan Gohman 
611b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
612*60ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
613*60ec3034SSam Clegg 
614acd7d2b0SSam Clegg     switch (RelEntry.Type) {
615acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6169d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
617*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
618*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
619d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
620d934cb88SDan Gohman       break;
621*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
622*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
623d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
624d934cb88SDan Gohman       break;
625*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
626*60ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
627*60ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
628*60ec3034SSam Clegg       break;
629d934cb88SDan Gohman     default:
6309d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
631d934cb88SDan Gohman     }
632d934cb88SDan Gohman   }
63318eafb6cSDan Gohman }
63418eafb6cSDan Gohman 
635acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will
636970d02c4SDan Gohman // need to handle.
637acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations(
6387c395943SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
639acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
640acd7d2b0SSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
641970d02c4SDan Gohman 
642acd7d2b0SSam Clegg     uint64_t Offset = RelEntry.Offset +
6437c395943SSam Clegg                       RelEntry.FixupSection->getSectionOffset();
644acd7d2b0SSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
645970d02c4SDan Gohman 
646acd7d2b0SSam Clegg     encodeULEB128(RelEntry.Type, Stream);
647970d02c4SDan Gohman     encodeULEB128(Offset, Stream);
648acd7d2b0SSam Clegg     encodeULEB128(Index, Stream);
649acd7d2b0SSam Clegg     if (RelEntry.hasAddend())
650acd7d2b0SSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
651970d02c4SDan Gohman   }
652970d02c4SDan Gohman }
653970d02c4SDan Gohman 
6549e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
655457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
6569e15f359SSam Clegg   if (FunctionTypes.empty())
6579e15f359SSam Clegg     return;
6589e15f359SSam Clegg 
6599e15f359SSam Clegg   SectionBookkeeping Section;
6609e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6619e15f359SSam Clegg 
6629e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
6639e15f359SSam Clegg 
6649e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
6659e15f359SSam Clegg     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
6669e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
6679e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
6689e15f359SSam Clegg       writeValueType(Ty);
6699e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
6709e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
6719e15f359SSam Clegg       writeValueType(Ty);
6729e15f359SSam Clegg   }
6739e15f359SSam Clegg 
6749e15f359SSam Clegg   endSection(Section);
6759e15f359SSam Clegg }
6769e15f359SSam Clegg 
677f950b24aSSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
678f950b24aSSam Clegg                                           uint32_t DataSize,
679f950b24aSSam Clegg                                           uint32_t NumElements) {
6809e15f359SSam Clegg   if (Imports.empty())
6819e15f359SSam Clegg     return;
6829e15f359SSam Clegg 
683f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
684f950b24aSSam Clegg 
6859e15f359SSam Clegg   SectionBookkeeping Section;
6869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
6879e15f359SSam Clegg 
6889e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
6899e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
690b7787fd0SSam Clegg     writeString(Import.ModuleName);
691b7787fd0SSam Clegg     writeString(Import.FieldName);
6929e15f359SSam Clegg 
6939e15f359SSam Clegg     encodeULEB128(Import.Kind, getStream());
6949e15f359SSam Clegg 
6959e15f359SSam Clegg     switch (Import.Kind) {
6969e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
6979e15f359SSam Clegg       encodeULEB128(Import.Type, getStream());
6989e15f359SSam Clegg       break;
6999e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7009e15f359SSam Clegg       encodeSLEB128(int32_t(Import.Type), getStream());
70132ce5ca0SDan Gohman       encodeULEB128(int32_t(Import.IsMutable), getStream());
7029e15f359SSam Clegg       break;
703f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
704f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
705f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
706f950b24aSSam Clegg       break;
707f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
708f950b24aSSam Clegg       encodeSLEB128(int32_t(Import.Type), getStream());
709f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
710f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
711f950b24aSSam Clegg       break;
7129e15f359SSam Clegg     default:
7139e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7149e15f359SSam Clegg     }
7159e15f359SSam Clegg   }
7169e15f359SSam Clegg 
7179e15f359SSam Clegg   endSection(Section);
7189e15f359SSam Clegg }
7199e15f359SSam Clegg 
720457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7219e15f359SSam Clegg   if (Functions.empty())
7229e15f359SSam Clegg     return;
7239e15f359SSam Clegg 
7249e15f359SSam Clegg   SectionBookkeeping Section;
7259e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7269e15f359SSam Clegg 
7279e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7289e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7299e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7309e15f359SSam Clegg 
7319e15f359SSam Clegg   endSection(Section);
7329e15f359SSam Clegg }
7339e15f359SSam Clegg 
7347c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7359e15f359SSam Clegg   if (Globals.empty())
7369e15f359SSam Clegg     return;
7379e15f359SSam Clegg 
7389e15f359SSam Clegg   SectionBookkeeping Section;
7399e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7409e15f359SSam Clegg 
7419e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7429e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7439e15f359SSam Clegg     writeValueType(Global.Type);
7449e15f359SSam Clegg     write8(Global.IsMutable);
7459e15f359SSam Clegg 
7469e15f359SSam Clegg     if (Global.HasImport) {
7479e15f359SSam Clegg       assert(Global.InitialValue == 0);
7489e15f359SSam Clegg       write8(wasm::WASM_OPCODE_GET_GLOBAL);
7499e15f359SSam Clegg       encodeULEB128(Global.ImportIndex, getStream());
7509e15f359SSam Clegg     } else {
7519e15f359SSam Clegg       assert(Global.ImportIndex == 0);
7529e15f359SSam Clegg       write8(wasm::WASM_OPCODE_I32_CONST);
7539e15f359SSam Clegg       encodeSLEB128(Global.InitialValue, getStream()); // offset
7549e15f359SSam Clegg     }
7559e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7569e15f359SSam Clegg   }
7579e15f359SSam Clegg 
7589e15f359SSam Clegg   endSection(Section);
7599e15f359SSam Clegg }
7609e15f359SSam Clegg 
761457fb0b4SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
7629e15f359SSam Clegg   if (Exports.empty())
7639e15f359SSam Clegg     return;
7649e15f359SSam Clegg 
7659e15f359SSam Clegg   SectionBookkeeping Section;
7669e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7679e15f359SSam Clegg 
7689e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
7699e15f359SSam Clegg   for (const WasmExport &Export : Exports) {
770b7787fd0SSam Clegg     writeString(Export.FieldName);
7719e15f359SSam Clegg     encodeSLEB128(Export.Kind, getStream());
7729e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7739e15f359SSam Clegg   }
7749e15f359SSam Clegg 
7759e15f359SSam Clegg   endSection(Section);
7769e15f359SSam Clegg }
7779e15f359SSam Clegg 
778457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7799e15f359SSam Clegg   if (TableElems.empty())
7809e15f359SSam Clegg     return;
7819e15f359SSam Clegg 
7829e15f359SSam Clegg   SectionBookkeeping Section;
7839e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7849e15f359SSam Clegg 
7859e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7869e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7879e15f359SSam Clegg 
7889e15f359SSam Clegg   // init expr for starting offset
7899e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
79030e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
7919e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7929e15f359SSam Clegg 
7939e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7949e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7959e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7969e15f359SSam Clegg 
7979e15f359SSam Clegg   endSection(Section);
7989e15f359SSam Clegg }
7999e15f359SSam Clegg 
800457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
801457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
802457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8039e15f359SSam Clegg   if (Functions.empty())
8049e15f359SSam Clegg     return;
8059e15f359SSam Clegg 
8069e15f359SSam Clegg   SectionBookkeeping Section;
8079e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8089e15f359SSam Clegg 
8099e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8109e15f359SSam Clegg 
8119e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
812fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8139e15f359SSam Clegg 
8149e15f359SSam Clegg     int64_t Size = 0;
8159e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8169e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8179e15f359SSam Clegg 
8189e15f359SSam Clegg     encodeULEB128(Size, getStream());
819fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8209e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8219e15f359SSam Clegg   }
8229e15f359SSam Clegg 
8239e15f359SSam Clegg   // Apply fixups.
824acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8259e15f359SSam Clegg 
8269e15f359SSam Clegg   endSection(Section);
8279e15f359SSam Clegg }
8289e15f359SSam Clegg 
829457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
8307c395943SSam Clegg   if (Segments.empty())
8317c395943SSam Clegg     return;
8329e15f359SSam Clegg 
8339e15f359SSam Clegg   SectionBookkeeping Section;
8349e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8359e15f359SSam Clegg 
8367c395943SSam Clegg   encodeULEB128(Segments.size(), getStream()); // count
8377c395943SSam Clegg 
8387c395943SSam Clegg   for (const WasmDataSegment & Segment : Segments) {
8399e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8409e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8417c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8429e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8437c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8447c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8457c395943SSam Clegg     writeBytes(Segment.Data); // data
8467c395943SSam Clegg   }
8479e15f359SSam Clegg 
8489e15f359SSam Clegg   // Apply fixups.
8497c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8509e15f359SSam Clegg 
8519e15f359SSam Clegg   endSection(Section);
8529e15f359SSam Clegg }
8539e15f359SSam Clegg 
8549f3fe42eSSam Clegg void WasmObjectWriter::writeNameSection(ArrayRef<WasmFunction> Functions,
8559f3fe42eSSam Clegg                                         ArrayRef<WasmImport> Imports) {
8569f3fe42eSSam Clegg   uint32_t TotalFunctions = NumFunctionImports + Functions.size();
8579e15f359SSam Clegg   if (TotalFunctions == 0)
8589e15f359SSam Clegg     return;
8599e15f359SSam Clegg 
8609e15f359SSam Clegg   SectionBookkeeping Section;
8619e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
8629e15f359SSam Clegg   SectionBookkeeping SubSection;
8639e15f359SSam Clegg   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
8649e15f359SSam Clegg 
8659e15f359SSam Clegg   encodeULEB128(TotalFunctions, getStream());
8669e15f359SSam Clegg   uint32_t Index = 0;
8679e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
8689e15f359SSam Clegg     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
8699e15f359SSam Clegg       encodeULEB128(Index, getStream());
870b7787fd0SSam Clegg       writeString(Import.FieldName);
8719e15f359SSam Clegg       ++Index;
8729e15f359SSam Clegg     }
8739e15f359SSam Clegg   }
8749e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
8759e15f359SSam Clegg     encodeULEB128(Index, getStream());
876b7787fd0SSam Clegg     writeString(Func.Sym->getName());
8779e15f359SSam Clegg     ++Index;
8789e15f359SSam Clegg   }
8799e15f359SSam Clegg 
8809e15f359SSam Clegg   endSection(SubSection);
8819e15f359SSam Clegg   endSection(Section);
8829e15f359SSam Clegg }
8839e15f359SSam Clegg 
884acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() {
8859e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8869e15f359SSam Clegg   // for descriptions of the reloc sections.
8879e15f359SSam Clegg 
8889e15f359SSam Clegg   if (CodeRelocations.empty())
8899e15f359SSam Clegg     return;
8909e15f359SSam Clegg 
8919e15f359SSam Clegg   SectionBookkeeping Section;
8929e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
8939e15f359SSam Clegg 
8949e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
895acd7d2b0SSam Clegg   encodeULEB128(CodeRelocations.size(), getStream());
8969e15f359SSam Clegg 
8977c395943SSam Clegg   writeRelocations(CodeRelocations);
8989e15f359SSam Clegg 
8999e15f359SSam Clegg   endSection(Section);
9009e15f359SSam Clegg }
9019e15f359SSam Clegg 
9027c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() {
9039e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9049e15f359SSam Clegg   // for descriptions of the reloc sections.
9059e15f359SSam Clegg 
9069e15f359SSam Clegg   if (DataRelocations.empty())
9079e15f359SSam Clegg     return;
9089e15f359SSam Clegg 
9099e15f359SSam Clegg   SectionBookkeeping Section;
9109e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
9119e15f359SSam Clegg 
9129e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
9139e15f359SSam Clegg   encodeULEB128(DataRelocations.size(), getStream());
9149e15f359SSam Clegg 
9157c395943SSam Clegg   writeRelocations(DataRelocations);
9169e15f359SSam Clegg 
9179e15f359SSam Clegg   endSection(Section);
9189e15f359SSam Clegg }
9199e15f359SSam Clegg 
9209e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
921d95ed959SSam Clegg     ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
922ea7caceeSSam Clegg     ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
923ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
924ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
9259e15f359SSam Clegg   SectionBookkeeping Section;
9269e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
927b7787fd0SSam Clegg   SectionBookkeeping SubSection;
9289e15f359SSam Clegg 
92931a2c809SSam Clegg   if (SymbolFlags.size() != 0) {
930b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
93131a2c809SSam Clegg     encodeULEB128(SymbolFlags.size(), getStream());
93231a2c809SSam Clegg     for (auto Pair: SymbolFlags) {
93331a2c809SSam Clegg       writeString(Pair.first);
93431a2c809SSam Clegg       encodeULEB128(Pair.second, getStream());
935b7787fd0SSam Clegg     }
936b7787fd0SSam Clegg     endSection(SubSection);
937b7787fd0SSam Clegg   }
9389e15f359SSam Clegg 
9399e1ade93SSam Clegg   if (DataSize > 0) {
9409e1ade93SSam Clegg     startSection(SubSection, wasm::WASM_DATA_SIZE);
9419e1ade93SSam Clegg     encodeULEB128(DataSize, getStream());
9429e1ade93SSam Clegg     endSection(SubSection);
9439e1ade93SSam Clegg   }
9449e1ade93SSam Clegg 
945d95ed959SSam Clegg   if (Segments.size()) {
94663ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
947d95ed959SSam Clegg     encodeULEB128(Segments.size(), getStream());
94863ebb813SSam Clegg     for (const WasmDataSegment &Segment : Segments) {
949d95ed959SSam Clegg       writeString(Segment.Name);
95063ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
95163ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
95263ebb813SSam Clegg     }
953d95ed959SSam Clegg     endSection(SubSection);
954d95ed959SSam Clegg   }
955d95ed959SSam Clegg 
956bafe6902SSam Clegg   if (!InitFuncs.empty()) {
957bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
958bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
959bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
960bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
961bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
962bafe6902SSam Clegg     }
963bafe6902SSam Clegg     endSection(SubSection);
964bafe6902SSam Clegg   }
965bafe6902SSam Clegg 
966ea7caceeSSam Clegg   if (Comdats.size()) {
967ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
968ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
969ea7caceeSSam Clegg     for (const auto &C : Comdats) {
970ea7caceeSSam Clegg       writeString(C.first);
971ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
972ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
973ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
974ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
975ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
976ea7caceeSSam Clegg       }
977ea7caceeSSam Clegg     }
978ea7caceeSSam Clegg     endSection(SubSection);
979ea7caceeSSam Clegg   }
980ea7caceeSSam Clegg 
9819e15f359SSam Clegg   endSection(Section);
9829e15f359SSam Clegg }
9839e15f359SSam Clegg 
9845e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
9855e3d33a7SSam Clegg   assert(Symbol.isFunction());
9865e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
9875e3d33a7SSam Clegg   return TypeIndices[&Symbol];
9885e3d33a7SSam Clegg }
9895e3d33a7SSam Clegg 
9905e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
9915e3d33a7SSam Clegg   assert(Symbol.isFunction());
9925e3d33a7SSam Clegg 
9935e3d33a7SSam Clegg   WasmFunctionType F;
994aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
9955e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
9965e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
9975e3d33a7SSam Clegg 
9985e3d33a7SSam Clegg   auto Pair =
9995e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10005e3d33a7SSam Clegg   if (Pair.second)
10015e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10025e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10035e3d33a7SSam Clegg 
10045e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
10055e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10065e3d33a7SSam Clegg   return Pair.first->second;
10075e3d33a7SSam Clegg }
10085e3d33a7SSam Clegg 
100918eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
101018eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1011b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
101282607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1013b879539aSDerek Schuff   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
1014d934cb88SDan Gohman 
1015d934cb88SDan Gohman   // Collect information from the available symbols.
1016d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1017d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
1018d934cb88SDan Gohman   SmallVector<WasmImport, 4> Imports;
1019d934cb88SDan Gohman   SmallVector<WasmExport, 4> Exports;
102031a2c809SSam Clegg   SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
1021bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1022ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
10237c395943SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
10247c395943SSam Clegg   uint32_t DataSize = 0;
1025d934cb88SDan Gohman 
102682607f56SDan Gohman   // In the special .global_variables section, we've encoded global
102782607f56SDan Gohman   // variables used by the function. Translate them into the Globals
102882607f56SDan Gohman   // list.
102912fd3da9SSam Clegg   MCSectionWasm *GlobalVars =
103012fd3da9SSam Clegg       Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
103182607f56SDan Gohman   if (!GlobalVars->getFragmentList().empty()) {
103282607f56SDan Gohman     if (GlobalVars->getFragmentList().size() != 1)
103382607f56SDan Gohman       report_fatal_error("only one .global_variables fragment supported");
103482607f56SDan Gohman     const MCFragment &Frag = *GlobalVars->begin();
103582607f56SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
103682607f56SDan Gohman       report_fatal_error("only data supported in .global_variables");
1037fe6414b0SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
103882607f56SDan Gohman     if (!DataFrag.getFixups().empty())
103982607f56SDan Gohman       report_fatal_error("fixups not supported in .global_variables");
104082607f56SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1041970d02c4SDan Gohman     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1042970d02c4SDan Gohman                      *end = (const uint8_t *)Contents.data() + Contents.size();
1043970d02c4SDan Gohman          p != end; ) {
104482607f56SDan Gohman       WasmGlobal G;
1045970d02c4SDan Gohman       if (end - p < 3)
1046970d02c4SDan Gohman         report_fatal_error("truncated global variable encoding");
1047970d02c4SDan Gohman       G.Type = wasm::ValType(int8_t(*p++));
1048970d02c4SDan Gohman       G.IsMutable = bool(*p++);
1049970d02c4SDan Gohman       G.HasImport = bool(*p++);
1050970d02c4SDan Gohman       if (G.HasImport) {
105182607f56SDan Gohman         G.InitialValue = 0;
1052970d02c4SDan Gohman 
1053970d02c4SDan Gohman         WasmImport Import;
1054970d02c4SDan Gohman         Import.ModuleName = (const char *)p;
1055970d02c4SDan Gohman         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1056970d02c4SDan Gohman         if (!nul)
1057970d02c4SDan Gohman           report_fatal_error("global module name must be nul-terminated");
1058970d02c4SDan Gohman         p = nul + 1;
1059970d02c4SDan Gohman         nul = (const uint8_t *)memchr(p, '\0', end - p);
1060970d02c4SDan Gohman         if (!nul)
1061970d02c4SDan Gohman           report_fatal_error("global base name must be nul-terminated");
1062970d02c4SDan Gohman         Import.FieldName = (const char *)p;
1063970d02c4SDan Gohman         p = nul + 1;
1064970d02c4SDan Gohman 
1065970d02c4SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1066970d02c4SDan Gohman         Import.Type = int32_t(G.Type);
1067970d02c4SDan Gohman 
1068970d02c4SDan Gohman         G.ImportIndex = NumGlobalImports;
1069970d02c4SDan Gohman         ++NumGlobalImports;
1070970d02c4SDan Gohman 
1071970d02c4SDan Gohman         Imports.push_back(Import);
1072970d02c4SDan Gohman       } else {
1073970d02c4SDan Gohman         unsigned n;
1074970d02c4SDan Gohman         G.InitialValue = decodeSLEB128(p, &n);
1075970d02c4SDan Gohman         G.ImportIndex = 0;
1076c8da0c0bSSimon Pilgrim         if ((ptrdiff_t)n > end - p)
1077970d02c4SDan Gohman           report_fatal_error("global initial value must be valid SLEB128");
1078970d02c4SDan Gohman         p += n;
1079970d02c4SDan Gohman       }
108082607f56SDan Gohman       Globals.push_back(G);
108182607f56SDan Gohman     }
108282607f56SDan Gohman   }
108382607f56SDan Gohman 
1084f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1085f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1086f950b24aSSam Clegg   // it if there are no loads or stores.
1087f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1088f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1089f950b24aSSam Clegg   WasmImport MemImport;
1090f950b24aSSam Clegg   MemImport.ModuleName = MemorySym->getModuleName();
1091f950b24aSSam Clegg   MemImport.FieldName = MemorySym->getName();
1092f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1093f950b24aSSam Clegg   Imports.push_back(MemImport);
1094f950b24aSSam Clegg 
1095f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1096f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1097f950b24aSSam Clegg   // it if there are no indirect calls.
1098f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1099f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1100f950b24aSSam Clegg   WasmImport TableImport;
1101f950b24aSSam Clegg   TableImport.ModuleName = TableSym->getModuleName();
1102f950b24aSSam Clegg   TableImport.FieldName = TableSym->getName();
1103f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1104f950b24aSSam Clegg   TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1105f950b24aSSam Clegg   Imports.push_back(TableImport);
1106f950b24aSSam Clegg 
110732ce5ca0SDan Gohman   // Populate FunctionTypeIndices and Imports.
110832ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
110932ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
111032ce5ca0SDan Gohman 
111132ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11129f3fe42eSSam Clegg     // (because wasm always needs a type signature).
111332ce5ca0SDan Gohman     if (WS.isFunction())
111432ce5ca0SDan Gohman       registerFunctionType(WS);
111532ce5ca0SDan Gohman 
111632ce5ca0SDan Gohman     if (WS.isTemporary())
111732ce5ca0SDan Gohman       continue;
111832ce5ca0SDan Gohman 
111932ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
1120cd65f698SSam Clegg     if ((!WS.isDefined() && !WS.isComdat()) ||
1121d423f0d2SSam Clegg         WS.isVariable()) {
112232ce5ca0SDan Gohman       WasmImport Import;
112332ce5ca0SDan Gohman       Import.ModuleName = WS.getModuleName();
112432ce5ca0SDan Gohman       Import.FieldName = WS.getName();
112532ce5ca0SDan Gohman 
112632ce5ca0SDan Gohman       if (WS.isFunction()) {
112732ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
112832ce5ca0SDan Gohman         Import.Type = getFunctionType(WS);
11299f3fe42eSSam Clegg         SymbolIndices[&WS] = NumFunctionImports;
11309f3fe42eSSam Clegg         ++NumFunctionImports;
113132ce5ca0SDan Gohman       } else {
113232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
113332ce5ca0SDan Gohman         Import.Type = int32_t(PtrType);
113432ce5ca0SDan Gohman         Import.IsMutable = false;
113532ce5ca0SDan Gohman         SymbolIndices[&WS] = NumGlobalImports;
113632ce5ca0SDan Gohman 
113783b16226SDan Gohman         // If this global is the stack pointer, make it mutable.
1138ad19047dSDan Gohman         if (WS.getName() == "__stack_pointer")
113932ce5ca0SDan Gohman           Import.IsMutable = true;
114032ce5ca0SDan Gohman 
114132ce5ca0SDan Gohman         ++NumGlobalImports;
114232ce5ca0SDan Gohman       }
114332ce5ca0SDan Gohman 
114432ce5ca0SDan Gohman       Imports.push_back(Import);
114532ce5ca0SDan Gohman     }
114632ce5ca0SDan Gohman   }
114732ce5ca0SDan Gohman 
1148759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1149759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
115012fd3da9SSam Clegg     if (!Section.isWasmData())
1151759631c7SSam Clegg       continue;
1152759631c7SSam Clegg 
1153bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1154bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1155bafe6902SSam Clegg       continue;
1156bafe6902SSam Clegg 
1157759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1158759631c7SSam Clegg     DataSegments.emplace_back();
1159759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1160d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1161759631c7SSam Clegg     Segment.Offset = DataSize;
1162759631c7SSam Clegg     Segment.Section = &Section;
116363ebb813SSam Clegg     addData(Segment.Data, Section);
116463ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
116563ebb813SSam Clegg     Segment.Flags = 0;
1166759631c7SSam Clegg     DataSize += Segment.Data.size();
1167759631c7SSam Clegg     Section.setMemoryOffset(Segment.Offset);
1168ea7caceeSSam Clegg 
1169ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1170ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1171ea7caceeSSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA,
1172ea7caceeSSam Clegg                           static_cast<uint32_t>(DataSegments.size()) - 1});
1173ea7caceeSSam Clegg     }
1174759631c7SSam Clegg   }
1175759631c7SSam Clegg 
1176b7787fd0SSam Clegg   // Handle regular defined and undefined symbols.
1177d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1178d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1179d934cb88SDan Gohman     // or used in relocations.
1180d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1181d934cb88SDan Gohman       continue;
1182b7787fd0SSam Clegg 
1183d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1184b7787fd0SSam Clegg     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1185b7787fd0SSam Clegg                  << " isDefined=" << S.isDefined() << " isExternal="
1186b7787fd0SSam Clegg                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1187b7787fd0SSam Clegg                  << " isFunction=" << WS.isFunction()
1188b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1189a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1190b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1191b7787fd0SSam Clegg 
1192a2b35dacSSam Clegg     if (WS.isWeak() || WS.isHidden()) {
1193a2b35dacSSam Clegg       uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1194a2b35dacSSam Clegg           (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1195a2b35dacSSam Clegg       SymbolFlags.emplace_back(WS.getName(), Flags);
1196a2b35dacSSam Clegg     }
1197b7787fd0SSam Clegg 
11985e3d33a7SSam Clegg     if (WS.isVariable())
11995e3d33a7SSam Clegg       continue;
12005e3d33a7SSam Clegg 
1201d934cb88SDan Gohman     unsigned Index;
1202b7787fd0SSam Clegg 
1203d934cb88SDan Gohman     if (WS.isFunction()) {
1204cd65f698SSam Clegg       if (WS.isDefined()) {
1205b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1206b7787fd0SSam Clegg           report_fatal_error(
1207b7787fd0SSam Clegg               "function sections must contain one function each");
1208b7787fd0SSam Clegg 
1209b7787fd0SSam Clegg         if (WS.getSize() == 0)
1210b7787fd0SSam Clegg           report_fatal_error(
1211b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1212b7787fd0SSam Clegg 
1213d934cb88SDan Gohman         // A definition. Take the next available index.
12149f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1215d934cb88SDan Gohman 
1216d934cb88SDan Gohman         // Prepare the function.
1217d934cb88SDan Gohman         WasmFunction Func;
12185e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1219d934cb88SDan Gohman         Func.Sym = &WS;
1220d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1221d934cb88SDan Gohman         Functions.push_back(Func);
1222d934cb88SDan Gohman       } else {
1223d934cb88SDan Gohman         // An import; the index was assigned above.
1224d934cb88SDan Gohman         Index = SymbolIndices.find(&WS)->second;
1225d934cb88SDan Gohman       }
1226d934cb88SDan Gohman 
12275e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1228d934cb88SDan Gohman    } else {
1229c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1230c38e947eSSam Clegg         continue;
1231c38e947eSSam Clegg 
1232cd65f698SSam Clegg       if (!WS.isDefined())
1233fe6414b0SSam Clegg         continue;
1234fe6414b0SSam Clegg 
1235d934cb88SDan Gohman       if (!WS.getSize())
1236c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1237c38e947eSSam Clegg                            WS.getName());
1238d934cb88SDan Gohman 
1239d934cb88SDan Gohman       int64_t Size = 0;
1240d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1241d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1242d934cb88SDan Gohman 
12437c395943SSam Clegg       // For each global, prepare a corresponding wasm global holding its
12447c395943SSam Clegg       // address.  For externals these will also be named exports.
12457c395943SSam Clegg       Index = NumGlobalImports + Globals.size();
1246759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1247ea7caceeSSam Clegg       assert(DataSection.isWasmData());
12487c395943SSam Clegg 
12497c395943SSam Clegg       WasmGlobal Global;
12507c395943SSam Clegg       Global.Type = PtrType;
12517c395943SSam Clegg       Global.IsMutable = false;
12527c395943SSam Clegg       Global.HasImport = false;
1253759631c7SSam Clegg       Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
12547c395943SSam Clegg       Global.ImportIndex = 0;
12557c395943SSam Clegg       SymbolIndices[&WS] = Index;
12567c395943SSam Clegg       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
12577c395943SSam Clegg       Globals.push_back(Global);
1258d934cb88SDan Gohman     }
1259d934cb88SDan Gohman 
1260d934cb88SDan Gohman     // If the symbol is visible outside this translation unit, export it.
1261cd65f698SSam Clegg     if (WS.isDefined()) {
1262d934cb88SDan Gohman       WasmExport Export;
1263d934cb88SDan Gohman       Export.FieldName = WS.getName();
1264d934cb88SDan Gohman       Export.Index = Index;
1265d934cb88SDan Gohman       if (WS.isFunction())
1266d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1267d934cb88SDan Gohman       else
1268d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
12695e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1270d934cb88SDan Gohman       Exports.push_back(Export);
1271ea7caceeSSam Clegg 
127231a2c809SSam Clegg       if (!WS.isExternal())
127331a2c809SSam Clegg         SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1274ea7caceeSSam Clegg 
1275ea7caceeSSam Clegg       if (WS.isFunction()) {
1276cd65f698SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1277ea7caceeSSam Clegg         if (const MCSymbolWasm *C = Section.getGroup())
1278ea7caceeSSam Clegg           Comdats[C->getName()].emplace_back(
1279ea7caceeSSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1280ea7caceeSSam Clegg       }
1281d934cb88SDan Gohman     }
1282d934cb88SDan Gohman   }
1283d934cb88SDan Gohman 
12845e3d33a7SSam Clegg   // Handle weak aliases. We need to process these in a separate pass because
12855e3d33a7SSam Clegg   // we need to have processed the target of the alias before the alias itself
12865e3d33a7SSam Clegg   // and the symbols are not necessarily ordered in this way.
1287b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1288b7787fd0SSam Clegg     if (!S.isVariable())
1289b7787fd0SSam Clegg       continue;
129031a2c809SSam Clegg 
1291cd65f698SSam Clegg     assert(S.isDefined());
1292b7787fd0SSam Clegg 
12935e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1294aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1295aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
12965e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
12975e3d33a7SSam Clegg     assert(SymbolIndices.count(ResolvedSym) > 0);
1298b7787fd0SSam Clegg     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
12995e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> index:" << Index << "\n");
1300b7787fd0SSam Clegg 
1301b7787fd0SSam Clegg     WasmExport Export;
1302b7787fd0SSam Clegg     Export.FieldName = WS.getName();
1303b7787fd0SSam Clegg     Export.Index = Index;
1304b7787fd0SSam Clegg     if (WS.isFunction())
1305b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1306b7787fd0SSam Clegg     else
1307b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
13085e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1309b7787fd0SSam Clegg     Exports.push_back(Export);
131031a2c809SSam Clegg 
131131a2c809SSam Clegg     if (!WS.isExternal())
131231a2c809SSam Clegg       SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1313b7787fd0SSam Clegg   }
1314b7787fd0SSam Clegg 
13156006e091SSam Clegg   {
13166006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
13176006e091SSam Clegg       // Functions referenced by a relocation need to prepared to be called
13186006e091SSam Clegg       // indirectly.
13196006e091SSam Clegg       const MCSymbolWasm& WS = *Rel.Symbol;
13206006e091SSam Clegg       if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
13216006e091SSam Clegg         switch (Rel.Type) {
13226006e091SSam Clegg         case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
13236006e091SSam Clegg         case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
13246006e091SSam Clegg         case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
13256006e091SSam Clegg         case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
13266006e091SSam Clegg           uint32_t Index = SymbolIndices.find(&WS)->second;
132730e1bbc1SSam Clegg           IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset;
13286006e091SSam Clegg           DEBUG(dbgs() << "  -> adding to table: " << TableElems.size() << "\n");
13296006e091SSam Clegg           TableElems.push_back(Index);
13306006e091SSam Clegg           registerFunctionType(WS);
13316006e091SSam Clegg           break;
13326006e091SSam Clegg         }
13336006e091SSam Clegg         default:
13346006e091SSam Clegg           break;
13356006e091SSam Clegg         }
13366006e091SSam Clegg       }
13376006e091SSam Clegg     };
1338970d02c4SDan Gohman 
13396006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
13406006e091SSam Clegg       HandleReloc(RelEntry);
13416006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
13426006e091SSam Clegg       HandleReloc(RelEntry);
1343d934cb88SDan Gohman   }
1344d934cb88SDan Gohman 
1345bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1346bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1347bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1348bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1349bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1350bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1351bafe6902SSam Clegg       continue;
1352bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1353bafe6902SSam Clegg       continue;
1354bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1355bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1356bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1357bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1358bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1359bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1360bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1361bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1362bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1363bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1364bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1365bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1366bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1367bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1368bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1369bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1370bafe6902SSam Clegg     }
1371bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1372bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1373bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1374bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1375bafe6902SSam Clegg          p != end; ++p) {
1376bafe6902SSam Clegg       if (*p != 0)
1377bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1378bafe6902SSam Clegg     }
1379bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1380bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1381bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1382bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1383bafe6902SSam Clegg       if (!Sym)
1384bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1385bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1386bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1387bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1388bafe6902SSam Clegg       if (I == SymbolIndices.end())
1389bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1390bafe6902SSam Clegg       uint32_t Index = I->second;
1391bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1392bafe6902SSam Clegg     }
1393bafe6902SSam Clegg   }
1394bafe6902SSam Clegg 
139518eafb6cSDan Gohman   // Write out the Wasm header.
139618eafb6cSDan Gohman   writeHeader(Asm);
139718eafb6cSDan Gohman 
13989e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1399f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14009e15f359SSam Clegg   writeFunctionSection(Functions);
1401f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1402f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14037c395943SSam Clegg   writeGlobalSection();
14049e15f359SSam Clegg   writeExportSection(Exports);
14059e15f359SSam Clegg   writeElemSection(TableElems);
1406acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14077c395943SSam Clegg   writeDataSection(DataSegments);
14089f3fe42eSSam Clegg   writeNameSection(Functions, Imports);
1409acd7d2b0SSam Clegg   writeCodeRelocSection();
14107c395943SSam Clegg   writeDataRelocSection();
1411bafe6902SSam Clegg   writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1412ea7caceeSSam Clegg                               InitFuncs, Comdats);
1413970d02c4SDan Gohman 
1414d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1415d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
141618eafb6cSDan Gohman }
141718eafb6cSDan Gohman 
141860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
14191301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
142018eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
14210917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
142218eafb6cSDan Gohman }
1423