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 
20225d8e68bSSam Clegg static const uint32_t INVALID_INDEX = -1;
20325d8e68bSSam Clegg 
204cfd44a2eSSam Clegg struct WasmCustomSection {
205cfd44a2eSSam Clegg 
2066a31a0d6SSam Clegg   StringRef Name;
2076a31a0d6SSam Clegg   MCSectionWasm *Section;
2086a31a0d6SSam Clegg 
2096a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
2106a31a0d6SSam Clegg   uint32_t OutputIndex;
2116a31a0d6SSam Clegg 
2126a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
2136a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
2146a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
215cfd44a2eSSam Clegg };
216cfd44a2eSSam Clegg 
2171fb8daa6SSam Clegg #if !defined(NDEBUG)
2187f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
219b7787fd0SSam Clegg   Rel.print(OS);
220b7787fd0SSam Clegg   return OS;
221b7787fd0SSam Clegg }
2221fb8daa6SSam Clegg #endif
223b7787fd0SSam Clegg 
22418eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
22518eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22618eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22718eafb6cSDan Gohman 
228d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
229d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2306f08c84aSSam Clegg   uint32_t CodeSectionIndex;
231d934cb88SDan Gohman 
232d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
233d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2346f08c84aSSam Clegg   uint32_t DataSectionIndex;
235d934cb88SDan Gohman 
236d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
237acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
238acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
239d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
240d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
241f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
242a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2436c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2446c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2456c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2466a31a0d6SSam Clegg 
2476a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2486a31a0d6SSam Clegg   // section.
2496a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2506a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2516a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2526a31a0d6SSam Clegg       CustomSectionsRelocations;
253acd7d2b0SSam Clegg 
254acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
255acd7d2b0SSam Clegg       FunctionTypeIndices;
2565e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2577c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2586c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2599f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2607c395943SSam Clegg   unsigned NumGlobalImports = 0;
2617e1c3345SChandler Carruth   uint32_t SectionCount = 0;
262d934cb88SDan Gohman 
26318eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
265ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
266ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
26718eafb6cSDan Gohman   }
26818eafb6cSDan Gohman 
2692322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2702322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
271d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
272d934cb88SDan Gohman 
27318eafb6cSDan Gohman public:
2741301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2751301a878SLang Hames                    raw_pwrite_stream &OS)
2761301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2771301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
27818eafb6cSDan Gohman 
27918eafb6cSDan Gohman   ~WasmObjectWriter() override;
28018eafb6cSDan Gohman 
2810917c9e4SDan Gohman private:
282acd7d2b0SSam Clegg   void reset() override {
283acd7d2b0SSam Clegg     CodeRelocations.clear();
284acd7d2b0SSam Clegg     DataRelocations.clear();
285acd7d2b0SSam Clegg     TypeIndices.clear();
2866c899ba6SSam Clegg     WasmIndices.clear();
287f9edbe95SSam Clegg     TableIndices.clear();
2886c899ba6SSam Clegg     DataLocations.clear();
2896a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
290acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2915e3d33a7SSam Clegg     FunctionTypes.clear();
2927c395943SSam Clegg     Globals.clear();
2936c899ba6SSam Clegg     DataSegments.clear();
294acd7d2b0SSam Clegg     MCObjectWriter::reset();
2959f3fe42eSSam Clegg     NumFunctionImports = 0;
2967c395943SSam Clegg     NumGlobalImports = 0;
297acd7d2b0SSam Clegg   }
298acd7d2b0SSam Clegg 
29918eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30018eafb6cSDan Gohman 
30118eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30218eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
303ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30418eafb6cSDan Gohman 
30518eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30618eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30718eafb6cSDan Gohman 
30818eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3099e15f359SSam Clegg 
310b7787fd0SSam Clegg   void writeString(const StringRef Str) {
311b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
312b7787fd0SSam Clegg     writeBytes(Str);
313b7787fd0SSam Clegg   }
314b7787fd0SSam Clegg 
3159e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
31603e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
3179e15f359SSam Clegg   }
3189e15f359SSam Clegg 
319457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
3208defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
321f950b24aSSam Clegg                           uint32_t NumElements);
322457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3237c395943SSam Clegg   void writeGlobalSection();
3248defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
325457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3269e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
327457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3286c899ba6SSam Clegg   void writeDataSection();
3296f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3306f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
33131a2c809SSam Clegg   void writeLinkingMetaDataSection(
33286b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
333ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
334ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3356a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3366a31a0d6SSam Clegg   void writeCustomRelocSections();
3376a31a0d6SSam Clegg   void
3386a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3396a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
340acd7d2b0SSam Clegg 
3417c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
342acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
343acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
344acd7d2b0SSam Clegg 
345acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3465e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3475e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
34818eafb6cSDan Gohman };
3499e15f359SSam Clegg 
35018eafb6cSDan Gohman } // end anonymous namespace
35118eafb6cSDan Gohman 
35218eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
35318eafb6cSDan Gohman 
354d934cb88SDan Gohman // Write out a section header and a patchable section size field.
355d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3562322a937SSam Clegg                                     unsigned SectionId) {
3572322a937SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << "\n");
35803e101f1SSam Clegg   write8(SectionId);
359d934cb88SDan Gohman 
360d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
361d934cb88SDan Gohman 
362d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
363d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
364d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
365d934cb88SDan Gohman 
366d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
367d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
3686a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3696f08c84aSSam Clegg   Section.Index = SectionCount++;
370d934cb88SDan Gohman }
3712322a937SSam Clegg 
3722322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3732322a937SSam Clegg                                           StringRef Name) {
3742322a937SSam Clegg   DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3752322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3766a31a0d6SSam Clegg 
3776a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3786a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3796a31a0d6SSam Clegg 
3802322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3812322a937SSam Clegg   writeString(Name);
3826a31a0d6SSam Clegg 
3836a31a0d6SSam Clegg   // The position where the custom section starts.
3846a31a0d6SSam Clegg   Section.ContentsOffset = getStream().tell();
385d934cb88SDan Gohman }
386d934cb88SDan Gohman 
387d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
388d934cb88SDan Gohman // section size field at the start of the section.
389d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3906a31a0d6SSam Clegg   uint64_t Size = getStream().tell() - Section.PayloadOffset;
391d934cb88SDan Gohman   if (uint32_t(Size) != Size)
392d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
393d934cb88SDan Gohman 
394b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
395d934cb88SDan Gohman 
396d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
397d934cb88SDan Gohman   // the section id byte.
398d934cb88SDan Gohman   uint8_t Buffer[16];
39966a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
400d934cb88SDan Gohman   assert(SizeLen == 5);
401d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
402d934cb88SDan Gohman }
403d934cb88SDan Gohman 
40418eafb6cSDan Gohman // Emit the Wasm header.
40518eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4067ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
4077ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
40818eafb6cSDan Gohman }
40918eafb6cSDan Gohman 
41018eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41118eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
41218eafb6cSDan Gohman }
41318eafb6cSDan Gohman 
41418eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
41518eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
41618eafb6cSDan Gohman                                         const MCFragment *Fragment,
41718eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
418ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
419ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
420ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
421ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
422fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
423d934cb88SDan Gohman   uint64_t C = Target.getConstant();
424d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
425d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
426d934cb88SDan Gohman 
427bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
428bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
429bafe6902SSam Clegg     return;
430bafe6902SSam Clegg 
431d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
432d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
433d934cb88SDan Gohman            "Should not have constructed this");
434d934cb88SDan Gohman 
435d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
436d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
437d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
438d934cb88SDan Gohman 
439d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
440d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
441d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
442d934cb88SDan Gohman     if (IsPCRel) {
443d934cb88SDan Gohman       Ctx.reportError(
444d934cb88SDan Gohman           Fixup.getLoc(),
445d934cb88SDan Gohman           "No relocation available to represent this relative expression");
446d934cb88SDan Gohman       return;
447d934cb88SDan Gohman     }
448d934cb88SDan Gohman 
449d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
450d934cb88SDan Gohman 
451d934cb88SDan Gohman     if (SymB.isUndefined()) {
452d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
453d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
454d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
455d934cb88SDan Gohman       return;
456d934cb88SDan Gohman     }
457d934cb88SDan Gohman 
458d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
459d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
460d934cb88SDan Gohman     if (&SecB != &FixupSection) {
461d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
462d934cb88SDan Gohman                       "Cannot represent a difference across sections");
463d934cb88SDan Gohman       return;
464d934cb88SDan Gohman     }
465d934cb88SDan Gohman 
466d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
467d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
468d934cb88SDan Gohman     IsPCRel = true;
469d934cb88SDan Gohman     C -= K;
470d934cb88SDan Gohman   }
471d934cb88SDan Gohman 
472d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
473d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
474d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
475d934cb88SDan Gohman 
476d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
477d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4786ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4796ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4806ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
481d934cb88SDan Gohman   }
482d934cb88SDan Gohman 
483d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
484d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
485d934cb88SDan Gohman   // be negative and don't wrap.
486d934cb88SDan Gohman   FixedValue = 0;
487d934cb88SDan Gohman 
4884d57fbd0SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
489ae03c1e7SSam Clegg   assert(!IsPCRel);
4909d24fb7fSSam Clegg   assert(SymA);
4919d24fb7fSSam Clegg 
4924d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4934d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4944d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
4954d57fbd0SSam Clegg   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
4964d57fbd0SSam Clegg       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
4974d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4984d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4994d57fbd0SSam Clegg                          "only supported in metadata sections");
5004d57fbd0SSam Clegg 
5014d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5024d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5034d57fbd0SSam Clegg     if (SecA.getKind().isText())
5044d57fbd0SSam Clegg       SectionSymbol = SecA.begin()->getAtom();
5054d57fbd0SSam Clegg     else
5064d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5074d57fbd0SSam Clegg     if (!SectionSymbol)
5084d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5094d57fbd0SSam Clegg 
5104d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5114d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5124d57fbd0SSam Clegg   }
5134d57fbd0SSam Clegg 
5144d57fbd0SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
5154d57fbd0SSam Clegg   // against a named symbol.
5164d57fbd0SSam Clegg   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
5174d57fbd0SSam Clegg     if (SymA->getName().empty())
5184d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5194d57fbd0SSam Clegg                          "supported by wasm");
5204d57fbd0SSam Clegg 
5214d57fbd0SSam Clegg     SymA->setUsedInReloc();
5224d57fbd0SSam Clegg   }
523ae03c1e7SSam Clegg 
524d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
525b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
526d934cb88SDan Gohman 
5276a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
528d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5296a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
53012fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5316a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5326a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5336a31a0d6SSam Clegg   } else {
53412fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
535d934cb88SDan Gohman   }
5366a31a0d6SSam Clegg }
537d934cb88SDan Gohman 
538d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
539d934cb88SDan Gohman // to allow patching.
540d934cb88SDan Gohman static void
541d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
542d934cb88SDan Gohman   uint8_t Buffer[5];
54366a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
544d934cb88SDan Gohman   assert(SizeLen == 5);
545d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
546d934cb88SDan Gohman }
547d934cb88SDan Gohman 
548d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
549d934cb88SDan Gohman // to allow patching.
550d934cb88SDan Gohman static void
551d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
552d934cb88SDan Gohman   uint8_t Buffer[5];
55366a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
554d934cb88SDan Gohman   assert(SizeLen == 5);
555d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
556d934cb88SDan Gohman }
557d934cb88SDan Gohman 
558d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
559d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
560d934cb88SDan Gohman   uint8_t Buffer[4];
561d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
562d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
563d934cb88SDan Gohman }
564d934cb88SDan Gohman 
565aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
566aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
567aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
568aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
569aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
570aff1c4dfSSam Clegg   }
571aff1c4dfSSam Clegg   return &Symbol;
572aff1c4dfSSam Clegg }
573aff1c4dfSSam Clegg 
574d934cb88SDan Gohman // Compute a value to write into the code at the location covered
57560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57660ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57760ec3034SSam Clegg // useable.
5787c395943SSam Clegg uint32_t
5797c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
58060ec3034SSam Clegg   switch (RelEntry.Type) {
58160ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
582f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
583f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
584f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
585f9edbe95SSam Clegg     assert(Sym->isFunction());
586f9edbe95SSam Clegg     return TableIndices[Sym];
587f9edbe95SSam Clegg   }
58860ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5896c899ba6SSam Clegg     // Provisional value is same as the index
59060ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5916c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5926c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5936c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5946c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5956c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5966c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5976c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5984d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
5994d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
6006a31a0d6SSam Clegg     const auto &Section =
6016a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6026a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6036a31a0d6SSam Clegg   }
60460ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
60560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
60660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
607f9edbe95SSam Clegg     // Provisional value is address of the global
60860ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
609270ed1b3SSam Clegg     // For undefined symbols, use zero
610cd65f698SSam Clegg     if (!Sym->isDefined())
611270ed1b3SSam Clegg       return 0;
6126c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6136c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
614d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6156c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61660ec3034SSam Clegg   }
61760ec3034SSam Clegg   default:
61860ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61960ec3034SSam Clegg   }
620d934cb88SDan Gohman }
621d934cb88SDan Gohman 
622759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62363ebb813SSam Clegg                     MCSectionWasm &DataSection) {
624759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
625759631c7SSam Clegg 
62663ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62763ebb813SSam Clegg 
628759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
629759631c7SSam Clegg     if (Frag.hasInstructions())
630759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
631759631c7SSam Clegg 
632759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
633759631c7SSam Clegg       if (Align->getValueSize() != 1)
634759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
635759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
636759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
637759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
638759631c7SSam Clegg                                                  Align->getAlignment()),
639759631c7SSam Clegg                                          DataBytes.size() +
640759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
641759631c7SSam Clegg       DataBytes.resize(Size, Value);
642759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
643d707c370SRafael Espindola       int64_t Size;
644d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
645d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
646d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
647759631c7SSam Clegg     } else {
648759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
649759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
650759631c7SSam Clegg 
651759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
652759631c7SSam Clegg     }
653759631c7SSam Clegg   }
654759631c7SSam Clegg 
655759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
656759631c7SSam Clegg }
657759631c7SSam Clegg 
65860ec3034SSam Clegg uint32_t
65960ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
66060ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
661b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
662b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
663b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
664acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
665acd7d2b0SSam Clegg   }
66660ec3034SSam Clegg 
66725d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
668acd7d2b0SSam Clegg }
669acd7d2b0SSam Clegg 
670d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
671d934cb88SDan Gohman // directly.
672acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
673acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
674acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
675d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
676d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
677d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
678d934cb88SDan Gohman                       RelEntry.Offset;
679d934cb88SDan Gohman 
680b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68160ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68260ec3034SSam Clegg 
683acd7d2b0SSam Clegg     switch (RelEntry.Type) {
684acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6859d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
68660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
68760ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
688d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
689d934cb88SDan Gohman       break;
69060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
69160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6926a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6936a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
694d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
695d934cb88SDan Gohman       break;
69660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
69760ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
69860ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
69960ec3034SSam Clegg       break;
700d934cb88SDan Gohman     default:
7019d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
702d934cb88SDan Gohman     }
703d934cb88SDan Gohman   }
70418eafb6cSDan Gohman }
70518eafb6cSDan Gohman 
7069e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
707457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7089e15f359SSam Clegg   if (FunctionTypes.empty())
7099e15f359SSam Clegg     return;
7109e15f359SSam Clegg 
7119e15f359SSam Clegg   SectionBookkeeping Section;
7129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7139e15f359SSam Clegg 
7149e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
7159e15f359SSam Clegg 
7169e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
71703e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
7189e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
7199e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7209e15f359SSam Clegg       writeValueType(Ty);
7219e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
7229e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7239e15f359SSam Clegg       writeValueType(Ty);
7249e15f359SSam Clegg   }
7259e15f359SSam Clegg 
7269e15f359SSam Clegg   endSection(Section);
7279e15f359SSam Clegg }
7289e15f359SSam Clegg 
7298defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
730f950b24aSSam Clegg                                           uint32_t DataSize,
731f950b24aSSam Clegg                                           uint32_t NumElements) {
7329e15f359SSam Clegg   if (Imports.empty())
7339e15f359SSam Clegg     return;
7349e15f359SSam Clegg 
735f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
736f950b24aSSam Clegg 
7379e15f359SSam Clegg   SectionBookkeeping Section;
7389e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7399e15f359SSam Clegg 
7409e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7418defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7428defa952SSam Clegg     writeString(Import.Module);
7438defa952SSam Clegg     writeString(Import.Field);
74403e101f1SSam Clegg     write8(Import.Kind);
7459e15f359SSam Clegg 
7469e15f359SSam Clegg     switch (Import.Kind) {
7479e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7488defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7499e15f359SSam Clegg       break;
7509e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
75103e101f1SSam Clegg       write8(Import.Global.Type);
75203e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7539e15f359SSam Clegg       break;
754f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
755f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
756f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
757f950b24aSSam Clegg       break;
758f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
75903e101f1SSam Clegg       write8(Import.Table.ElemType);
760f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
761f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
762f950b24aSSam Clegg       break;
7639e15f359SSam Clegg     default:
7649e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7659e15f359SSam Clegg     }
7669e15f359SSam Clegg   }
7679e15f359SSam Clegg 
7689e15f359SSam Clegg   endSection(Section);
7699e15f359SSam Clegg }
7709e15f359SSam Clegg 
771457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7729e15f359SSam Clegg   if (Functions.empty())
7739e15f359SSam Clegg     return;
7749e15f359SSam Clegg 
7759e15f359SSam Clegg   SectionBookkeeping Section;
7769e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7779e15f359SSam Clegg 
7789e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7799e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7809e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7819e15f359SSam Clegg 
7829e15f359SSam Clegg   endSection(Section);
7839e15f359SSam Clegg }
7849e15f359SSam Clegg 
7857c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7869e15f359SSam Clegg   if (Globals.empty())
7879e15f359SSam Clegg     return;
7889e15f359SSam Clegg 
7899e15f359SSam Clegg   SectionBookkeeping Section;
7909e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7919e15f359SSam Clegg 
7929e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7939e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7946e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7956e7f1826SSam Clegg     write8(Global.Type.Mutable);
7969e15f359SSam Clegg 
7979e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7986e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7999e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8009e15f359SSam Clegg   }
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   endSection(Section);
8039e15f359SSam Clegg }
8049e15f359SSam Clegg 
8058defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8069e15f359SSam Clegg   if (Exports.empty())
8079e15f359SSam Clegg     return;
8089e15f359SSam Clegg 
8099e15f359SSam Clegg   SectionBookkeeping Section;
8109e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8119e15f359SSam Clegg 
8129e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
8138defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8148defa952SSam Clegg     writeString(Export.Name);
81503e101f1SSam Clegg     write8(Export.Kind);
8169e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
8179e15f359SSam Clegg   }
8189e15f359SSam Clegg 
8199e15f359SSam Clegg   endSection(Section);
8209e15f359SSam Clegg }
8219e15f359SSam Clegg 
822457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8239e15f359SSam Clegg   if (TableElems.empty())
8249e15f359SSam Clegg     return;
8259e15f359SSam Clegg 
8269e15f359SSam Clegg   SectionBookkeeping Section;
8279e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8289e15f359SSam Clegg 
8299e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8309e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8319e15f359SSam Clegg 
8329e15f359SSam Clegg   // init expr for starting offset
8339e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
83430e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8359e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8369e15f359SSam Clegg 
8379e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8389e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8399e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8409e15f359SSam Clegg 
8419e15f359SSam Clegg   endSection(Section);
8429e15f359SSam Clegg }
8439e15f359SSam Clegg 
844457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
845457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
846457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8479e15f359SSam Clegg   if (Functions.empty())
8489e15f359SSam Clegg     return;
8499e15f359SSam Clegg 
8509e15f359SSam Clegg   SectionBookkeeping Section;
8519e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8526f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8539e15f359SSam Clegg 
8549e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
857fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8589e15f359SSam Clegg 
8599e15f359SSam Clegg     int64_t Size = 0;
8609e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8619e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8629e15f359SSam Clegg 
8639e15f359SSam Clegg     encodeULEB128(Size, getStream());
864fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8659e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8669e15f359SSam Clegg   }
8679e15f359SSam Clegg 
8689e15f359SSam Clegg   // Apply fixups.
869acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   endSection(Section);
8729e15f359SSam Clegg }
8739e15f359SSam Clegg 
8746c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8756c899ba6SSam Clegg   if (DataSegments.empty())
8767c395943SSam Clegg     return;
8779e15f359SSam Clegg 
8789e15f359SSam Clegg   SectionBookkeeping Section;
8799e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8806f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8819e15f359SSam Clegg 
8826c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8837c395943SSam Clegg 
8846c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8859e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8869e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8877c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8889e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8897c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8907c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8917c395943SSam Clegg     writeBytes(Segment.Data); // data
8927c395943SSam Clegg   }
8939e15f359SSam Clegg 
8949e15f359SSam Clegg   // Apply fixups.
8957c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8969e15f359SSam Clegg 
8979e15f359SSam Clegg   endSection(Section);
8989e15f359SSam Clegg }
8999e15f359SSam Clegg 
9006f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9016f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
9026f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
9039e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9049e15f359SSam Clegg   // for descriptions of the reloc sections.
9059e15f359SSam Clegg 
9066f08c84aSSam Clegg   if (Relocations.empty())
9079e15f359SSam Clegg     return;
9089e15f359SSam Clegg 
9099e15f359SSam Clegg   SectionBookkeeping Section;
9106f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9119e15f359SSam Clegg 
9126f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
9139e15f359SSam Clegg 
9146f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
9156f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
9166f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
9176f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
9186f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
9196f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9209e15f359SSam Clegg 
9216f08c84aSSam Clegg     write8(RelEntry.Type);
9226f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
9236f08c84aSSam Clegg     encodeULEB128(Index, Stream);
9246f08c84aSSam Clegg     if (RelEntry.hasAddend())
9256f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9269e15f359SSam Clegg   }
9279e15f359SSam Clegg 
9289e15f359SSam Clegg   endSection(Section);
9299e15f359SSam Clegg }
9309e15f359SSam Clegg 
9316a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9326a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9336a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9346a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9356a31a0d6SSam Clegg   }
9366a31a0d6SSam Clegg }
9376a31a0d6SSam Clegg 
9389e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
93986b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
940ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
941ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9429e15f359SSam Clegg   SectionBookkeeping Section;
9432322a937SSam Clegg   startCustomSection(Section, "linking");
9446bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9459e15f359SSam Clegg 
9466bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9476c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9486c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9496c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9506c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9516c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9526c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9536c899ba6SSam Clegg       switch (Sym.Kind) {
9546c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9556c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9566c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9576c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9586c899ba6SSam Clegg           writeString(Sym.Name);
9596c899ba6SSam Clegg         break;
9606c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9616c899ba6SSam Clegg         writeString(Sym.Name);
9626c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9636c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9646c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9656c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9666c899ba6SSam Clegg         }
9676c899ba6SSam Clegg         break;
9686a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9696a31a0d6SSam Clegg         const uint32_t SectionIndex =
9706a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9716a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9726a31a0d6SSam Clegg         break;
9736a31a0d6SSam Clegg       }
9746c899ba6SSam Clegg       default:
9756c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9766c899ba6SSam Clegg       }
977b7787fd0SSam Clegg     }
978b7787fd0SSam Clegg     endSection(SubSection);
979b7787fd0SSam Clegg   }
9809e15f359SSam Clegg 
9816c899ba6SSam Clegg   if (DataSegments.size()) {
98263ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9836c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9846c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
985d95ed959SSam Clegg       writeString(Segment.Name);
98663ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
98763ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
98863ebb813SSam Clegg     }
989d95ed959SSam Clegg     endSection(SubSection);
990d95ed959SSam Clegg   }
991d95ed959SSam Clegg 
992bafe6902SSam Clegg   if (!InitFuncs.empty()) {
993bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
994bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
995bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
996bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
997bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
998bafe6902SSam Clegg     }
999bafe6902SSam Clegg     endSection(SubSection);
1000bafe6902SSam Clegg   }
1001bafe6902SSam Clegg 
1002ea7caceeSSam Clegg   if (Comdats.size()) {
1003ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1004ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
1005ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1006ea7caceeSSam Clegg       writeString(C.first);
1007ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
1008ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
1009ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1010ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
1011ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
1012ea7caceeSSam Clegg       }
1013ea7caceeSSam Clegg     }
1014ea7caceeSSam Clegg     endSection(SubSection);
1015ea7caceeSSam Clegg   }
1016ea7caceeSSam Clegg 
10179e15f359SSam Clegg   endSection(Section);
10189e15f359SSam Clegg }
10199e15f359SSam Clegg 
10206a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10216a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10226a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1023cfd44a2eSSam Clegg     SectionBookkeeping Section;
10246a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10252322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10266a31a0d6SSam Clegg 
10276a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10286a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10296a31a0d6SSam Clegg 
10306a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10316a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10326a31a0d6SSam Clegg 
1033cfd44a2eSSam Clegg     endSection(Section);
10346a31a0d6SSam Clegg 
10356a31a0d6SSam Clegg     // Apply fixups.
10364d57fbd0SSam Clegg     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10374d57fbd0SSam Clegg     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10386a31a0d6SSam Clegg   }
10396a31a0d6SSam Clegg }
10406a31a0d6SSam Clegg 
10415e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10425e3d33a7SSam Clegg   assert(Symbol.isFunction());
10435e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10445e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10455e3d33a7SSam Clegg }
10465e3d33a7SSam Clegg 
10475e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10485e3d33a7SSam Clegg   assert(Symbol.isFunction());
10495e3d33a7SSam Clegg 
10505e3d33a7SSam Clegg   WasmFunctionType F;
1051aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10525e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10535e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10545e3d33a7SSam Clegg 
10555e3d33a7SSam Clegg   auto Pair =
10565e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10575e3d33a7SSam Clegg   if (Pair.second)
10585e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10595e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10605e3d33a7SSam Clegg 
10615e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
10625e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10635e3d33a7SSam Clegg   return Pair.first->second;
10645e3d33a7SSam Clegg }
10655e3d33a7SSam Clegg 
10664d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
10674d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
10684d57fbd0SSam Clegg     return true;
10694d57fbd0SSam Clegg 
10704d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
10714d57fbd0SSam Clegg     return false;
10724d57fbd0SSam Clegg 
10734d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
10744d57fbd0SSam Clegg     return false;
10754d57fbd0SSam Clegg 
10764d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
10774d57fbd0SSam Clegg     return false;
10784d57fbd0SSam Clegg 
10794d57fbd0SSam Clegg   if (Sym.isSection())
10804d57fbd0SSam Clegg     return false;
10814d57fbd0SSam Clegg 
10824d57fbd0SSam Clegg   return true;
10834d57fbd0SSam Clegg }
10844d57fbd0SSam Clegg 
108518eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
108618eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1087b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
108882607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1089d934cb88SDan Gohman 
1090d934cb88SDan Gohman   // Collect information from the available symbols.
1091d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1092d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
10938defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
10948defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
10956c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1096bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1097ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
10987c395943SSam Clegg   uint32_t DataSize = 0;
1099d934cb88SDan Gohman 
1100f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1101f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1102f950b24aSSam Clegg   // it if there are no loads or stores.
1103f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1104f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11058defa952SSam Clegg   wasm::WasmImport MemImport;
11068defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11078defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1108f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1109f950b24aSSam Clegg   Imports.push_back(MemImport);
1110f950b24aSSam Clegg 
1111f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1112f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1113f950b24aSSam Clegg   // it if there are no indirect calls.
1114f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1115f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11168defa952SSam Clegg   wasm::WasmImport TableImport;
11178defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11188defa952SSam Clegg   TableImport.Field = TableSym->getName();
1119f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11208defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1121f950b24aSSam Clegg   Imports.push_back(TableImport);
1122f950b24aSSam Clegg 
1123586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1124586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1125586320c0SNicholas Wilson   // symbols.
112632ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
112732ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
112832ce5ca0SDan Gohman 
112932ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11309f3fe42eSSam Clegg     // (because wasm always needs a type signature).
113132ce5ca0SDan Gohman     if (WS.isFunction())
113232ce5ca0SDan Gohman       registerFunctionType(WS);
113332ce5ca0SDan Gohman 
113432ce5ca0SDan Gohman     if (WS.isTemporary())
113532ce5ca0SDan Gohman       continue;
113632ce5ca0SDan Gohman 
113732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11386c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11396c899ba6SSam Clegg       if (WS.isFunction()) {
11408defa952SSam Clegg         wasm::WasmImport Import;
11418defa952SSam Clegg         Import.Module = WS.getModuleName();
11428defa952SSam Clegg         Import.Field = WS.getName();
114332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11448defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11456c899ba6SSam Clegg         Imports.push_back(Import);
11466c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11476c899ba6SSam Clegg       } else if (WS.isGlobal()) {
114815f349f7SNicholas Wilson         if (WS.isWeak())
114915f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
115015f349f7SNicholas Wilson 
11516c899ba6SSam Clegg         wasm::WasmImport Import;
11526c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11536c899ba6SSam Clegg         Import.Field = WS.getName();
115432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11556c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11566c899ba6SSam Clegg         Imports.push_back(Import);
11576c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
115832ce5ca0SDan Gohman       }
115932ce5ca0SDan Gohman     }
116032ce5ca0SDan Gohman   }
116132ce5ca0SDan Gohman 
11624d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
11634d57fbd0SSam Clegg   // populating DataLocations.
1164759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1165759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
11664d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1167759631c7SSam Clegg 
1168bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
11694d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1170bafe6902SSam Clegg       continue;
1171bafe6902SSam Clegg 
11724d57fbd0SSam Clegg     // Code is handled separately
11734d57fbd0SSam Clegg     if (Section.getKind().isText())
11744d57fbd0SSam Clegg       continue;
11754d57fbd0SSam Clegg 
11764d57fbd0SSam Clegg     if (Section.isWasmData()) {
1177329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1178759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1179759631c7SSam Clegg       DataSegments.emplace_back();
1180759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
11814d57fbd0SSam Clegg       Segment.Name = SectionName;
1182759631c7SSam Clegg       Segment.Offset = DataSize;
1183759631c7SSam Clegg       Segment.Section = &Section;
118463ebb813SSam Clegg       addData(Segment.Data, Section);
118563ebb813SSam Clegg       Segment.Alignment = Section.getAlignment();
118663ebb813SSam Clegg       Segment.Flags = 0;
1187759631c7SSam Clegg       DataSize += Segment.Data.size();
11886c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1189ea7caceeSSam Clegg 
1190ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1191ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1192329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1193ea7caceeSSam Clegg       }
11944d57fbd0SSam Clegg     } else {
11954d57fbd0SSam Clegg       // Create custom sections
11964d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
11974d57fbd0SSam Clegg 
11984d57fbd0SSam Clegg       StringRef Name = SectionName;
11994d57fbd0SSam Clegg 
12004d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12014d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12024d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
12034d57fbd0SSam Clegg 
12044d57fbd0SSam Clegg       MCSymbol* Begin = Sec.getBeginSymbol();
1205fb807d4dSSam Clegg       if (Begin) {
12064d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1207*b210c64bSSam Clegg         if (SectionName != Begin->getName())
1208fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1209*b210c64bSSam Clegg                              Twine(SectionName));
1210fb807d4dSSam Clegg       }
12114d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1212759631c7SSam Clegg     }
12136a31a0d6SSam Clegg   }
12146a31a0d6SSam Clegg 
1215586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1216d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1217d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1218d934cb88SDan Gohman     // or used in relocations.
1219d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1220d934cb88SDan Gohman       continue;
1221b7787fd0SSam Clegg 
1222d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1223a165f2d6SSam Clegg     DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1224a165f2d6SSam Clegg                  << " '" << S << "'"
1225329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1226329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1227329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1228b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1229a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1230b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1231b7787fd0SSam Clegg 
12325e3d33a7SSam Clegg     if (WS.isVariable())
12335e3d33a7SSam Clegg       continue;
12346c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12356c899ba6SSam Clegg       continue;
1236b7787fd0SSam Clegg 
1237d934cb88SDan Gohman     if (WS.isFunction()) {
12386c899ba6SSam Clegg       unsigned Index;
1239cd65f698SSam Clegg       if (WS.isDefined()) {
1240b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1241b7787fd0SSam Clegg           report_fatal_error(
1242b7787fd0SSam Clegg               "function sections must contain one function each");
1243b7787fd0SSam Clegg 
1244b7787fd0SSam Clegg         if (WS.getSize() == 0)
1245b7787fd0SSam Clegg           report_fatal_error(
1246b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1247b7787fd0SSam Clegg 
12486c899ba6SSam Clegg         // A definition. Write out the function body.
12499f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1250d934cb88SDan Gohman         WasmFunction Func;
12515e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1252d934cb88SDan Gohman         Func.Sym = &WS;
12536c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1254d934cb88SDan Gohman         Functions.push_back(Func);
12556c899ba6SSam Clegg 
12566c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12576c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12586c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12596c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12606c899ba6SSam Clegg         }
1261d934cb88SDan Gohman       } else {
1262d934cb88SDan Gohman         // An import; the index was assigned above.
12636c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1264d934cb88SDan Gohman       }
1265d934cb88SDan Gohman 
12665e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
12676c899ba6SSam Clegg     } else if (WS.isData()) {
1268c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1269c38e947eSSam Clegg         continue;
1270c38e947eSSam Clegg 
12716c899ba6SSam Clegg       if (!WS.isDefined()) {
1272a165f2d6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1" << "\n");
1273fe6414b0SSam Clegg         continue;
12746c899ba6SSam Clegg       }
1275fe6414b0SSam Clegg 
1276d934cb88SDan Gohman       if (!WS.getSize())
1277c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1278c38e947eSSam Clegg                            WS.getName());
1279d934cb88SDan Gohman 
1280d934cb88SDan Gohman       int64_t Size = 0;
1281d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1282d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1283d934cb88SDan Gohman 
1284759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1285ea7caceeSSam Clegg       assert(DataSection.isWasmData());
12867c395943SSam Clegg 
12876c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
12886c899ba6SSam Clegg       // corresponding Wasm data segment.
12896c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
12906c899ba6SSam Clegg           DataSection.getSegmentIndex(),
12916c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
12926c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
12936c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1294a165f2d6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1295a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
12966c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1297545932beSEric Christopher       if (WS.isDefined())
12986c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
12996c899ba6SSam Clegg 
1300545932beSEric Christopher       // An import; the index was assigned above
1301545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1302545932beSEric Christopher                    << "\n");
1303a165f2d6SSam Clegg     } else {
1304a165f2d6SSam Clegg       assert(WS.isSection());
1305d934cb88SDan Gohman     }
1306d934cb88SDan Gohman   }
1307d934cb88SDan Gohman 
1308586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1309586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1310586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1311586320c0SNicholas Wilson   // necessarily ordered in this way.
1312b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1313b7787fd0SSam Clegg     if (!S.isVariable())
1314b7787fd0SSam Clegg       continue;
131531a2c809SSam Clegg 
1316cd65f698SSam Clegg     assert(S.isDefined());
1317b7787fd0SSam Clegg 
13185e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1319aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1320aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
13215e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1322b7787fd0SSam Clegg 
13236c899ba6SSam Clegg     if (WS.isFunction()) {
13246c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13256c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13266c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
13276c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13286c899ba6SSam Clegg     } else if (WS.isData()) {
13296c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13306c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13316c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13326c899ba6SSam Clegg       DataLocations[&WS] = Ref;
13336c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13346c899ba6SSam Clegg     } else {
13356c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13366c899ba6SSam Clegg     }
1337586320c0SNicholas Wilson   }
133831a2c809SSam Clegg 
1339586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1340586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1341586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
134225d8e68bSSam Clegg     if (!isInSymtab(WS)) {
134325d8e68bSSam Clegg       WS.setIndex(INVALID_INDEX);
1344586320c0SNicholas Wilson       continue;
134525d8e68bSSam Clegg     }
13464d57fbd0SSam Clegg     DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1347586320c0SNicholas Wilson 
1348586320c0SNicholas Wilson     uint32_t Flags = 0;
1349586320c0SNicholas Wilson     if (WS.isWeak())
1350586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1351586320c0SNicholas Wilson     if (WS.isHidden())
1352586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1353586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1354586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1355586320c0SNicholas Wilson     if (WS.isUndefined())
1356586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1357586320c0SNicholas Wilson 
1358586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1359586320c0SNicholas Wilson     Info.Name = WS.getName();
1360586320c0SNicholas Wilson     Info.Kind = WS.getType();
1361586320c0SNicholas Wilson     Info.Flags = Flags;
13624d57fbd0SSam Clegg     if (!WS.isData()) {
13634d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1364586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
13654d57fbd0SSam Clegg     } else if (WS.isDefined()) {
13664d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1367586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
13684d57fbd0SSam Clegg     }
136925d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1370586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1371b7787fd0SSam Clegg   }
1372b7787fd0SSam Clegg 
13736006e091SSam Clegg   {
13746006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1375f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1376f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1377f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1378f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1379f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1380f9edbe95SSam Clegg         return;
1381f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1382f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
13836c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1384f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1385f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1386329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1387f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
13886c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
13896006e091SSam Clegg         registerFunctionType(WS);
13906006e091SSam Clegg       }
13916006e091SSam Clegg     };
1392970d02c4SDan Gohman 
13936006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
13946006e091SSam Clegg       HandleReloc(RelEntry);
13956006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
13966006e091SSam Clegg       HandleReloc(RelEntry);
1397d934cb88SDan Gohman   }
1398d934cb88SDan Gohman 
1399bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1400bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1401bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1402bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1403bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1404bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1405bafe6902SSam Clegg       continue;
1406bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1407bafe6902SSam Clegg       continue;
1408*b210c64bSSam Clegg 
1409*b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1410*b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1411bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1412*b210c64bSSam Clegg 
1413*b210c64bSSam Clegg     auto IT = WS.begin();
1414*b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1415*b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1416*b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1417*b210c64bSSam Clegg 
1418*b210c64bSSam Clegg     IT = std::next(IT);
1419*b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1420bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1421bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1422bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1423bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1424*b210c64bSSam Clegg 
1425*b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1426bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1427bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1428*b210c64bSSam Clegg 
1429bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
14304d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
14314d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
14324d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1433bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
14344d57fbd0SSam Clegg       if (WS.getSectionName()
14354d57fbd0SSam Clegg               .substr(PrefixLength + 1)
14364d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1437bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1438bafe6902SSam Clegg     }
1439bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1440bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1441bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1442bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1443bafe6902SSam Clegg          p != end; ++p) {
1444bafe6902SSam Clegg       if (*p != 0)
1445bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1446bafe6902SSam Clegg     }
1447bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1448bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1449bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1450bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1451bafe6902SSam Clegg       if (!Sym)
1452bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1453bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1454bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
145525d8e68bSSam Clegg       if (Sym->getSymbol().getIndex() == INVALID_INDEX)
145625d8e68bSSam Clegg         report_fatal_error("symbols in .init_array should exist in symbtab");
145725d8e68bSSam Clegg       InitFuncs.push_back(
145825d8e68bSSam Clegg           std::make_pair(Priority, Sym->getSymbol().getIndex()));
1459bafe6902SSam Clegg     }
1460bafe6902SSam Clegg   }
1461bafe6902SSam Clegg 
146218eafb6cSDan Gohman   // Write out the Wasm header.
146318eafb6cSDan Gohman   writeHeader(Asm);
146418eafb6cSDan Gohman 
14659e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1466f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14679e15f359SSam Clegg   writeFunctionSection(Functions);
1468f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1469f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14707c395943SSam Clegg   writeGlobalSection();
14719e15f359SSam Clegg   writeExportSection(Exports);
14729e15f359SSam Clegg   writeElemSection(TableElems);
1473acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14746c899ba6SSam Clegg   writeDataSection();
14756a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
1476c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
14776f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
14786f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
14796a31a0d6SSam Clegg   writeCustomRelocSections();
1480970d02c4SDan Gohman 
1481d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
148218eafb6cSDan Gohman }
148318eafb6cSDan Gohman 
148460fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
14851301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
148618eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
14870917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
148818eafb6cSDan Gohman }
1489