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"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
32d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
385e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3918eafb6cSDan Gohman 
40d1f0910aSSam Clegg #if !defined(NDEBUG)
41a165f2d6SSam Clegg static std::string toString(wasm::WasmSymbolType type) {
42a165f2d6SSam Clegg   switch (type) {
43a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
44a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_FUNCTION";
45a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
46a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_GLOBAL";
47a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_DATA:
48a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_DATA";
49a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_SECTION:
50a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_SECTION";
51a165f2d6SSam Clegg   }
52ba4d85eeSFlorian Hahn   llvm_unreachable("unknown symbol type");
53a165f2d6SSam Clegg }
54d1f0910aSSam Clegg #endif
55a165f2d6SSam Clegg 
56a165f2d6SSam Clegg static std::string relocTypetoString(uint32_t type) {
57a165f2d6SSam Clegg   switch (type) {
58a165f2d6SSam Clegg #define WASM_RELOC(NAME, VALUE) case VALUE: return #NAME;
59a165f2d6SSam Clegg #include "llvm/BinaryFormat/WasmRelocs.def"
60a165f2d6SSam Clegg #undef WASM_RELOC
61a165f2d6SSam Clegg   default:
62a165f2d6SSam Clegg     llvm_unreachable("uknown reloc type");
63a165f2d6SSam Clegg   }
64a165f2d6SSam Clegg }
65a165f2d6SSam Clegg 
6618eafb6cSDan Gohman namespace {
679e15f359SSam Clegg 
6830e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
6930e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
7030e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
7130e1bbc1SSam Clegg 
72d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
73d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
74d934cb88SDan Gohman // locations within the section.
75d934cb88SDan Gohman struct SectionBookkeeping {
76d934cb88SDan Gohman   // Where the size of the section is written.
77d934cb88SDan Gohman   uint64_t SizeOffset;
786a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
796a31a0d6SSam Clegg   uint64_t PayloadOffset;
806a31a0d6SSam Clegg   // Where the contents of the section starts.
81d934cb88SDan Gohman   uint64_t ContentsOffset;
826f08c84aSSam Clegg   uint32_t Index;
83d934cb88SDan Gohman };
84d934cb88SDan Gohman 
859e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
869e15f359SSam Clegg // DenseMap key.
879e15f359SSam Clegg struct WasmFunctionType {
889e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
899e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
909e15f359SSam Clegg 
919e15f359SSam Clegg   // The return types of the function.
929e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
939e15f359SSam Clegg 
949e15f359SSam Clegg   // The parameter types of the function.
959e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
969e15f359SSam Clegg 
979e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
989e15f359SSam Clegg 
999e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
1009e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
1019e15f359SSam Clegg            Params == Other.Params;
1029e15f359SSam Clegg   }
1039e15f359SSam Clegg };
1049e15f359SSam Clegg 
1059e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
1069e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
1079e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
1089e15f359SSam Clegg     WasmFunctionType FuncTy;
1099e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
1109e15f359SSam Clegg     return FuncTy;
1119e15f359SSam Clegg   }
1129e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
1139e15f359SSam Clegg     WasmFunctionType FuncTy;
1149e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
1159e15f359SSam Clegg     return FuncTy;
1169e15f359SSam Clegg   }
1179e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
1189e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
1199e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
1209e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
1219e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
1229e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
1239e15f359SSam Clegg     return Value;
1249e15f359SSam Clegg   }
1259e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1269e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1279e15f359SSam Clegg     return LHS == RHS;
1289e15f359SSam Clegg   }
1299e15f359SSam Clegg };
1309e15f359SSam Clegg 
1317c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1327c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1337c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1347c395943SSam Clegg // wasm data segment.
1357c395943SSam Clegg struct WasmDataSegment {
1367c395943SSam Clegg   MCSectionWasm *Section;
137d95ed959SSam Clegg   StringRef Name;
1387c395943SSam Clegg   uint32_t Offset;
13963ebb813SSam Clegg   uint32_t Alignment;
14063ebb813SSam Clegg   uint32_t Flags;
1417c395943SSam Clegg   SmallVector<char, 4> Data;
1427c395943SSam Clegg };
1437c395943SSam Clegg 
1449e15f359SSam Clegg // A wasm function to be written into the function section.
1459e15f359SSam Clegg struct WasmFunction {
1469e15f359SSam Clegg   int32_t Type;
1479e15f359SSam Clegg   const MCSymbolWasm *Sym;
1489e15f359SSam Clegg };
1499e15f359SSam Clegg 
1509e15f359SSam Clegg // A wasm global to be written into the global section.
1519e15f359SSam Clegg struct WasmGlobal {
1526e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1539e15f359SSam Clegg   uint64_t InitialValue;
1549e15f359SSam Clegg };
1559e15f359SSam Clegg 
156ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
157ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
158ea7caceeSSam Clegg // WasmComdatEntry.
159ea7caceeSSam Clegg struct WasmComdatEntry {
160ea7caceeSSam Clegg   unsigned Kind;
161ea7caceeSSam Clegg   uint32_t Index;
162ea7caceeSSam Clegg };
163ea7caceeSSam Clegg 
1646dc65e91SSam Clegg // Information about a single relocation.
1656dc65e91SSam Clegg struct WasmRelocationEntry {
1666dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1676dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1686dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1696dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
170fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1716dc65e91SSam Clegg 
1726dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1736dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
174fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1756dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1766dc65e91SSam Clegg         FixupSection(FixupSection) {}
1776dc65e91SSam Clegg 
178acd7d2b0SSam Clegg   bool hasAddend() const {
179acd7d2b0SSam Clegg     switch (Type) {
18013a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
18113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
18213a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1836a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1846a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
185acd7d2b0SSam Clegg       return true;
186acd7d2b0SSam Clegg     default:
187acd7d2b0SSam Clegg       return false;
188acd7d2b0SSam Clegg     }
189acd7d2b0SSam Clegg   }
190acd7d2b0SSam Clegg 
1916dc65e91SSam Clegg   void print(raw_ostream &Out) const {
192a165f2d6SSam Clegg     Out << relocTypetoString(Type)
193a165f2d6SSam Clegg         << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
194759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1956dc65e91SSam Clegg   }
196b7787fd0SSam Clegg 
197615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
198b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
199b7787fd0SSam Clegg #endif
2006dc65e91SSam Clegg };
2016dc65e91SSam Clegg 
202cfd44a2eSSam Clegg struct WasmCustomSection {
2036a31a0d6SSam Clegg   const uint32_t INVALID_INDEX = -1;
204cfd44a2eSSam Clegg 
2056a31a0d6SSam Clegg   StringRef Name;
2066a31a0d6SSam Clegg   MCSectionWasm *Section;
2076a31a0d6SSam Clegg 
2086a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
2096a31a0d6SSam Clegg   uint32_t OutputIndex;
2106a31a0d6SSam Clegg 
2116a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
2126a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
2136a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
214cfd44a2eSSam Clegg };
215cfd44a2eSSam Clegg 
2161fb8daa6SSam Clegg #if !defined(NDEBUG)
2177f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
218b7787fd0SSam Clegg   Rel.print(OS);
219b7787fd0SSam Clegg   return OS;
220b7787fd0SSam Clegg }
2211fb8daa6SSam Clegg #endif
222b7787fd0SSam Clegg 
22318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
22418eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22518eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22618eafb6cSDan Gohman 
227d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
228d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2296f08c84aSSam Clegg   uint32_t CodeSectionIndex;
230d934cb88SDan Gohman 
231d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
232d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2336f08c84aSSam Clegg   uint32_t DataSectionIndex;
234d934cb88SDan Gohman 
235d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
236acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
237acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
238d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
239d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
240f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2416c899ba6SSam Clegg   // Maps function/global symbols to the (shared) Symbol index space.
242acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
243a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2446c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2456c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2466c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2476a31a0d6SSam Clegg 
2486a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2496a31a0d6SSam Clegg   // section.
2506a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2516a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2526a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2536a31a0d6SSam Clegg       CustomSectionsRelocations;
254acd7d2b0SSam Clegg 
255acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
256acd7d2b0SSam Clegg       FunctionTypeIndices;
2575e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2587c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2596c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2609f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2617c395943SSam Clegg   unsigned NumGlobalImports = 0;
2627e1c3345SChandler Carruth   uint32_t SectionCount = 0;
263d934cb88SDan Gohman 
26418eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26518eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
266ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
267ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
26818eafb6cSDan Gohman   }
26918eafb6cSDan Gohman 
2702322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2712322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
272d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
273d934cb88SDan Gohman 
27418eafb6cSDan Gohman public:
2751301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2761301a878SLang Hames                    raw_pwrite_stream &OS)
2771301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2781301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
27918eafb6cSDan Gohman 
28018eafb6cSDan Gohman   ~WasmObjectWriter() override;
28118eafb6cSDan Gohman 
2820917c9e4SDan Gohman private:
283acd7d2b0SSam Clegg   void reset() override {
284acd7d2b0SSam Clegg     CodeRelocations.clear();
285acd7d2b0SSam Clegg     DataRelocations.clear();
286acd7d2b0SSam Clegg     TypeIndices.clear();
287acd7d2b0SSam Clegg     SymbolIndices.clear();
2886c899ba6SSam Clegg     WasmIndices.clear();
289f9edbe95SSam Clegg     TableIndices.clear();
2906c899ba6SSam Clegg     DataLocations.clear();
2916a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
292acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2935e3d33a7SSam Clegg     FunctionTypes.clear();
2947c395943SSam Clegg     Globals.clear();
2956c899ba6SSam Clegg     DataSegments.clear();
296acd7d2b0SSam Clegg     MCObjectWriter::reset();
2979f3fe42eSSam Clegg     NumFunctionImports = 0;
2987c395943SSam Clegg     NumGlobalImports = 0;
299acd7d2b0SSam Clegg   }
300acd7d2b0SSam Clegg 
30118eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30218eafb6cSDan Gohman 
30318eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30418eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
305ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30618eafb6cSDan Gohman 
30718eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30818eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30918eafb6cSDan Gohman 
31018eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3119e15f359SSam Clegg 
312b7787fd0SSam Clegg   void writeString(const StringRef Str) {
313b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
314b7787fd0SSam Clegg     writeBytes(Str);
315b7787fd0SSam Clegg   }
316b7787fd0SSam Clegg 
3179e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
31803e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
3199e15f359SSam Clegg   }
3209e15f359SSam Clegg 
321457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
3228defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
323f950b24aSSam Clegg                           uint32_t NumElements);
324457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3257c395943SSam Clegg   void writeGlobalSection();
3268defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
327457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3289e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
329457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3306c899ba6SSam Clegg   void writeDataSection();
3316f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3326f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
33331a2c809SSam Clegg   void writeLinkingMetaDataSection(
33486b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
335ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
336ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3376a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3386a31a0d6SSam Clegg   void writeCustomRelocSections();
3396a31a0d6SSam Clegg   void
3406a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3416a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
342acd7d2b0SSam Clegg 
3437c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
344acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
345acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
346acd7d2b0SSam Clegg 
347acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3485e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3495e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
35018eafb6cSDan Gohman };
3519e15f359SSam Clegg 
35218eafb6cSDan Gohman } // end anonymous namespace
35318eafb6cSDan Gohman 
35418eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
35518eafb6cSDan Gohman 
356d934cb88SDan Gohman // Write out a section header and a patchable section size field.
357d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3582322a937SSam Clegg                                     unsigned SectionId) {
3592322a937SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << "\n");
36003e101f1SSam Clegg   write8(SectionId);
361d934cb88SDan Gohman 
362d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
363d934cb88SDan Gohman 
364d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
365d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
366d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
367d934cb88SDan Gohman 
368d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
369d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
3706a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3716f08c84aSSam Clegg   Section.Index = SectionCount++;
372d934cb88SDan Gohman }
3732322a937SSam Clegg 
3742322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3752322a937SSam Clegg                                           StringRef Name) {
3762322a937SSam Clegg   DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3772322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3786a31a0d6SSam Clegg 
3796a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3806a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3816a31a0d6SSam Clegg 
3822322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3832322a937SSam Clegg   writeString(Name);
3846a31a0d6SSam Clegg 
3856a31a0d6SSam Clegg   // The position where the custom section starts.
3866a31a0d6SSam Clegg   Section.ContentsOffset = getStream().tell();
387d934cb88SDan Gohman }
388d934cb88SDan Gohman 
389d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
390d934cb88SDan Gohman // section size field at the start of the section.
391d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3926a31a0d6SSam Clegg   uint64_t Size = getStream().tell() - Section.PayloadOffset;
393d934cb88SDan Gohman   if (uint32_t(Size) != Size)
394d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
395d934cb88SDan Gohman 
396b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
397d934cb88SDan Gohman 
398d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
399d934cb88SDan Gohman   // the section id byte.
400d934cb88SDan Gohman   uint8_t Buffer[16];
40166a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
402d934cb88SDan Gohman   assert(SizeLen == 5);
403d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
404d934cb88SDan Gohman }
405d934cb88SDan Gohman 
40618eafb6cSDan Gohman // Emit the Wasm header.
40718eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4087ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
4097ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
41018eafb6cSDan Gohman }
41118eafb6cSDan Gohman 
41218eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41318eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
41418eafb6cSDan Gohman }
41518eafb6cSDan Gohman 
41618eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
41718eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
41818eafb6cSDan Gohman                                         const MCFragment *Fragment,
41918eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
420ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
421ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
422ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
423ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
424fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
425d934cb88SDan Gohman   uint64_t C = Target.getConstant();
426d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
427d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
428d934cb88SDan Gohman 
429bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
430bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
431bafe6902SSam Clegg     return;
432bafe6902SSam Clegg 
433d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
434d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
435d934cb88SDan Gohman            "Should not have constructed this");
436d934cb88SDan Gohman 
437d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
438d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
439d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
440d934cb88SDan Gohman 
441d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
442d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
443d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
444d934cb88SDan Gohman     if (IsPCRel) {
445d934cb88SDan Gohman       Ctx.reportError(
446d934cb88SDan Gohman           Fixup.getLoc(),
447d934cb88SDan Gohman           "No relocation available to represent this relative expression");
448d934cb88SDan Gohman       return;
449d934cb88SDan Gohman     }
450d934cb88SDan Gohman 
451d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
452d934cb88SDan Gohman 
453d934cb88SDan Gohman     if (SymB.isUndefined()) {
454d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
455d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
456d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
457d934cb88SDan Gohman       return;
458d934cb88SDan Gohman     }
459d934cb88SDan Gohman 
460d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
461d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
462d934cb88SDan Gohman     if (&SecB != &FixupSection) {
463d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
464d934cb88SDan Gohman                       "Cannot represent a difference across sections");
465d934cb88SDan Gohman       return;
466d934cb88SDan Gohman     }
467d934cb88SDan Gohman 
468d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
469d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
470d934cb88SDan Gohman     IsPCRel = true;
471d934cb88SDan Gohman     C -= K;
472d934cb88SDan Gohman   }
473d934cb88SDan Gohman 
474d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
475d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
476d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
477d934cb88SDan Gohman 
478d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
479d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4806ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4816ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4826ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
483d934cb88SDan Gohman   }
484d934cb88SDan Gohman 
485d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
486d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
487d934cb88SDan Gohman   // be negative and don't wrap.
488d934cb88SDan Gohman   FixedValue = 0;
489d934cb88SDan Gohman 
490*4d57fbd0SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
491ae03c1e7SSam Clegg   assert(!IsPCRel);
4929d24fb7fSSam Clegg   assert(SymA);
4939d24fb7fSSam Clegg 
494*4d57fbd0SSam Clegg   // Absolute offset within a section or a function.
495*4d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
496*4d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
497*4d57fbd0SSam Clegg   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
498*4d57fbd0SSam Clegg       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
499*4d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
500*4d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
501*4d57fbd0SSam Clegg                          "only supported in metadata sections");
502*4d57fbd0SSam Clegg 
503*4d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
504*4d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
505*4d57fbd0SSam Clegg     if (SecA.getKind().isText())
506*4d57fbd0SSam Clegg       SectionSymbol = SecA.begin()->getAtom();
507*4d57fbd0SSam Clegg     else
508*4d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
509*4d57fbd0SSam Clegg     if (!SectionSymbol)
510*4d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
511*4d57fbd0SSam Clegg 
512*4d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
513*4d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
514*4d57fbd0SSam Clegg   }
515*4d57fbd0SSam Clegg 
516*4d57fbd0SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
517*4d57fbd0SSam Clegg   // against a named symbol.
518*4d57fbd0SSam Clegg   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
519*4d57fbd0SSam Clegg     if (SymA->getName().empty())
520*4d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
521*4d57fbd0SSam Clegg                          "supported by wasm");
522*4d57fbd0SSam Clegg 
523*4d57fbd0SSam Clegg     SymA->setUsedInReloc();
524*4d57fbd0SSam Clegg   }
525ae03c1e7SSam Clegg 
526d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
527b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
528d934cb88SDan Gohman 
5296a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
530d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5316a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
53212fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5336a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5346a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5356a31a0d6SSam Clegg   } else {
53612fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
537d934cb88SDan Gohman   }
5386a31a0d6SSam Clegg }
539d934cb88SDan Gohman 
540d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
541d934cb88SDan Gohman // to allow patching.
542d934cb88SDan Gohman static void
543d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
544d934cb88SDan Gohman   uint8_t Buffer[5];
54566a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
546d934cb88SDan Gohman   assert(SizeLen == 5);
547d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
548d934cb88SDan Gohman }
549d934cb88SDan Gohman 
550d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
551d934cb88SDan Gohman // to allow patching.
552d934cb88SDan Gohman static void
553d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
554d934cb88SDan Gohman   uint8_t Buffer[5];
55566a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
556d934cb88SDan Gohman   assert(SizeLen == 5);
557d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
558d934cb88SDan Gohman }
559d934cb88SDan Gohman 
560d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
561d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
562d934cb88SDan Gohman   uint8_t Buffer[4];
563d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
564d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
565d934cb88SDan Gohman }
566d934cb88SDan Gohman 
567aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
568aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
569aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
570aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
571aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
572aff1c4dfSSam Clegg   }
573aff1c4dfSSam Clegg   return &Symbol;
574aff1c4dfSSam Clegg }
575aff1c4dfSSam Clegg 
576d934cb88SDan Gohman // Compute a value to write into the code at the location covered
57760ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57860ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57960ec3034SSam Clegg // useable.
5807c395943SSam Clegg uint32_t
5817c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
58260ec3034SSam Clegg   switch (RelEntry.Type) {
58360ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
584f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
585f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
586f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
587f9edbe95SSam Clegg     assert(Sym->isFunction());
588f9edbe95SSam Clegg     return TableIndices[Sym];
589f9edbe95SSam Clegg   }
59060ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5916c899ba6SSam Clegg     // Provisional value is same as the index
59260ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5936c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5946c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5956c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5966c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5976c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5986c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5996c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
600*4d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
601*4d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
6026a31a0d6SSam Clegg     const auto &Section =
6036a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6046a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6056a31a0d6SSam Clegg   }
60660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
60760ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
60860ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
609f9edbe95SSam Clegg     // Provisional value is address of the global
61060ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
611270ed1b3SSam Clegg     // For undefined symbols, use zero
612cd65f698SSam Clegg     if (!Sym->isDefined())
613270ed1b3SSam Clegg       return 0;
6146c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6156c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
616d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6176c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61860ec3034SSam Clegg   }
61960ec3034SSam Clegg   default:
62060ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
62160ec3034SSam Clegg   }
622d934cb88SDan Gohman }
623d934cb88SDan Gohman 
624759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62563ebb813SSam Clegg                     MCSectionWasm &DataSection) {
626759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
627759631c7SSam Clegg 
62863ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62963ebb813SSam Clegg 
630759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
631759631c7SSam Clegg     if (Frag.hasInstructions())
632759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
633759631c7SSam Clegg 
634759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
635759631c7SSam Clegg       if (Align->getValueSize() != 1)
636759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
637759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
638759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
639759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
640759631c7SSam Clegg                                                  Align->getAlignment()),
641759631c7SSam Clegg                                          DataBytes.size() +
642759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
643759631c7SSam Clegg       DataBytes.resize(Size, Value);
644759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
645d707c370SRafael Espindola       int64_t Size;
646d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
647d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
648d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
649759631c7SSam Clegg     } else {
650759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
651759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
652759631c7SSam Clegg 
653759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
654759631c7SSam Clegg     }
655759631c7SSam Clegg   }
656759631c7SSam Clegg 
657759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
658759631c7SSam Clegg }
659759631c7SSam Clegg 
66060ec3034SSam Clegg uint32_t
66160ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
66260ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
663b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
664b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
665b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
666acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
667acd7d2b0SSam Clegg   }
66860ec3034SSam Clegg 
66960ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
6706c899ba6SSam Clegg     report_fatal_error("symbol not found in symbol index space: " +
67160ec3034SSam Clegg                        RelEntry.Symbol->getName());
67260ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
673acd7d2b0SSam Clegg }
674acd7d2b0SSam Clegg 
675d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
676d934cb88SDan Gohman // directly.
677acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
678acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
679acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
680d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
681d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
682d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
683d934cb88SDan Gohman                       RelEntry.Offset;
684d934cb88SDan Gohman 
685b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68660ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68760ec3034SSam Clegg 
688acd7d2b0SSam Clegg     switch (RelEntry.Type) {
689acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6909d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
69160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
69260ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
693d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
694d934cb88SDan Gohman       break;
69560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
69660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6976a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6986a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
699d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
700d934cb88SDan Gohman       break;
70160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
70260ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
70360ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
70460ec3034SSam Clegg       break;
705d934cb88SDan Gohman     default:
7069d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
707d934cb88SDan Gohman     }
708d934cb88SDan Gohman   }
70918eafb6cSDan Gohman }
71018eafb6cSDan Gohman 
7119e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
712457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7139e15f359SSam Clegg   if (FunctionTypes.empty())
7149e15f359SSam Clegg     return;
7159e15f359SSam Clegg 
7169e15f359SSam Clegg   SectionBookkeeping Section;
7179e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7189e15f359SSam Clegg 
7199e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
7209e15f359SSam Clegg 
7219e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
72203e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
7239e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
7249e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7259e15f359SSam Clegg       writeValueType(Ty);
7269e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
7279e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7289e15f359SSam Clegg       writeValueType(Ty);
7299e15f359SSam Clegg   }
7309e15f359SSam Clegg 
7319e15f359SSam Clegg   endSection(Section);
7329e15f359SSam Clegg }
7339e15f359SSam Clegg 
7348defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
735f950b24aSSam Clegg                                           uint32_t DataSize,
736f950b24aSSam Clegg                                           uint32_t NumElements) {
7379e15f359SSam Clegg   if (Imports.empty())
7389e15f359SSam Clegg     return;
7399e15f359SSam Clegg 
740f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
741f950b24aSSam Clegg 
7429e15f359SSam Clegg   SectionBookkeeping Section;
7439e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7449e15f359SSam Clegg 
7459e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7468defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7478defa952SSam Clegg     writeString(Import.Module);
7488defa952SSam Clegg     writeString(Import.Field);
74903e101f1SSam Clegg     write8(Import.Kind);
7509e15f359SSam Clegg 
7519e15f359SSam Clegg     switch (Import.Kind) {
7529e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7538defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7549e15f359SSam Clegg       break;
7559e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
75603e101f1SSam Clegg       write8(Import.Global.Type);
75703e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7589e15f359SSam Clegg       break;
759f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
760f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
761f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
762f950b24aSSam Clegg       break;
763f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
76403e101f1SSam Clegg       write8(Import.Table.ElemType);
765f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
766f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
767f950b24aSSam Clegg       break;
7689e15f359SSam Clegg     default:
7699e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7709e15f359SSam Clegg     }
7719e15f359SSam Clegg   }
7729e15f359SSam Clegg 
7739e15f359SSam Clegg   endSection(Section);
7749e15f359SSam Clegg }
7759e15f359SSam Clegg 
776457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7779e15f359SSam Clegg   if (Functions.empty())
7789e15f359SSam Clegg     return;
7799e15f359SSam Clegg 
7809e15f359SSam Clegg   SectionBookkeeping Section;
7819e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7829e15f359SSam Clegg 
7839e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7849e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7859e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7869e15f359SSam Clegg 
7879e15f359SSam Clegg   endSection(Section);
7889e15f359SSam Clegg }
7899e15f359SSam Clegg 
7907c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7919e15f359SSam Clegg   if (Globals.empty())
7929e15f359SSam Clegg     return;
7939e15f359SSam Clegg 
7949e15f359SSam Clegg   SectionBookkeeping Section;
7959e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7969e15f359SSam Clegg 
7979e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7989e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7996e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
8006e7f1826SSam Clegg     write8(Global.Type.Mutable);
8019e15f359SSam Clegg 
8029e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8036e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
8049e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8059e15f359SSam Clegg   }
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   endSection(Section);
8089e15f359SSam Clegg }
8099e15f359SSam Clegg 
8108defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8119e15f359SSam Clegg   if (Exports.empty())
8129e15f359SSam Clegg     return;
8139e15f359SSam Clegg 
8149e15f359SSam Clegg   SectionBookkeeping Section;
8159e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8169e15f359SSam Clegg 
8179e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
8188defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8198defa952SSam Clegg     writeString(Export.Name);
82003e101f1SSam Clegg     write8(Export.Kind);
8219e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
8229e15f359SSam Clegg   }
8239e15f359SSam Clegg 
8249e15f359SSam Clegg   endSection(Section);
8259e15f359SSam Clegg }
8269e15f359SSam Clegg 
827457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8289e15f359SSam Clegg   if (TableElems.empty())
8299e15f359SSam Clegg     return;
8309e15f359SSam Clegg 
8319e15f359SSam Clegg   SectionBookkeeping Section;
8329e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8339e15f359SSam Clegg 
8349e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8359e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8369e15f359SSam Clegg 
8379e15f359SSam Clegg   // init expr for starting offset
8389e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
83930e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8409e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8419e15f359SSam Clegg 
8429e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8439e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8449e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8459e15f359SSam Clegg 
8469e15f359SSam Clegg   endSection(Section);
8479e15f359SSam Clegg }
8489e15f359SSam Clegg 
849457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
850457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
851457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8529e15f359SSam Clegg   if (Functions.empty())
8539e15f359SSam Clegg     return;
8549e15f359SSam Clegg 
8559e15f359SSam Clegg   SectionBookkeeping Section;
8569e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8576f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8589e15f359SSam Clegg 
8599e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8609e15f359SSam Clegg 
8619e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
862fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8639e15f359SSam Clegg 
8649e15f359SSam Clegg     int64_t Size = 0;
8659e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8669e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8679e15f359SSam Clegg 
8689e15f359SSam Clegg     encodeULEB128(Size, getStream());
869fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8709e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8719e15f359SSam Clegg   }
8729e15f359SSam Clegg 
8739e15f359SSam Clegg   // Apply fixups.
874acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8759e15f359SSam Clegg 
8769e15f359SSam Clegg   endSection(Section);
8779e15f359SSam Clegg }
8789e15f359SSam Clegg 
8796c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8806c899ba6SSam Clegg   if (DataSegments.empty())
8817c395943SSam Clegg     return;
8829e15f359SSam Clegg 
8839e15f359SSam Clegg   SectionBookkeeping Section;
8849e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8856f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8869e15f359SSam Clegg 
8876c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8887c395943SSam Clegg 
8896c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8909e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8919e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8927c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8939e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8947c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8957c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8967c395943SSam Clegg     writeBytes(Segment.Data); // data
8977c395943SSam Clegg   }
8989e15f359SSam Clegg 
8999e15f359SSam Clegg   // Apply fixups.
9007c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
9019e15f359SSam Clegg 
9029e15f359SSam Clegg   endSection(Section);
9039e15f359SSam Clegg }
9049e15f359SSam Clegg 
9056f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9066f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
9076f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
9089e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9099e15f359SSam Clegg   // for descriptions of the reloc sections.
9109e15f359SSam Clegg 
9116f08c84aSSam Clegg   if (Relocations.empty())
9129e15f359SSam Clegg     return;
9139e15f359SSam Clegg 
9149e15f359SSam Clegg   SectionBookkeeping Section;
9156f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9169e15f359SSam Clegg 
9176f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
9189e15f359SSam Clegg 
9196f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
9206f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
9216f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
9226f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
9236f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
9246f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9259e15f359SSam Clegg 
9266f08c84aSSam Clegg     write8(RelEntry.Type);
9276f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
9286f08c84aSSam Clegg     encodeULEB128(Index, Stream);
9296f08c84aSSam Clegg     if (RelEntry.hasAddend())
9306f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9319e15f359SSam Clegg   }
9329e15f359SSam Clegg 
9339e15f359SSam Clegg   endSection(Section);
9349e15f359SSam Clegg }
9359e15f359SSam Clegg 
9366a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9376a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9386a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9396a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9406a31a0d6SSam Clegg   }
9416a31a0d6SSam Clegg }
9426a31a0d6SSam Clegg 
9439e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
94486b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
945ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
946ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9479e15f359SSam Clegg   SectionBookkeeping Section;
9482322a937SSam Clegg   startCustomSection(Section, "linking");
9496bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9509e15f359SSam Clegg 
9516bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9526c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9536c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9546c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9556c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9566c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9576c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9586c899ba6SSam Clegg       switch (Sym.Kind) {
9596c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9606c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9616c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9626c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9636c899ba6SSam Clegg           writeString(Sym.Name);
9646c899ba6SSam Clegg         break;
9656c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9666c899ba6SSam Clegg         writeString(Sym.Name);
9676c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9686c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9696c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9706c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9716c899ba6SSam Clegg         }
9726c899ba6SSam Clegg         break;
9736a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9746a31a0d6SSam Clegg         const uint32_t SectionIndex =
9756a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9766a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9776a31a0d6SSam Clegg         break;
9786a31a0d6SSam Clegg       }
9796c899ba6SSam Clegg       default:
9806c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9816c899ba6SSam Clegg       }
982b7787fd0SSam Clegg     }
983b7787fd0SSam Clegg     endSection(SubSection);
984b7787fd0SSam Clegg   }
9859e15f359SSam Clegg 
9866c899ba6SSam Clegg   if (DataSegments.size()) {
98763ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9886c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9896c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
990d95ed959SSam Clegg       writeString(Segment.Name);
99163ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
99263ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
99363ebb813SSam Clegg     }
994d95ed959SSam Clegg     endSection(SubSection);
995d95ed959SSam Clegg   }
996d95ed959SSam Clegg 
997bafe6902SSam Clegg   if (!InitFuncs.empty()) {
998bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
999bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
1000bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1001bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
1002bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
1003bafe6902SSam Clegg     }
1004bafe6902SSam Clegg     endSection(SubSection);
1005bafe6902SSam Clegg   }
1006bafe6902SSam Clegg 
1007ea7caceeSSam Clegg   if (Comdats.size()) {
1008ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1009ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
1010ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1011ea7caceeSSam Clegg       writeString(C.first);
1012ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
1013ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
1014ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1015ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
1016ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
1017ea7caceeSSam Clegg       }
1018ea7caceeSSam Clegg     }
1019ea7caceeSSam Clegg     endSection(SubSection);
1020ea7caceeSSam Clegg   }
1021ea7caceeSSam Clegg 
10229e15f359SSam Clegg   endSection(Section);
10239e15f359SSam Clegg }
10249e15f359SSam Clegg 
10256a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10266a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10276a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1028cfd44a2eSSam Clegg     SectionBookkeeping Section;
10296a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10302322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10316a31a0d6SSam Clegg 
10326a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10336a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10346a31a0d6SSam Clegg 
10356a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10366a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10376a31a0d6SSam Clegg 
1038cfd44a2eSSam Clegg     endSection(Section);
10396a31a0d6SSam Clegg 
10406a31a0d6SSam Clegg     // Apply fixups.
1041*4d57fbd0SSam Clegg     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1042*4d57fbd0SSam Clegg     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10436a31a0d6SSam Clegg   }
10446a31a0d6SSam Clegg }
10456a31a0d6SSam Clegg 
10465e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10475e3d33a7SSam Clegg   assert(Symbol.isFunction());
10485e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10495e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10505e3d33a7SSam Clegg }
10515e3d33a7SSam Clegg 
10525e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10535e3d33a7SSam Clegg   assert(Symbol.isFunction());
10545e3d33a7SSam Clegg 
10555e3d33a7SSam Clegg   WasmFunctionType F;
1056aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10575e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10585e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10595e3d33a7SSam Clegg 
10605e3d33a7SSam Clegg   auto Pair =
10615e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10625e3d33a7SSam Clegg   if (Pair.second)
10635e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10645e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10655e3d33a7SSam Clegg 
10665e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
10675e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10685e3d33a7SSam Clegg   return Pair.first->second;
10695e3d33a7SSam Clegg }
10705e3d33a7SSam Clegg 
1071*4d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
1072*4d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
1073*4d57fbd0SSam Clegg     return true;
1074*4d57fbd0SSam Clegg 
1075*4d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
1076*4d57fbd0SSam Clegg     return false;
1077*4d57fbd0SSam Clegg 
1078*4d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
1079*4d57fbd0SSam Clegg     return false;
1080*4d57fbd0SSam Clegg 
1081*4d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1082*4d57fbd0SSam Clegg     return false;
1083*4d57fbd0SSam Clegg 
1084*4d57fbd0SSam Clegg   if (Sym.isSection())
1085*4d57fbd0SSam Clegg     return false;
1086*4d57fbd0SSam Clegg 
1087*4d57fbd0SSam Clegg   return true;
1088*4d57fbd0SSam Clegg }
1089*4d57fbd0SSam Clegg 
109018eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
109118eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1092b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
109382607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1094d934cb88SDan Gohman 
1095d934cb88SDan Gohman   // Collect information from the available symbols.
1096d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1097d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
10988defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
10998defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
11006c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1101bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1102ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11037c395943SSam Clegg   uint32_t DataSize = 0;
1104d934cb88SDan Gohman 
1105f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1106f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1107f950b24aSSam Clegg   // it if there are no loads or stores.
1108f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1109f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11108defa952SSam Clegg   wasm::WasmImport MemImport;
11118defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11128defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1113f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1114f950b24aSSam Clegg   Imports.push_back(MemImport);
1115f950b24aSSam Clegg 
1116f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1117f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1118f950b24aSSam Clegg   // it if there are no indirect calls.
1119f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1120f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11218defa952SSam Clegg   wasm::WasmImport TableImport;
11228defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11238defa952SSam Clegg   TableImport.Field = TableSym->getName();
1124f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11258defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1126f950b24aSSam Clegg   Imports.push_back(TableImport);
1127f950b24aSSam Clegg 
1128586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1129586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1130586320c0SNicholas Wilson   // symbols.
113132ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
113232ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
113332ce5ca0SDan Gohman 
113432ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11359f3fe42eSSam Clegg     // (because wasm always needs a type signature).
113632ce5ca0SDan Gohman     if (WS.isFunction())
113732ce5ca0SDan Gohman       registerFunctionType(WS);
113832ce5ca0SDan Gohman 
113932ce5ca0SDan Gohman     if (WS.isTemporary())
114032ce5ca0SDan Gohman       continue;
114132ce5ca0SDan Gohman 
114232ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11436c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11446c899ba6SSam Clegg       if (WS.isFunction()) {
11458defa952SSam Clegg         wasm::WasmImport Import;
11468defa952SSam Clegg         Import.Module = WS.getModuleName();
11478defa952SSam Clegg         Import.Field = WS.getName();
114832ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11498defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11506c899ba6SSam Clegg         Imports.push_back(Import);
11516c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11526c899ba6SSam Clegg       } else if (WS.isGlobal()) {
115315f349f7SNicholas Wilson         if (WS.isWeak())
115415f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
115515f349f7SNicholas Wilson 
11566c899ba6SSam Clegg         wasm::WasmImport Import;
11576c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11586c899ba6SSam Clegg         Import.Field = WS.getName();
115932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11606c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11616c899ba6SSam Clegg         Imports.push_back(Import);
11626c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
116332ce5ca0SDan Gohman       }
116432ce5ca0SDan Gohman     }
116532ce5ca0SDan Gohman   }
116632ce5ca0SDan Gohman 
1167*4d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
1168*4d57fbd0SSam Clegg   // populating DataLocations.
1169759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1170759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1171*4d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1172759631c7SSam Clegg 
1173bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1174*4d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1175bafe6902SSam Clegg       continue;
1176bafe6902SSam Clegg 
1177*4d57fbd0SSam Clegg     // Code is handled separately
1178*4d57fbd0SSam Clegg     if (Section.getKind().isText())
1179*4d57fbd0SSam Clegg       continue;
1180*4d57fbd0SSam Clegg 
1181*4d57fbd0SSam Clegg     if (Section.isWasmData()) {
1182329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1183759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1184759631c7SSam Clegg       DataSegments.emplace_back();
1185759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
1186*4d57fbd0SSam Clegg       Segment.Name = SectionName;
1187759631c7SSam Clegg       Segment.Offset = DataSize;
1188759631c7SSam Clegg       Segment.Section = &Section;
118963ebb813SSam Clegg       addData(Segment.Data, Section);
119063ebb813SSam Clegg       Segment.Alignment = Section.getAlignment();
119163ebb813SSam Clegg       Segment.Flags = 0;
1192759631c7SSam Clegg       DataSize += Segment.Data.size();
11936c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1194ea7caceeSSam Clegg 
1195ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1196ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1197329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1198ea7caceeSSam Clegg       }
1199*4d57fbd0SSam Clegg     } else {
1200*4d57fbd0SSam Clegg       // Create custom sections
1201*4d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
1202*4d57fbd0SSam Clegg 
1203*4d57fbd0SSam Clegg       StringRef Name = SectionName;
1204*4d57fbd0SSam Clegg 
1205*4d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
1206*4d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
1207*4d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
1208*4d57fbd0SSam Clegg 
1209*4d57fbd0SSam Clegg       MCSymbol* Begin = Sec.getBeginSymbol();
1210*4d57fbd0SSam Clegg       if (Begin)
1211*4d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1212*4d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1213759631c7SSam Clegg     }
12146a31a0d6SSam Clegg   }
12156a31a0d6SSam Clegg 
1216586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1217d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1218d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1219d934cb88SDan Gohman     // or used in relocations.
1220d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1221d934cb88SDan Gohman       continue;
1222b7787fd0SSam Clegg 
1223d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1224a165f2d6SSam Clegg     DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1225a165f2d6SSam Clegg                  << " '" << S << "'"
1226329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1227329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1228329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1229b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1230a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1231b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1232b7787fd0SSam Clegg 
12335e3d33a7SSam Clegg     if (WS.isVariable())
12345e3d33a7SSam Clegg       continue;
12356c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12366c899ba6SSam Clegg       continue;
1237b7787fd0SSam Clegg 
1238d934cb88SDan Gohman     if (WS.isFunction()) {
12396c899ba6SSam Clegg       unsigned Index;
1240cd65f698SSam Clegg       if (WS.isDefined()) {
1241b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1242b7787fd0SSam Clegg           report_fatal_error(
1243b7787fd0SSam Clegg               "function sections must contain one function each");
1244b7787fd0SSam Clegg 
1245b7787fd0SSam Clegg         if (WS.getSize() == 0)
1246b7787fd0SSam Clegg           report_fatal_error(
1247b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1248b7787fd0SSam Clegg 
12496c899ba6SSam Clegg         // A definition. Write out the function body.
12509f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1251d934cb88SDan Gohman         WasmFunction Func;
12525e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1253d934cb88SDan Gohman         Func.Sym = &WS;
12546c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1255d934cb88SDan Gohman         Functions.push_back(Func);
12566c899ba6SSam Clegg 
12576c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12586c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12596c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12606c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12616c899ba6SSam Clegg         }
1262d934cb88SDan Gohman       } else {
1263d934cb88SDan Gohman         // An import; the index was assigned above.
12646c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1265d934cb88SDan Gohman       }
1266d934cb88SDan Gohman 
12675e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
12686c899ba6SSam Clegg     } else if (WS.isData()) {
1269c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1270c38e947eSSam Clegg         continue;
1271c38e947eSSam Clegg 
12726c899ba6SSam Clegg       if (!WS.isDefined()) {
1273a165f2d6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1" << "\n");
1274fe6414b0SSam Clegg         continue;
12756c899ba6SSam Clegg       }
1276fe6414b0SSam Clegg 
1277d934cb88SDan Gohman       if (!WS.getSize())
1278c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1279c38e947eSSam Clegg                            WS.getName());
1280d934cb88SDan Gohman 
1281d934cb88SDan Gohman       int64_t Size = 0;
1282d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1283d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1284d934cb88SDan Gohman 
1285759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1286ea7caceeSSam Clegg       assert(DataSection.isWasmData());
12877c395943SSam Clegg 
12886c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
12896c899ba6SSam Clegg       // corresponding Wasm data segment.
12906c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
12916c899ba6SSam Clegg           DataSection.getSegmentIndex(),
12926c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
12936c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
12946c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1295a165f2d6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1296a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
12976c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1298545932beSEric Christopher       if (WS.isDefined())
12996c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13006c899ba6SSam Clegg 
1301545932beSEric Christopher       // An import; the index was assigned above
1302545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1303545932beSEric Christopher                    << "\n");
1304a165f2d6SSam Clegg     } else {
1305a165f2d6SSam Clegg       assert(WS.isSection());
1306d934cb88SDan Gohman     }
1307d934cb88SDan Gohman   }
1308d934cb88SDan Gohman 
1309586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1310586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1311586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1312586320c0SNicholas Wilson   // necessarily ordered in this way.
1313b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1314b7787fd0SSam Clegg     if (!S.isVariable())
1315b7787fd0SSam Clegg       continue;
131631a2c809SSam Clegg 
1317cd65f698SSam Clegg     assert(S.isDefined());
1318b7787fd0SSam Clegg 
13195e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1320aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1321aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
13225e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1323b7787fd0SSam Clegg 
13246c899ba6SSam Clegg     if (WS.isFunction()) {
13256c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13266c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13276c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
13286c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13296c899ba6SSam Clegg     } else if (WS.isData()) {
13306c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13316c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13326c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13336c899ba6SSam Clegg       DataLocations[&WS] = Ref;
13346c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13356c899ba6SSam Clegg     } else {
13366c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13376c899ba6SSam Clegg     }
1338586320c0SNicholas Wilson   }
133931a2c809SSam Clegg 
1340586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1341586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1342586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1343*4d57fbd0SSam Clegg     if (!isInSymtab(WS))
1344586320c0SNicholas Wilson       continue;
1345*4d57fbd0SSam Clegg     DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1346586320c0SNicholas Wilson 
1347586320c0SNicholas Wilson     uint32_t Flags = 0;
1348586320c0SNicholas Wilson     if (WS.isWeak())
1349586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1350586320c0SNicholas Wilson     if (WS.isHidden())
1351586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1352586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1353586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1354586320c0SNicholas Wilson     if (WS.isUndefined())
1355586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1356586320c0SNicholas Wilson 
1357586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1358586320c0SNicholas Wilson     Info.Name = WS.getName();
1359586320c0SNicholas Wilson     Info.Kind = WS.getType();
1360586320c0SNicholas Wilson     Info.Flags = Flags;
1361*4d57fbd0SSam Clegg     if (!WS.isData()) {
1362*4d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1363586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
1364*4d57fbd0SSam Clegg     } else if (WS.isDefined()) {
1365*4d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1366586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
1367*4d57fbd0SSam Clegg     }
1368586320c0SNicholas Wilson     SymbolIndices[&WS] = SymbolInfos.size();
1369586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1370b7787fd0SSam Clegg   }
1371b7787fd0SSam Clegg 
13726006e091SSam Clegg   {
13736006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1374f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1375f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1376f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1377f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1378f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1379f9edbe95SSam Clegg         return;
1380f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1381f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
13826c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1383f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1384f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1385329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1386f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
13876c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
13886006e091SSam Clegg         registerFunctionType(WS);
13896006e091SSam Clegg       }
13906006e091SSam Clegg     };
1391970d02c4SDan Gohman 
13926006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
13936006e091SSam Clegg       HandleReloc(RelEntry);
13946006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
13956006e091SSam Clegg       HandleReloc(RelEntry);
1396d934cb88SDan Gohman   }
1397d934cb88SDan Gohman 
1398bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1399bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1400bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1401bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1402bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1403bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1404bafe6902SSam Clegg       continue;
1405bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1406bafe6902SSam Clegg       continue;
1407bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1408bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1409bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1410bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1411bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1412bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1413bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1414bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1415bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1416bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1417bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1418*4d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
1419*4d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
1420*4d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1421bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1422*4d57fbd0SSam Clegg       if (WS.getSectionName()
1423*4d57fbd0SSam Clegg               .substr(PrefixLength + 1)
1424*4d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1425bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1426bafe6902SSam Clegg     }
1427bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1428bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1429bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1430bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1431bafe6902SSam Clegg          p != end; ++p) {
1432bafe6902SSam Clegg       if (*p != 0)
1433bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1434bafe6902SSam Clegg     }
1435bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1436bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1437bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1438bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1439bafe6902SSam Clegg       if (!Sym)
1440bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1441bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1442bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1443bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1444bafe6902SSam Clegg       if (I == SymbolIndices.end())
1445bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1446bafe6902SSam Clegg       uint32_t Index = I->second;
1447bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1448bafe6902SSam Clegg     }
1449bafe6902SSam Clegg   }
1450bafe6902SSam Clegg 
145118eafb6cSDan Gohman   // Write out the Wasm header.
145218eafb6cSDan Gohman   writeHeader(Asm);
145318eafb6cSDan Gohman 
14549e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1455f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14569e15f359SSam Clegg   writeFunctionSection(Functions);
1457f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1458f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14597c395943SSam Clegg   writeGlobalSection();
14609e15f359SSam Clegg   writeExportSection(Exports);
14619e15f359SSam Clegg   writeElemSection(TableElems);
1462acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14636c899ba6SSam Clegg   writeDataSection();
14646a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
1465c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
14666f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
14676f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
14686a31a0d6SSam Clegg   writeCustomRelocSections();
1469970d02c4SDan Gohman 
1470d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
147118eafb6cSDan Gohman }
147218eafb6cSDan Gohman 
147360fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
14741301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
147518eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
14760917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
147718eafb6cSDan Gohman }
1478