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 
40*a165f2d6SSam Clegg static std::string toString(wasm::WasmSymbolType type) {
41*a165f2d6SSam Clegg   switch (type) {
42*a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
43*a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_FUNCTION";
44*a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
45*a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_GLOBAL";
46*a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_DATA:
47*a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_DATA";
48*a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_SECTION:
49*a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_SECTION";
50*a165f2d6SSam Clegg   }
51*a165f2d6SSam Clegg }
52*a165f2d6SSam Clegg 
53*a165f2d6SSam Clegg static std::string relocTypetoString(uint32_t type) {
54*a165f2d6SSam Clegg   switch (type) {
55*a165f2d6SSam Clegg #define WASM_RELOC(NAME, VALUE) case VALUE: return #NAME;
56*a165f2d6SSam Clegg #include "llvm/BinaryFormat/WasmRelocs.def"
57*a165f2d6SSam Clegg #undef WASM_RELOC
58*a165f2d6SSam Clegg   default:
59*a165f2d6SSam Clegg     llvm_unreachable("uknown reloc type");
60*a165f2d6SSam Clegg   }
61*a165f2d6SSam Clegg }
62*a165f2d6SSam Clegg 
6318eafb6cSDan Gohman namespace {
649e15f359SSam Clegg 
6530e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
6630e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
6730e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
6830e1bbc1SSam Clegg 
69d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
70d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
71d934cb88SDan Gohman // locations within the section.
72d934cb88SDan Gohman struct SectionBookkeeping {
73d934cb88SDan Gohman   // Where the size of the section is written.
74d934cb88SDan Gohman   uint64_t SizeOffset;
756a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
766a31a0d6SSam Clegg   uint64_t PayloadOffset;
776a31a0d6SSam Clegg   // Where the contents of the section starts.
78d934cb88SDan Gohman   uint64_t ContentsOffset;
796f08c84aSSam Clegg   uint32_t Index;
80d934cb88SDan Gohman };
81d934cb88SDan Gohman 
829e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
839e15f359SSam Clegg // DenseMap key.
849e15f359SSam Clegg struct WasmFunctionType {
859e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
869e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
879e15f359SSam Clegg 
889e15f359SSam Clegg   // The return types of the function.
899e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
909e15f359SSam Clegg 
919e15f359SSam Clegg   // The parameter types of the function.
929e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
939e15f359SSam Clegg 
949e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
959e15f359SSam Clegg 
969e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
979e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
989e15f359SSam Clegg            Params == Other.Params;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg };
1019e15f359SSam Clegg 
1029e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
1039e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
1049e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
1059e15f359SSam Clegg     WasmFunctionType FuncTy;
1069e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
1079e15f359SSam Clegg     return FuncTy;
1089e15f359SSam Clegg   }
1099e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
1109e15f359SSam Clegg     WasmFunctionType FuncTy;
1119e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
1129e15f359SSam Clegg     return FuncTy;
1139e15f359SSam Clegg   }
1149e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
1159e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
1169e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
1179e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
1189e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
1199e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
1209e15f359SSam Clegg     return Value;
1219e15f359SSam Clegg   }
1229e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1239e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1249e15f359SSam Clegg     return LHS == RHS;
1259e15f359SSam Clegg   }
1269e15f359SSam Clegg };
1279e15f359SSam Clegg 
1287c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1297c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1307c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1317c395943SSam Clegg // wasm data segment.
1327c395943SSam Clegg struct WasmDataSegment {
1337c395943SSam Clegg   MCSectionWasm *Section;
134d95ed959SSam Clegg   StringRef Name;
1357c395943SSam Clegg   uint32_t Offset;
13663ebb813SSam Clegg   uint32_t Alignment;
13763ebb813SSam Clegg   uint32_t Flags;
1387c395943SSam Clegg   SmallVector<char, 4> Data;
1397c395943SSam Clegg };
1407c395943SSam Clegg 
1419e15f359SSam Clegg // A wasm function to be written into the function section.
1429e15f359SSam Clegg struct WasmFunction {
1439e15f359SSam Clegg   int32_t Type;
1449e15f359SSam Clegg   const MCSymbolWasm *Sym;
1459e15f359SSam Clegg };
1469e15f359SSam Clegg 
1479e15f359SSam Clegg // A wasm global to be written into the global section.
1489e15f359SSam Clegg struct WasmGlobal {
1496e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1509e15f359SSam Clegg   uint64_t InitialValue;
1519e15f359SSam Clegg };
1529e15f359SSam Clegg 
153ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
154ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
155ea7caceeSSam Clegg // WasmComdatEntry.
156ea7caceeSSam Clegg struct WasmComdatEntry {
157ea7caceeSSam Clegg   unsigned Kind;
158ea7caceeSSam Clegg   uint32_t Index;
159ea7caceeSSam Clegg };
160ea7caceeSSam Clegg 
1616dc65e91SSam Clegg // Information about a single relocation.
1626dc65e91SSam Clegg struct WasmRelocationEntry {
1636dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1646dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1656dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1666dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
167fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1686dc65e91SSam Clegg 
1696dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1706dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
171fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1726dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1736dc65e91SSam Clegg         FixupSection(FixupSection) {}
1746dc65e91SSam Clegg 
175acd7d2b0SSam Clegg   bool hasAddend() const {
176acd7d2b0SSam Clegg     switch (Type) {
17713a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
17813a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
17913a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1806a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1816a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
182acd7d2b0SSam Clegg       return true;
183acd7d2b0SSam Clegg     default:
184acd7d2b0SSam Clegg       return false;
185acd7d2b0SSam Clegg     }
186acd7d2b0SSam Clegg   }
187acd7d2b0SSam Clegg 
1886dc65e91SSam Clegg   void print(raw_ostream &Out) const {
189*a165f2d6SSam Clegg     Out << relocTypetoString(Type)
190*a165f2d6SSam Clegg         << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
191759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1926dc65e91SSam Clegg   }
193b7787fd0SSam Clegg 
194615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
195b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
196b7787fd0SSam Clegg #endif
1976dc65e91SSam Clegg };
1986dc65e91SSam Clegg 
199cfd44a2eSSam Clegg struct WasmCustomSection {
2006a31a0d6SSam Clegg   const uint32_t INVALID_INDEX = -1;
201cfd44a2eSSam Clegg 
2026a31a0d6SSam Clegg   StringRef Name;
2036a31a0d6SSam Clegg   MCSectionWasm *Section;
2046a31a0d6SSam Clegg 
2056a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
2066a31a0d6SSam Clegg   uint32_t OutputIndex;
2076a31a0d6SSam Clegg 
2086a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
2096a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
2106a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
211cfd44a2eSSam Clegg };
212cfd44a2eSSam Clegg 
2131fb8daa6SSam Clegg #if !defined(NDEBUG)
2147f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
215b7787fd0SSam Clegg   Rel.print(OS);
216b7787fd0SSam Clegg   return OS;
217b7787fd0SSam Clegg }
2181fb8daa6SSam Clegg #endif
219b7787fd0SSam Clegg 
22018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
22118eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22218eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22318eafb6cSDan Gohman 
224d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
225d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2266f08c84aSSam Clegg   uint32_t CodeSectionIndex;
227d934cb88SDan Gohman 
228d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
229d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2306f08c84aSSam Clegg   uint32_t DataSectionIndex;
231d934cb88SDan Gohman 
232d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
233acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
234acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
235d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
236d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
237f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2386c899ba6SSam Clegg   // Maps function/global symbols to the (shared) Symbol index space.
239acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
240*a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2416c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2426c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2436c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2446a31a0d6SSam Clegg   // Maps section symbols to the section.
2456a31a0d6SSam Clegg   DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols;
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();
286acd7d2b0SSam Clegg     SymbolIndices.clear();
2876c899ba6SSam Clegg     WasmIndices.clear();
288f9edbe95SSam Clegg     TableIndices.clear();
2896c899ba6SSam Clegg     DataLocations.clear();
2906a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
291acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2925e3d33a7SSam Clegg     FunctionTypes.clear();
2937c395943SSam Clegg     Globals.clear();
2946c899ba6SSam Clegg     DataSegments.clear();
2956a31a0d6SSam Clegg     CustomSectionSymbols.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 
4336a31a0d6SSam Clegg   // TODO: Add support for non-debug metadata sections?
4346a31a0d6SSam Clegg   if (FixupSection.getKind().isMetadata() &&
4356a31a0d6SSam Clegg       !FixupSection.getSectionName().startswith(".debug_"))
436b7a5469cSSam Clegg     return;
437b7a5469cSSam Clegg 
438d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
439d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
440d934cb88SDan Gohman            "Should not have constructed this");
441d934cb88SDan Gohman 
442d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
443d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
444d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
445d934cb88SDan Gohman 
446d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
447d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
448d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
449d934cb88SDan Gohman     if (IsPCRel) {
450d934cb88SDan Gohman       Ctx.reportError(
451d934cb88SDan Gohman           Fixup.getLoc(),
452d934cb88SDan Gohman           "No relocation available to represent this relative expression");
453d934cb88SDan Gohman       return;
454d934cb88SDan Gohman     }
455d934cb88SDan Gohman 
456d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
457d934cb88SDan Gohman 
458d934cb88SDan Gohman     if (SymB.isUndefined()) {
459d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
460d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
461d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
462d934cb88SDan Gohman       return;
463d934cb88SDan Gohman     }
464d934cb88SDan Gohman 
465d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
466d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
467d934cb88SDan Gohman     if (&SecB != &FixupSection) {
468d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
469d934cb88SDan Gohman                       "Cannot represent a difference across sections");
470d934cb88SDan Gohman       return;
471d934cb88SDan Gohman     }
472d934cb88SDan Gohman 
473d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
474d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
475d934cb88SDan Gohman     IsPCRel = true;
476d934cb88SDan Gohman     C -= K;
477d934cb88SDan Gohman   }
478d934cb88SDan Gohman 
479d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
480d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
481d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
482d934cb88SDan Gohman 
483d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
484d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4856ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4866ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4876ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
488d934cb88SDan Gohman   }
489d934cb88SDan Gohman 
490d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
491d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
492d934cb88SDan Gohman   // be negative and don't wrap.
493d934cb88SDan Gohman   FixedValue = 0;
494d934cb88SDan Gohman 
4956ad8f190SSam Clegg   if (SymA)
496d934cb88SDan Gohman     SymA->setUsedInReloc();
497d934cb88SDan Gohman 
498ae03c1e7SSam Clegg   assert(!IsPCRel);
4999d24fb7fSSam Clegg   assert(SymA);
5009d24fb7fSSam Clegg 
501ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
502ae03c1e7SSam Clegg 
503d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
504b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
505d934cb88SDan Gohman 
5066a31a0d6SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB,
5076a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32
5086a31a0d6SSam Clegg   // are currently required to be against a named symbol.
509b7a5469cSSam Clegg   // TODO(sbc): Add support for relocations against unnamed temporaries such
510b7a5469cSSam Clegg   // as those generated by llvm's `blockaddress`.
511b7a5469cSSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
5126a31a0d6SSam Clegg   if (SymA->getName().empty() &&
5136a31a0d6SSam Clegg       !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB ||
5146a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
5156a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32))
516b7a5469cSSam Clegg     report_fatal_error("relocations against un-named temporaries are not yet "
517b7a5469cSSam Clegg                        "supported by wasm");
518b7a5469cSSam Clegg 
5196a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
520d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5216a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
52212fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5236a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5246a31a0d6SSam Clegg     assert(FixupSection.getSectionName().startswith(".debug_"));
5256a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5266a31a0d6SSam Clegg   } else {
52712fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
528d934cb88SDan Gohman   }
5296a31a0d6SSam Clegg }
530d934cb88SDan Gohman 
531d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
532d934cb88SDan Gohman // to allow patching.
533d934cb88SDan Gohman static void
534d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
535d934cb88SDan Gohman   uint8_t Buffer[5];
53666a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
537d934cb88SDan Gohman   assert(SizeLen == 5);
538d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
539d934cb88SDan Gohman }
540d934cb88SDan Gohman 
541d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
542d934cb88SDan Gohman // to allow patching.
543d934cb88SDan Gohman static void
544d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
545d934cb88SDan Gohman   uint8_t Buffer[5];
54666a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
547d934cb88SDan Gohman   assert(SizeLen == 5);
548d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
549d934cb88SDan Gohman }
550d934cb88SDan Gohman 
551d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
552d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
553d934cb88SDan Gohman   uint8_t Buffer[4];
554d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
555d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
556d934cb88SDan Gohman }
557d934cb88SDan Gohman 
558aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
559aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
560aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
561aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
562aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
563aff1c4dfSSam Clegg   }
564aff1c4dfSSam Clegg   return &Symbol;
565aff1c4dfSSam Clegg }
566aff1c4dfSSam Clegg 
567d934cb88SDan Gohman // Compute a value to write into the code at the location covered
56860ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
56960ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57060ec3034SSam Clegg // useable.
5717c395943SSam Clegg uint32_t
5727c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
57360ec3034SSam Clegg   switch (RelEntry.Type) {
57460ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
575f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
576f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
577f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
578f9edbe95SSam Clegg     assert(Sym->isFunction());
579f9edbe95SSam Clegg     return TableIndices[Sym];
580f9edbe95SSam Clegg   }
58160ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5826c899ba6SSam Clegg     // Provisional value is same as the index
58360ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5846c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5856c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5866c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5876c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5886c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5896c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5906c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5916a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
5926a31a0d6SSam Clegg     const auto &Section =
5936a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5946a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5956a31a0d6SSam Clegg   }
5966a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
5976a31a0d6SSam Clegg     const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second;
5986a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5996a31a0d6SSam Clegg   }
60060ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
60160ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
60260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
603f9edbe95SSam Clegg     // Provisional value is address of the global
60460ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
605270ed1b3SSam Clegg     // For undefined symbols, use zero
606cd65f698SSam Clegg     if (!Sym->isDefined())
607270ed1b3SSam Clegg       return 0;
6086c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6096c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
610d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6116c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61260ec3034SSam Clegg   }
61360ec3034SSam Clegg   default:
61460ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61560ec3034SSam Clegg   }
616d934cb88SDan Gohman }
617d934cb88SDan Gohman 
618759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
61963ebb813SSam Clegg                     MCSectionWasm &DataSection) {
620759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
621759631c7SSam Clegg 
62263ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62363ebb813SSam Clegg 
624759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
625759631c7SSam Clegg     if (Frag.hasInstructions())
626759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
627759631c7SSam Clegg 
628759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
629759631c7SSam Clegg       if (Align->getValueSize() != 1)
630759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
631759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
632759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
633759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
634759631c7SSam Clegg                                                  Align->getAlignment()),
635759631c7SSam Clegg                                          DataBytes.size() +
636759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
637759631c7SSam Clegg       DataBytes.resize(Size, Value);
638759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
639d707c370SRafael Espindola       int64_t Size;
640d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
641d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
642d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
643759631c7SSam Clegg     } else {
644759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
645759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
646759631c7SSam Clegg 
647759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
648759631c7SSam Clegg     }
649759631c7SSam Clegg   }
650759631c7SSam Clegg 
651759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
652759631c7SSam Clegg }
653759631c7SSam Clegg 
65460ec3034SSam Clegg uint32_t
65560ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
65660ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
657b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
658b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
659b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
660acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
661acd7d2b0SSam Clegg   }
66260ec3034SSam Clegg 
66360ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
6646c899ba6SSam Clegg     report_fatal_error("symbol not found in symbol index space: " +
66560ec3034SSam Clegg                        RelEntry.Symbol->getName());
66660ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
667acd7d2b0SSam Clegg }
668acd7d2b0SSam Clegg 
669d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
670d934cb88SDan Gohman // directly.
671acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
672acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
673acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
674d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
675d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
676d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
677d934cb88SDan Gohman                       RelEntry.Offset;
678d934cb88SDan Gohman 
679b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68060ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68160ec3034SSam Clegg 
682acd7d2b0SSam Clegg     switch (RelEntry.Type) {
683acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6849d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
68560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
68660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
687d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
688d934cb88SDan Gohman       break;
68960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
69060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6916a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6926a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
693d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
694d934cb88SDan Gohman       break;
69560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
69660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
69760ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
69860ec3034SSam Clegg       break;
699d934cb88SDan Gohman     default:
7009d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
701d934cb88SDan Gohman     }
702d934cb88SDan Gohman   }
70318eafb6cSDan Gohman }
70418eafb6cSDan Gohman 
7059e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
706457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7079e15f359SSam Clegg   if (FunctionTypes.empty())
7089e15f359SSam Clegg     return;
7099e15f359SSam Clegg 
7109e15f359SSam Clegg   SectionBookkeeping Section;
7119e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7129e15f359SSam Clegg 
7139e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
7149e15f359SSam Clegg 
7159e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
71603e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
7179e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
7189e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7199e15f359SSam Clegg       writeValueType(Ty);
7209e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
7219e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7229e15f359SSam Clegg       writeValueType(Ty);
7239e15f359SSam Clegg   }
7249e15f359SSam Clegg 
7259e15f359SSam Clegg   endSection(Section);
7269e15f359SSam Clegg }
7279e15f359SSam Clegg 
7288defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
729f950b24aSSam Clegg                                           uint32_t DataSize,
730f950b24aSSam Clegg                                           uint32_t NumElements) {
7319e15f359SSam Clegg   if (Imports.empty())
7329e15f359SSam Clegg     return;
7339e15f359SSam Clegg 
734f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
735f950b24aSSam Clegg 
7369e15f359SSam Clegg   SectionBookkeeping Section;
7379e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7389e15f359SSam Clegg 
7399e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7408defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7418defa952SSam Clegg     writeString(Import.Module);
7428defa952SSam Clegg     writeString(Import.Field);
74303e101f1SSam Clegg     write8(Import.Kind);
7449e15f359SSam Clegg 
7459e15f359SSam Clegg     switch (Import.Kind) {
7469e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7478defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7489e15f359SSam Clegg       break;
7499e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
75003e101f1SSam Clegg       write8(Import.Global.Type);
75103e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7529e15f359SSam Clegg       break;
753f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
754f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
755f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
756f950b24aSSam Clegg       break;
757f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
75803e101f1SSam Clegg       write8(Import.Table.ElemType);
759f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
760f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
761f950b24aSSam Clegg       break;
7629e15f359SSam Clegg     default:
7639e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7649e15f359SSam Clegg     }
7659e15f359SSam Clegg   }
7669e15f359SSam Clegg 
7679e15f359SSam Clegg   endSection(Section);
7689e15f359SSam Clegg }
7699e15f359SSam Clegg 
770457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7719e15f359SSam Clegg   if (Functions.empty())
7729e15f359SSam Clegg     return;
7739e15f359SSam Clegg 
7749e15f359SSam Clegg   SectionBookkeeping Section;
7759e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7769e15f359SSam Clegg 
7779e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7789e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7799e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7809e15f359SSam Clegg 
7819e15f359SSam Clegg   endSection(Section);
7829e15f359SSam Clegg }
7839e15f359SSam Clegg 
7847c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7859e15f359SSam Clegg   if (Globals.empty())
7869e15f359SSam Clegg     return;
7879e15f359SSam Clegg 
7889e15f359SSam Clegg   SectionBookkeeping Section;
7899e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7909e15f359SSam Clegg 
7919e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7929e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7936e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7946e7f1826SSam Clegg     write8(Global.Type.Mutable);
7959e15f359SSam Clegg 
7969e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7976e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7989e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7999e15f359SSam Clegg   }
8009e15f359SSam Clegg 
8019e15f359SSam Clegg   endSection(Section);
8029e15f359SSam Clegg }
8039e15f359SSam Clegg 
8048defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8059e15f359SSam Clegg   if (Exports.empty())
8069e15f359SSam Clegg     return;
8079e15f359SSam Clegg 
8089e15f359SSam Clegg   SectionBookkeeping Section;
8099e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8109e15f359SSam Clegg 
8119e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
8128defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8138defa952SSam Clegg     writeString(Export.Name);
81403e101f1SSam Clegg     write8(Export.Kind);
8159e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
8169e15f359SSam Clegg   }
8179e15f359SSam Clegg 
8189e15f359SSam Clegg   endSection(Section);
8199e15f359SSam Clegg }
8209e15f359SSam Clegg 
821457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8229e15f359SSam Clegg   if (TableElems.empty())
8239e15f359SSam Clegg     return;
8249e15f359SSam Clegg 
8259e15f359SSam Clegg   SectionBookkeeping Section;
8269e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8279e15f359SSam Clegg 
8289e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8299e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8309e15f359SSam Clegg 
8319e15f359SSam Clegg   // init expr for starting offset
8329e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
83330e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8349e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8359e15f359SSam Clegg 
8369e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8379e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8389e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8399e15f359SSam Clegg 
8409e15f359SSam Clegg   endSection(Section);
8419e15f359SSam Clegg }
8429e15f359SSam Clegg 
843457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
844457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
845457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8469e15f359SSam Clegg   if (Functions.empty())
8479e15f359SSam Clegg     return;
8489e15f359SSam Clegg 
8499e15f359SSam Clegg   SectionBookkeeping Section;
8509e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8516f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8529e15f359SSam Clegg 
8539e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8549e15f359SSam Clegg 
8559e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
856fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8579e15f359SSam Clegg 
8589e15f359SSam Clegg     int64_t Size = 0;
8599e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8609e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8619e15f359SSam Clegg 
8629e15f359SSam Clegg     encodeULEB128(Size, getStream());
863fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8649e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8659e15f359SSam Clegg   }
8669e15f359SSam Clegg 
8679e15f359SSam Clegg   // Apply fixups.
868acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8699e15f359SSam Clegg 
8709e15f359SSam Clegg   endSection(Section);
8719e15f359SSam Clegg }
8729e15f359SSam Clegg 
8736c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8746c899ba6SSam Clegg   if (DataSegments.empty())
8757c395943SSam Clegg     return;
8769e15f359SSam Clegg 
8779e15f359SSam Clegg   SectionBookkeeping Section;
8789e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8796f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8809e15f359SSam Clegg 
8816c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8827c395943SSam Clegg 
8836c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8849e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8859e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8867c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8879e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8887c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8897c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8907c395943SSam Clegg     writeBytes(Segment.Data); // data
8917c395943SSam Clegg   }
8929e15f359SSam Clegg 
8939e15f359SSam Clegg   // Apply fixups.
8947c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8959e15f359SSam Clegg 
8969e15f359SSam Clegg   endSection(Section);
8979e15f359SSam Clegg }
8989e15f359SSam Clegg 
8996f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9006f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
9016f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
9029e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9039e15f359SSam Clegg   // for descriptions of the reloc sections.
9049e15f359SSam Clegg 
9056f08c84aSSam Clegg   if (Relocations.empty())
9069e15f359SSam Clegg     return;
9079e15f359SSam Clegg 
9089e15f359SSam Clegg   SectionBookkeeping Section;
9096f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9109e15f359SSam Clegg 
9116f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
9129e15f359SSam Clegg 
9136f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
9146f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
9156f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
9166f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
9176f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
9186f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9199e15f359SSam Clegg 
9206f08c84aSSam Clegg     write8(RelEntry.Type);
9216f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
9226f08c84aSSam Clegg     encodeULEB128(Index, Stream);
9236f08c84aSSam Clegg     if (RelEntry.hasAddend())
9246f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9259e15f359SSam Clegg   }
9269e15f359SSam Clegg 
9279e15f359SSam Clegg   endSection(Section);
9289e15f359SSam Clegg }
9299e15f359SSam Clegg 
9306a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9316a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9326a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9336a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9346a31a0d6SSam Clegg   }
9356a31a0d6SSam Clegg }
9366a31a0d6SSam Clegg 
9379e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
93886b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
939ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
940ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9419e15f359SSam Clegg   SectionBookkeeping Section;
9422322a937SSam Clegg   startCustomSection(Section, "linking");
9436bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9449e15f359SSam Clegg 
9456bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9466c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9476c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9486c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9496c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9506c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9516c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9526c899ba6SSam Clegg       switch (Sym.Kind) {
9536c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9546c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9556c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9566c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9576c899ba6SSam Clegg           writeString(Sym.Name);
9586c899ba6SSam Clegg         break;
9596c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9606c899ba6SSam Clegg         writeString(Sym.Name);
9616c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9626c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9636c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9646c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9656c899ba6SSam Clegg         }
9666c899ba6SSam Clegg         break;
9676a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9686a31a0d6SSam Clegg         const uint32_t SectionIndex =
9696a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9706a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9716a31a0d6SSam Clegg         break;
9726a31a0d6SSam Clegg       }
9736c899ba6SSam Clegg       default:
9746c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9756c899ba6SSam Clegg       }
976b7787fd0SSam Clegg     }
977b7787fd0SSam Clegg     endSection(SubSection);
978b7787fd0SSam Clegg   }
9799e15f359SSam Clegg 
9806c899ba6SSam Clegg   if (DataSegments.size()) {
98163ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9826c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9836c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
984d95ed959SSam Clegg       writeString(Segment.Name);
98563ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
98663ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
98763ebb813SSam Clegg     }
988d95ed959SSam Clegg     endSection(SubSection);
989d95ed959SSam Clegg   }
990d95ed959SSam Clegg 
991bafe6902SSam Clegg   if (!InitFuncs.empty()) {
992bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
993bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
994bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
995bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
996bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
997bafe6902SSam Clegg     }
998bafe6902SSam Clegg     endSection(SubSection);
999bafe6902SSam Clegg   }
1000bafe6902SSam Clegg 
1001ea7caceeSSam Clegg   if (Comdats.size()) {
1002ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1003ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
1004ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1005ea7caceeSSam Clegg       writeString(C.first);
1006ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
1007ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
1008ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1009ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
1010ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
1011ea7caceeSSam Clegg       }
1012ea7caceeSSam Clegg     }
1013ea7caceeSSam Clegg     endSection(SubSection);
1014ea7caceeSSam Clegg   }
1015ea7caceeSSam Clegg 
10169e15f359SSam Clegg   endSection(Section);
10179e15f359SSam Clegg }
10189e15f359SSam Clegg 
10196a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10206a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10216a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1022cfd44a2eSSam Clegg     SectionBookkeeping Section;
10236a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10242322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10256a31a0d6SSam Clegg 
10266a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10276a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10286a31a0d6SSam Clegg 
10296a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10306a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10316a31a0d6SSam Clegg 
1032cfd44a2eSSam Clegg     endSection(Section);
1033cfd44a2eSSam Clegg   }
1034cfd44a2eSSam Clegg }
1035cfd44a2eSSam Clegg 
10366a31a0d6SSam Clegg void WasmObjectWriter::updateCustomSectionRelocations(
10376a31a0d6SSam Clegg     const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) {
10386a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols;
10396a31a0d6SSam Clegg   for (const auto &P : CustomSectionSymbols)
10406a31a0d6SSam Clegg     SectionSymbols[P.second] = P.first;
10416a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols;
10426a31a0d6SSam Clegg   for (const auto &FuncInfo : Functions)
10436a31a0d6SSam Clegg     FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym;
10446a31a0d6SSam Clegg 
10456a31a0d6SSam Clegg   // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and
10466a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from
10476a31a0d6SSam Clegg   // the beginning of the function or custom section -- all such relocations
10486a31a0d6SSam Clegg   // target the function or custom section starts.
10496a31a0d6SSam Clegg   for (auto &Section : CustomSections) {
10506a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Section.Section];
10516a31a0d6SSam Clegg     for (WasmRelocationEntry &RelEntry : Relocations) {
10526a31a0d6SSam Clegg       switch (RelEntry.Type) {
10536a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
10546a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10556a31a0d6SSam Clegg         auto &Section =
10566a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10576a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10586a31a0d6SSam Clegg         RelEntry.Symbol = FuncSymbols[&Section];
10596a31a0d6SSam Clegg         break;
10606a31a0d6SSam Clegg       }
10616a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
10626a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10636a31a0d6SSam Clegg         auto &Section =
10646a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10656a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10666a31a0d6SSam Clegg         RelEntry.Symbol = SectionSymbols[&Section];
10676a31a0d6SSam Clegg         break;
10686a31a0d6SSam Clegg       }
10696a31a0d6SSam Clegg       default:
10706a31a0d6SSam Clegg         break;
10716a31a0d6SSam Clegg       }
10726a31a0d6SSam Clegg     }
10736a31a0d6SSam Clegg 
10746a31a0d6SSam Clegg     // Apply fixups.
10756a31a0d6SSam Clegg     applyRelocations(Relocations, Section.OutputContentsOffset);
10766a31a0d6SSam Clegg   }
10776a31a0d6SSam Clegg }
10786a31a0d6SSam Clegg 
10795e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10805e3d33a7SSam Clegg   assert(Symbol.isFunction());
10815e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10825e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10835e3d33a7SSam Clegg }
10845e3d33a7SSam Clegg 
10855e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10865e3d33a7SSam Clegg   assert(Symbol.isFunction());
10875e3d33a7SSam Clegg 
10885e3d33a7SSam Clegg   WasmFunctionType F;
1089aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10905e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10915e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10925e3d33a7SSam Clegg 
10935e3d33a7SSam Clegg   auto Pair =
10945e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10955e3d33a7SSam Clegg   if (Pair.second)
10965e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10975e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10985e3d33a7SSam Clegg 
10995e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
11005e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11015e3d33a7SSam Clegg   return Pair.first->second;
11025e3d33a7SSam Clegg }
11035e3d33a7SSam Clegg 
110418eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
110518eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1106b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
110782607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1108d934cb88SDan Gohman 
1109d934cb88SDan Gohman   // Collect information from the available symbols.
1110d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1111d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11128defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11138defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
11146c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1115bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1116ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11177c395943SSam Clegg   uint32_t DataSize = 0;
1118d934cb88SDan Gohman 
1119f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1120f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1121f950b24aSSam Clegg   // it if there are no loads or stores.
1122f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1123f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11248defa952SSam Clegg   wasm::WasmImport MemImport;
11258defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11268defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1127f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1128f950b24aSSam Clegg   Imports.push_back(MemImport);
1129f950b24aSSam Clegg 
1130f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1131f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1132f950b24aSSam Clegg   // it if there are no indirect calls.
1133f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1134f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11358defa952SSam Clegg   wasm::WasmImport TableImport;
11368defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11378defa952SSam Clegg   TableImport.Field = TableSym->getName();
1138f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11398defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1140f950b24aSSam Clegg   Imports.push_back(TableImport);
1141f950b24aSSam Clegg 
1142586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1143586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1144586320c0SNicholas Wilson   // symbols.
114532ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
114632ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
114732ce5ca0SDan Gohman 
114832ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11499f3fe42eSSam Clegg     // (because wasm always needs a type signature).
115032ce5ca0SDan Gohman     if (WS.isFunction())
115132ce5ca0SDan Gohman       registerFunctionType(WS);
115232ce5ca0SDan Gohman 
115332ce5ca0SDan Gohman     if (WS.isTemporary())
115432ce5ca0SDan Gohman       continue;
115532ce5ca0SDan Gohman 
115632ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11576c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11586c899ba6SSam Clegg       if (WS.isFunction()) {
11598defa952SSam Clegg         wasm::WasmImport Import;
11608defa952SSam Clegg         Import.Module = WS.getModuleName();
11618defa952SSam Clegg         Import.Field = WS.getName();
116232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11638defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11646c899ba6SSam Clegg         Imports.push_back(Import);
11656c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11666c899ba6SSam Clegg       } else if (WS.isGlobal()) {
116715f349f7SNicholas Wilson         if (WS.isWeak())
116815f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
116915f349f7SNicholas Wilson 
11706c899ba6SSam Clegg         wasm::WasmImport Import;
11716c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11726c899ba6SSam Clegg         Import.Field = WS.getName();
117332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11746c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11756c899ba6SSam Clegg         Imports.push_back(Import);
11766c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
117732ce5ca0SDan Gohman       }
117832ce5ca0SDan Gohman     }
117932ce5ca0SDan Gohman   }
118032ce5ca0SDan Gohman 
1181586320c0SNicholas Wilson   // Populate DataSegments, which must be done before populating DataLocations.
1182759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1183759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1184cfd44a2eSSam Clegg 
11856a31a0d6SSam Clegg     if (Section.getSectionName().startswith(".custom_section.")) {
1186cfd44a2eSSam Clegg       if (Section.getFragmentList().empty())
1187cfd44a2eSSam Clegg         continue;
1188cfd44a2eSSam Clegg       if (Section.getFragmentList().size() != 1)
1189cfd44a2eSSam Clegg         report_fatal_error(
1190cfd44a2eSSam Clegg             "only one .custom_section section fragment supported");
1191cfd44a2eSSam Clegg       const MCFragment &Frag = *Section.begin();
1192cfd44a2eSSam Clegg       if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1193cfd44a2eSSam Clegg         report_fatal_error("only data supported in .custom_section section");
1194cfd44a2eSSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
1195cfd44a2eSSam Clegg       if (!DataFrag.getFixups().empty())
1196cfd44a2eSSam Clegg         report_fatal_error("fixups not supported in .custom_section section");
1197cfd44a2eSSam Clegg       StringRef UserName = Section.getSectionName().substr(16);
11986a31a0d6SSam Clegg       CustomSections.emplace_back(UserName, &Section);
1199cfd44a2eSSam Clegg       continue;
1200cfd44a2eSSam Clegg     }
1201cfd44a2eSSam Clegg 
120212fd3da9SSam Clegg     if (!Section.isWasmData())
1203759631c7SSam Clegg       continue;
1204759631c7SSam Clegg 
1205bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1206bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1207bafe6902SSam Clegg       continue;
1208bafe6902SSam Clegg 
1209329e76d5SSam Clegg     uint32_t SegmentIndex = DataSegments.size();
1210759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1211759631c7SSam Clegg     DataSegments.emplace_back();
1212759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1213d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1214759631c7SSam Clegg     Segment.Offset = DataSize;
1215759631c7SSam Clegg     Segment.Section = &Section;
121663ebb813SSam Clegg     addData(Segment.Data, Section);
121763ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
121863ebb813SSam Clegg     Segment.Flags = 0;
1219759631c7SSam Clegg     DataSize += Segment.Data.size();
12206c899ba6SSam Clegg     Section.setSegmentIndex(SegmentIndex);
1221ea7caceeSSam Clegg 
1222ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1223ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1224329e76d5SSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1225ea7caceeSSam Clegg     }
1226759631c7SSam Clegg   }
1227759631c7SSam Clegg 
12286a31a0d6SSam Clegg   // Create symbols for debug/custom sections.
12296a31a0d6SSam Clegg   for (MCSection &Sec : Asm) {
12306a31a0d6SSam Clegg     auto &DebugSection = static_cast<MCSectionWasm &>(Sec);
12316a31a0d6SSam Clegg     StringRef SectionName = DebugSection.getSectionName();
12326a31a0d6SSam Clegg 
12336a31a0d6SSam Clegg     // TODO: Add support for non-debug metadata sections?
12346a31a0d6SSam Clegg     if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_"))
12356a31a0d6SSam Clegg       continue;
12366a31a0d6SSam Clegg 
12376a31a0d6SSam Clegg     uint32_t ElementIndex = CustomSections.size();
12386a31a0d6SSam Clegg     CustomSections.emplace_back(SectionName, &DebugSection);
12396a31a0d6SSam Clegg 
12406a31a0d6SSam Clegg     MCSymbolWasm *SectionSym =
12416a31a0d6SSam Clegg         cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName));
12426a31a0d6SSam Clegg     CustomSectionSymbols[SectionSym] = &DebugSection;
12436a31a0d6SSam Clegg 
12446a31a0d6SSam Clegg     wasm::WasmSymbolInfo Info;
12456a31a0d6SSam Clegg     Info.Name = SectionSym->getName();
12466a31a0d6SSam Clegg     Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION;
1247d5504a0aSSam Clegg     Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL;
12486a31a0d6SSam Clegg     Info.ElementIndex = ElementIndex;
12496a31a0d6SSam Clegg     SymbolIndices[SectionSym] = SymbolInfos.size();
12506a31a0d6SSam Clegg     SymbolInfos.emplace_back(Info);
12516a31a0d6SSam Clegg   }
12526a31a0d6SSam Clegg 
1253586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1254d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1255d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1256d934cb88SDan Gohman     // or used in relocations.
1257d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1258d934cb88SDan Gohman       continue;
1259b7787fd0SSam Clegg 
1260d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1261*a165f2d6SSam Clegg     DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1262*a165f2d6SSam Clegg                  << " '" << S << "'"
1263329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1264329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1265329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1266b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1267a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1268b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1269b7787fd0SSam Clegg 
12705e3d33a7SSam Clegg     if (WS.isVariable())
12715e3d33a7SSam Clegg       continue;
12726c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12736c899ba6SSam Clegg       continue;
1274b7787fd0SSam Clegg 
1275d934cb88SDan Gohman     if (WS.isFunction()) {
12766c899ba6SSam Clegg       unsigned Index;
1277cd65f698SSam Clegg       if (WS.isDefined()) {
1278b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1279b7787fd0SSam Clegg           report_fatal_error(
1280b7787fd0SSam Clegg               "function sections must contain one function each");
1281b7787fd0SSam Clegg 
1282b7787fd0SSam Clegg         if (WS.getSize() == 0)
1283b7787fd0SSam Clegg           report_fatal_error(
1284b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1285b7787fd0SSam Clegg 
12866c899ba6SSam Clegg         // A definition. Write out the function body.
12879f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1288d934cb88SDan Gohman         WasmFunction Func;
12895e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1290d934cb88SDan Gohman         Func.Sym = &WS;
12916c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1292d934cb88SDan Gohman         Functions.push_back(Func);
12936c899ba6SSam Clegg 
12946c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12956c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12966c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12976c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12986c899ba6SSam Clegg         }
1299d934cb88SDan Gohman       } else {
1300d934cb88SDan Gohman         // An import; the index was assigned above.
13016c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1302d934cb88SDan Gohman       }
1303d934cb88SDan Gohman 
13045e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
13056c899ba6SSam Clegg     } else if (WS.isData()) {
1306c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1307c38e947eSSam Clegg         continue;
1308c38e947eSSam Clegg 
13096c899ba6SSam Clegg       if (!WS.isDefined()) {
1310*a165f2d6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1" << "\n");
1311fe6414b0SSam Clegg         continue;
13126c899ba6SSam Clegg       }
1313fe6414b0SSam Clegg 
1314d934cb88SDan Gohman       if (!WS.getSize())
1315c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1316c38e947eSSam Clegg                            WS.getName());
1317d934cb88SDan Gohman 
1318d934cb88SDan Gohman       int64_t Size = 0;
1319d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1320d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1321d934cb88SDan Gohman 
1322759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1323ea7caceeSSam Clegg       assert(DataSection.isWasmData());
13247c395943SSam Clegg 
13256c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13266c899ba6SSam Clegg       // corresponding Wasm data segment.
13276c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13286c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13296c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13306c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13316c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1332*a165f2d6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1333*a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13346c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1335545932beSEric Christopher       if (WS.isDefined())
13366c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13376c899ba6SSam Clegg 
1338545932beSEric Christopher       // An import; the index was assigned above
1339545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1340545932beSEric Christopher                    << "\n");
1341*a165f2d6SSam Clegg     } else {
1342*a165f2d6SSam Clegg       assert(WS.isSection());
1343d934cb88SDan Gohman     }
1344d934cb88SDan Gohman   }
1345d934cb88SDan Gohman 
1346586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1347586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1348586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1349586320c0SNicholas Wilson   // necessarily ordered in this way.
1350b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1351b7787fd0SSam Clegg     if (!S.isVariable())
1352b7787fd0SSam Clegg       continue;
135331a2c809SSam Clegg 
1354cd65f698SSam Clegg     assert(S.isDefined());
1355b7787fd0SSam Clegg 
13565e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1357aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1358aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
13595e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1360b7787fd0SSam Clegg 
13616c899ba6SSam Clegg     if (WS.isFunction()) {
13626c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13636c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13646c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
13656c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13666c899ba6SSam Clegg     } else if (WS.isData()) {
13676c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13686c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13696c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13706c899ba6SSam Clegg       DataLocations[&WS] = Ref;
13716c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13726c899ba6SSam Clegg     } else {
13736c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13746c899ba6SSam Clegg     }
1375586320c0SNicholas Wilson   }
137631a2c809SSam Clegg 
1377586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1378586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1379586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1380586320c0SNicholas Wilson     if (WS.isTemporary() && WS.getName().empty())
1381586320c0SNicholas Wilson       continue;
1382586320c0SNicholas Wilson     if (WS.isComdat() && !WS.isDefined())
1383586320c0SNicholas Wilson       continue;
1384586320c0SNicholas Wilson     if (WS.isTemporary() && WS.isData() && !WS.getSize())
1385586320c0SNicholas Wilson       continue;
1386586320c0SNicholas Wilson 
1387586320c0SNicholas Wilson     uint32_t Flags = 0;
1388586320c0SNicholas Wilson     if (WS.isWeak())
1389586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1390586320c0SNicholas Wilson     if (WS.isHidden())
1391586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1392586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1393586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1394586320c0SNicholas Wilson     if (WS.isUndefined())
1395586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1396586320c0SNicholas Wilson 
1397586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1398586320c0SNicholas Wilson     Info.Name = WS.getName();
1399586320c0SNicholas Wilson     Info.Kind = WS.getType();
1400586320c0SNicholas Wilson     Info.Flags = Flags;
1401586320c0SNicholas Wilson     if (!WS.isData())
1402586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
1403586320c0SNicholas Wilson     else if (WS.isDefined())
1404586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
1405586320c0SNicholas Wilson     SymbolIndices[&WS] = SymbolInfos.size();
1406586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1407b7787fd0SSam Clegg   }
1408b7787fd0SSam Clegg 
14096006e091SSam Clegg   {
14106006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1411f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1412f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1413f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1414f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1415f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1416f9edbe95SSam Clegg         return;
1417f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1418f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
14196c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1420f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1421f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1422329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1423f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
14246c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
14256006e091SSam Clegg         registerFunctionType(WS);
14266006e091SSam Clegg       }
14276006e091SSam Clegg     };
1428970d02c4SDan Gohman 
14296006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
14306006e091SSam Clegg       HandleReloc(RelEntry);
14316006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
14326006e091SSam Clegg       HandleReloc(RelEntry);
1433d934cb88SDan Gohman   }
1434d934cb88SDan Gohman 
1435bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1436bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1437bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1438bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1439bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1440bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1441bafe6902SSam Clegg       continue;
1442bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1443bafe6902SSam Clegg       continue;
1444bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1445bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1446bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1447bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1448bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1449bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1450bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1451bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1452bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1453bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1454bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1455bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1456bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1457bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1458bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1459bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1460bafe6902SSam Clegg     }
1461bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1462bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1463bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1464bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1465bafe6902SSam Clegg          p != end; ++p) {
1466bafe6902SSam Clegg       if (*p != 0)
1467bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1468bafe6902SSam Clegg     }
1469bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1470bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1471bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1472bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1473bafe6902SSam Clegg       if (!Sym)
1474bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1475bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1476bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1477bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1478bafe6902SSam Clegg       if (I == SymbolIndices.end())
1479bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1480bafe6902SSam Clegg       uint32_t Index = I->second;
1481bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1482bafe6902SSam Clegg     }
1483bafe6902SSam Clegg   }
1484bafe6902SSam Clegg 
148518eafb6cSDan Gohman   // Write out the Wasm header.
148618eafb6cSDan Gohman   writeHeader(Asm);
148718eafb6cSDan Gohman 
14889e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1489f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14909e15f359SSam Clegg   writeFunctionSection(Functions);
1491f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1492f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14937c395943SSam Clegg   writeGlobalSection();
14949e15f359SSam Clegg   writeExportSection(Exports);
14959e15f359SSam Clegg   writeElemSection(TableElems);
1496acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14976c899ba6SSam Clegg   writeDataSection();
14986a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
14996a31a0d6SSam Clegg   updateCustomSectionRelocations(Functions, Layout);
1500c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15016f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15026f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15036a31a0d6SSam Clegg   writeCustomRelocSections();
1504970d02c4SDan Gohman 
1505d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
150618eafb6cSDan Gohman }
150718eafb6cSDan Gohman 
150860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
15091301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
151018eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
15110917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
151218eafb6cSDan Gohman }
1513