118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
14264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
15b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.h"
16432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
30bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
32d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
41feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is
42feac819eSAndy Wingo // and empty slot at 0 and therefore calling a null function pointer will trap.
4318c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
516a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
526a31a0d6SSam Clegg   uint64_t PayloadOffset;
536a31a0d6SSam Clegg   // Where the contents of the section starts.
54d934cb88SDan Gohman   uint64_t ContentsOffset;
556f08c84aSSam Clegg   uint32_t Index;
56d934cb88SDan Gohman };
57d934cb88SDan Gohman 
587c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
597c395943SSam Clegg // but that can contain many segments, each with their own virtual location
607c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
617c395943SSam Clegg // wasm data segment.
627c395943SSam Clegg struct WasmDataSegment {
637c395943SSam Clegg   MCSectionWasm *Section;
64d95ed959SSam Clegg   StringRef Name;
652e150409SThomas Lively   uint32_t InitFlags;
664d135b04SWouter van Oortmerssen   uint64_t Offset;
6763ebb813SSam Clegg   uint32_t Alignment;
683b8d2be5SSam Clegg   uint32_t LinkingFlags;
697c395943SSam Clegg   SmallVector<char, 4> Data;
707c395943SSam Clegg };
717c395943SSam Clegg 
729e15f359SSam Clegg // A wasm function to be written into the function section.
739e15f359SSam Clegg struct WasmFunction {
74da419bdbSHeejin Ahn   uint32_t SigIndex;
759e15f359SSam Clegg   const MCSymbolWasm *Sym;
769e15f359SSam Clegg };
779e15f359SSam Clegg 
789e15f359SSam Clegg // A wasm global to be written into the global section.
799e15f359SSam Clegg struct WasmGlobal {
806e7f1826SSam Clegg   wasm::WasmGlobalType Type;
819e15f359SSam Clegg   uint64_t InitialValue;
829e15f359SSam Clegg };
839e15f359SSam Clegg 
84ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
85ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
86ea7caceeSSam Clegg // WasmComdatEntry.
87ea7caceeSSam Clegg struct WasmComdatEntry {
88ea7caceeSSam Clegg   unsigned Kind;
89ea7caceeSSam Clegg   uint32_t Index;
90ea7caceeSSam Clegg };
91ea7caceeSSam Clegg 
926dc65e91SSam Clegg // Information about a single relocation.
936dc65e91SSam Clegg struct WasmRelocationEntry {
946dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
956dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
966dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
976dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
98fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
996dc65e91SSam Clegg 
1006dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1016dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
102fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1036dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1046dc65e91SSam Clegg         FixupSection(FixupSection) {}
1056dc65e91SSam Clegg 
106cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
107acd7d2b0SSam Clegg 
1086dc65e91SSam Clegg   void print(raw_ostream &Out) const {
109f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
110f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1117d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1126dc65e91SSam Clegg   }
113b7787fd0SSam Clegg 
114615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
115b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
116b7787fd0SSam Clegg #endif
1176dc65e91SSam Clegg };
1186dc65e91SSam Clegg 
11918c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12025d8e68bSSam Clegg 
121cfd44a2eSSam Clegg struct WasmCustomSection {
122cfd44a2eSSam Clegg 
1236a31a0d6SSam Clegg   StringRef Name;
1246a31a0d6SSam Clegg   MCSectionWasm *Section;
1256a31a0d6SSam Clegg 
12670fc36d8SKazu Hirata   uint32_t OutputContentsOffset = 0;
12770fc36d8SKazu Hirata   uint32_t OutputIndex = InvalidIndex;
1286a31a0d6SSam Clegg 
1296a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
13070fc36d8SKazu Hirata       : Name(Name), Section(Section) {}
131cfd44a2eSSam Clegg };
132cfd44a2eSSam Clegg 
1331fb8daa6SSam Clegg #if !defined(NDEBUG)
1347f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
135b7787fd0SSam Clegg   Rel.print(OS);
136b7787fd0SSam Clegg   return OS;
137b7787fd0SSam Clegg }
1381fb8daa6SSam Clegg #endif
139b7787fd0SSam Clegg 
140*4c75521cSSam Clegg // Write Value as an (unsigned) LEB value at offset Offset in Stream, padded
14119e8befaSSam Clegg // to allow patching.
142*4c75521cSSam Clegg template <typename T, int W>
143*4c75521cSSam Clegg void writePatchableULEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1443b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
145*4c75521cSSam Clegg   unsigned SizeLen = encodeULEB128(Value, Buffer, W);
1463b29376eSWouter van Oortmerssen   assert(SizeLen == W);
14719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
14819e8befaSSam Clegg }
14919e8befaSSam Clegg 
150*4c75521cSSam Clegg // Write Value as an signed LEB value at offset Offset in Stream, padded
15119e8befaSSam Clegg // to allow patching.
152*4c75521cSSam Clegg template <typename T, int W>
153*4c75521cSSam Clegg void writePatchableSLEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1543b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
155*4c75521cSSam Clegg   unsigned SizeLen = encodeSLEB128(Value, Buffer, W);
1563b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15819e8befaSSam Clegg }
15919e8befaSSam Clegg 
160*4c75521cSSam Clegg static void writePatchableU32(raw_pwrite_stream &Stream, uint32_t Value,
161*4c75521cSSam Clegg                               uint64_t Offset) {
162*4c75521cSSam Clegg   writePatchableULEB<uint32_t, 5>(Stream, Value, Offset);
163*4c75521cSSam Clegg }
164*4c75521cSSam Clegg 
165*4c75521cSSam Clegg static void writePatchableS32(raw_pwrite_stream &Stream, int32_t Value,
166*4c75521cSSam Clegg                               uint64_t Offset) {
167*4c75521cSSam Clegg   writePatchableSLEB<int32_t, 5>(Stream, Value, Offset);
168*4c75521cSSam Clegg }
169*4c75521cSSam Clegg 
170*4c75521cSSam Clegg static void writePatchableU64(raw_pwrite_stream &Stream, uint64_t Value,
171*4c75521cSSam Clegg                               uint64_t Offset) {
172*4c75521cSSam Clegg   writePatchableSLEB<uint64_t, 10>(Stream, Value, Offset);
173*4c75521cSSam Clegg }
174*4c75521cSSam Clegg 
175*4c75521cSSam Clegg static void writePatchableS64(raw_pwrite_stream &Stream, int64_t Value,
176*4c75521cSSam Clegg                               uint64_t Offset) {
177*4c75521cSSam Clegg   writePatchableSLEB<int64_t, 10>(Stream, Value, Offset);
178*4c75521cSSam Clegg }
179*4c75521cSSam Clegg 
180*4c75521cSSam Clegg // Write Value as a plain integer value at offset Offset in Stream.
181*4c75521cSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t Value,
182*4c75521cSSam Clegg                      uint64_t Offset) {
18319e8befaSSam Clegg   uint8_t Buffer[4];
184*4c75521cSSam Clegg   support::endian::write32le(Buffer, Value);
18519e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
18619e8befaSSam Clegg }
18719e8befaSSam Clegg 
188*4c75521cSSam Clegg static void patchI64(raw_pwrite_stream &Stream, uint64_t Value,
189*4c75521cSSam Clegg                      uint64_t Offset) {
1903b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
191*4c75521cSSam Clegg   support::endian::write64le(Buffer, Value);
1923b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1933b29376eSWouter van Oortmerssen }
1943b29376eSWouter van Oortmerssen 
1950ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1960ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1970ff28fa6SDerek Schuff }
1980ff28fa6SDerek Schuff 
19918eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
2000ff28fa6SDerek Schuff   support::endian::Writer *W;
201f17b149dSPeter Collingbourne 
20218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
20318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
20418eafb6cSDan Gohman 
205d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
206d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
207d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
208d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
209d934cb88SDan Gohman 
210d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
211acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
212acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
213d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
214d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
215f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
216388fb67bSPaulo Matos   // Maps function/global/table symbols to the
2171d891d44SHeejin Ahn   // function/global/table/tag/section index space.
2186c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
219492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2206c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2216c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2226a31a0d6SSam Clegg 
2236a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2246a31a0d6SSam Clegg   // section.
2256a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
226cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
227f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2286a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2296a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2306a31a0d6SSam Clegg       CustomSectionsRelocations;
231acd7d2b0SSam Clegg 
232c0d41195SSam Clegg   // Map from section to defining function symbol.
2336ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2346ccb59b3SSam Clegg 
2354c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2364c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2376c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2389f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2397c395943SSam Clegg   unsigned NumGlobalImports = 0;
240feac819eSAndy Wingo   unsigned NumTableImports = 0;
2411d891d44SHeejin Ahn   unsigned NumTagImports = 0;
2427e1c3345SChandler Carruth   uint32_t SectionCount = 0;
243d934cb88SDan Gohman 
2440ff28fa6SDerek Schuff   enum class DwoMode {
2450ff28fa6SDerek Schuff     AllSections,
2460ff28fa6SDerek Schuff     NonDwoOnly,
2470ff28fa6SDerek Schuff     DwoOnly,
2480ff28fa6SDerek Schuff   };
2490ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2500ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2510ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2520ff28fa6SDerek Schuff 
2530ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
25418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
255da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
25618eafb6cSDan Gohman 
2572322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2582322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
259d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
260d934cb88SDan Gohman 
26118eafb6cSDan Gohman public:
2621301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2630ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2640ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2650ff28fa6SDerek Schuff 
2660ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2670ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2680ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2690ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
27018eafb6cSDan Gohman 
2710917c9e4SDan Gohman private:
272acd7d2b0SSam Clegg   void reset() override {
273acd7d2b0SSam Clegg     CodeRelocations.clear();
274acd7d2b0SSam Clegg     DataRelocations.clear();
275acd7d2b0SSam Clegg     TypeIndices.clear();
2766c899ba6SSam Clegg     WasmIndices.clear();
277492f7529SSam Clegg     GOTIndices.clear();
278f9edbe95SSam Clegg     TableIndices.clear();
2796c899ba6SSam Clegg     DataLocations.clear();
280cbda16ebSThomas Lively     CustomSections.clear();
281cbda16ebSThomas Lively     ProducersSection.reset();
282f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2836a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
284da419bdbSHeejin Ahn     SignatureIndices.clear();
285da419bdbSHeejin Ahn     Signatures.clear();
2866c899ba6SSam Clegg     DataSegments.clear();
2876ccb59b3SSam Clegg     SectionFunctions.clear();
2889f3fe42eSSam Clegg     NumFunctionImports = 0;
2897c395943SSam Clegg     NumGlobalImports = 0;
290feac819eSAndy Wingo     NumTableImports = 0;
291105bdc25SSam Clegg     MCObjectWriter::reset();
292acd7d2b0SSam Clegg   }
293acd7d2b0SSam Clegg 
29418eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
29518eafb6cSDan Gohman 
29618eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
29718eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
298ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
29918eafb6cSDan Gohman 
30018eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30118eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
3020ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
3030ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
304438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3059e15f359SSam Clegg 
3060ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
3070ff28fa6SDerek Schuff                           DwoMode Mode);
3080ff28fa6SDerek Schuff 
309b7787fd0SSam Clegg   void writeString(const StringRef Str) {
3100ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
3110ff28fa6SDerek Schuff     W->OS << Str;
312b7787fd0SSam Clegg   }
313b7787fd0SSam Clegg 
3141813fde9SYuta Saito   void writeStringWithAlignment(const StringRef Str, unsigned Alignment);
3151813fde9SYuta Saito 
3160a6c4d8dSSam Clegg   void writeI32(int32_t val) {
3170a6c4d8dSSam Clegg     char Buffer[4];
3180a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3190ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3200a6c4d8dSSam Clegg   }
3210a6c4d8dSSam Clegg 
3220a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3230a6c4d8dSSam Clegg     char Buffer[8];
3240a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3250ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3260a6c4d8dSSam Clegg   }
3270a6c4d8dSSam Clegg 
3280ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3299e15f359SSam Clegg 
3304c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3314d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
332f950b24aSSam Clegg                           uint32_t NumElements);
333457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3348defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
335a5a3659dSAndy Wingo   void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
336a5a3659dSAndy Wingo                         ArrayRef<uint32_t> TableElems);
337fef8de66SThomas Lively   void writeDataCountSection();
338e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
339457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
340e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
3413ec1760dSHeejin Ahn   void writeTagSection(ArrayRef<uint32_t> TagTypes);
3420a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
343388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3446f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
345f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
34631a2c809SSam Clegg   void writeLinkingMetaDataSection(
34786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
348ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
349ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
350cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
351cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3526a31a0d6SSam Clegg   void writeCustomRelocSections();
353acd7d2b0SSam Clegg 
3547ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3557ee758d6SSam Clegg                                const MCAsmLayout &Layout);
356acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3577ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
358acd7d2b0SSam Clegg 
359acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3605e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3611d891d44SHeejin Ahn   uint32_t getTagType(const MCSymbolWasm &Symbol);
36238b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
3631d891d44SHeejin Ahn   void registerTagType(const MCSymbolWasm &Symbol);
36418eafb6cSDan Gohman };
3659e15f359SSam Clegg 
36618eafb6cSDan Gohman } // end anonymous namespace
36718eafb6cSDan Gohman 
368d934cb88SDan Gohman // Write out a section header and a patchable section size field.
369d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3702322a937SSam Clegg                                     unsigned SectionId) {
371d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3720ff28fa6SDerek Schuff   W->OS << char(SectionId);
373d934cb88SDan Gohman 
3740ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
375d934cb88SDan Gohman 
376d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
377d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3780ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
379d934cb88SDan Gohman 
380d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3810ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3820ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3836f08c84aSSam Clegg   Section.Index = SectionCount++;
384d934cb88SDan Gohman }
3852322a937SSam Clegg 
3861813fde9SYuta Saito // Write a string with extra paddings for trailing alignment
3871813fde9SYuta Saito // TODO: support alignment at asm and llvm level?
3881813fde9SYuta Saito void WasmObjectWriter::writeStringWithAlignment(const StringRef Str,
3891813fde9SYuta Saito                                                 unsigned Alignment) {
3901813fde9SYuta Saito 
3911813fde9SYuta Saito   // Calculate the encoded size of str length and add pads based on it and
3921813fde9SYuta Saito   // alignment.
3931813fde9SYuta Saito   raw_null_ostream NullOS;
3941813fde9SYuta Saito   uint64_t StrSizeLength = encodeULEB128(Str.size(), NullOS);
3951813fde9SYuta Saito   uint64_t Offset = W->OS.tell() + StrSizeLength + Str.size();
3961813fde9SYuta Saito   uint64_t Paddings = offsetToAlignment(Offset, Align(Alignment));
3971813fde9SYuta Saito   Offset += Paddings;
3981813fde9SYuta Saito 
3991813fde9SYuta Saito   // LEB128 greater than 5 bytes is invalid
4001813fde9SYuta Saito   assert((StrSizeLength + Paddings) <= 5 && "too long string to align");
4011813fde9SYuta Saito 
4021813fde9SYuta Saito   encodeSLEB128(Str.size(), W->OS, StrSizeLength + Paddings);
4031813fde9SYuta Saito   W->OS << Str;
4041813fde9SYuta Saito 
4051813fde9SYuta Saito   assert(W->OS.tell() == Offset && "invalid padding");
4061813fde9SYuta Saito }
4071813fde9SYuta Saito 
4082322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
4092322a937SSam Clegg                                           StringRef Name) {
410d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
4112322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
4126a31a0d6SSam Clegg 
4136a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
4140ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
4156a31a0d6SSam Clegg 
4162322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
4171813fde9SYuta Saito   if (Name != "__clangast") {
4182322a937SSam Clegg     writeString(Name);
4191813fde9SYuta Saito   } else {
4201813fde9SYuta Saito     // The on-disk hashtable in clangast needs to be aligned by 4 bytes.
4211813fde9SYuta Saito     writeStringWithAlignment(Name, 4);
4221813fde9SYuta Saito   }
4236a31a0d6SSam Clegg 
4246a31a0d6SSam Clegg   // The position where the custom section starts.
4250ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
426d934cb88SDan Gohman }
427d934cb88SDan Gohman 
428d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
429d934cb88SDan Gohman // section size field at the start of the section.
430d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
4310ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
432c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
433c0affde8SSam Clegg   // Simply skip this patching in that case.
434c0affde8SSam Clegg   if (!Size)
435c0affde8SSam Clegg     return;
436c0affde8SSam Clegg 
437c0affde8SSam Clegg   Size -= Section.PayloadOffset;
438d934cb88SDan Gohman   if (uint32_t(Size) != Size)
439d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
440d934cb88SDan Gohman 
441d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
442d934cb88SDan Gohman 
443d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
444d934cb88SDan Gohman   // the section id byte.
445*4c75521cSSam Clegg   writePatchableU32(static_cast<raw_pwrite_stream &>(W->OS), Size,
446f17b149dSPeter Collingbourne                     Section.SizeOffset);
447d934cb88SDan Gohman }
448d934cb88SDan Gohman 
44918eafb6cSDan Gohman // Emit the Wasm header.
45018eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4510ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4520ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
45318eafb6cSDan Gohman }
45418eafb6cSDan Gohman 
45518eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
45618eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4572632ba6aSAndy Wingo   // Some compilation units require the indirect function table to be present
4582632ba6aSAndy Wingo   // but don't explicitly reference it.  This is the case for call_indirect
4592632ba6aSAndy Wingo   // without the reference-types feature, and also function bitcasts in all
4602632ba6aSAndy Wingo   // cases.  In those cases the __indirect_function_table has the
4612632ba6aSAndy Wingo   // WASM_SYMBOL_NO_STRIP attribute.  Here we make sure this symbol makes it to
4622632ba6aSAndy Wingo   // the assembler, if needed.
4632632ba6aSAndy Wingo   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
4642632ba6aSAndy Wingo     const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
4652632ba6aSAndy Wingo     if (WasmSym->isNoStrip())
46696ef4f30SSam Clegg       Asm.registerSymbol(*Sym);
4672632ba6aSAndy Wingo   }
46896ef4f30SSam Clegg 
4696ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4706ccb59b3SSam Clegg   // in recordRelocation.
4716ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4726ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4736ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4746ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4756ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4766ccb59b3SSam Clegg       if (!Pair.second)
4776ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4787d1ff446SFangrui Song                            Sec.getName());
4796ccb59b3SSam Clegg     }
4806ccb59b3SSam Clegg   }
48118eafb6cSDan Gohman }
48218eafb6cSDan Gohman 
48318eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
48418eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
48518eafb6cSDan Gohman                                         const MCFragment *Fragment,
48618eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
487ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
488ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
489e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
490ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
491ecc5e808SSam Clegg 
492fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
493d934cb88SDan Gohman   uint64_t C = Target.getConstant();
494d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
495d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
496aa0c571aSYuta Saito   bool IsLocRel = false;
497d934cb88SDan Gohman 
498d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
499aa0c571aSYuta Saito 
500ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
501aa0c571aSYuta Saito 
502aa0c571aSYuta Saito     if (FixupSection.getKind().isText()) {
503aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
504d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
505aa0c571aSYuta Saito                           "' unsupported subtraction expression used in "
506aa0c571aSYuta Saito                           "relocation in code section.");
507d934cb88SDan Gohman       return;
508d934cb88SDan Gohman     }
509d934cb88SDan Gohman 
510aa0c571aSYuta Saito     if (SymB.isUndefined()) {
511aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
512aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
513aa0c571aSYuta Saito                           "' can not be undefined in a subtraction expression");
514aa0c571aSYuta Saito       return;
515aa0c571aSYuta Saito     }
516aa0c571aSYuta Saito     const MCSection &SecB = SymB.getSection();
517aa0c571aSYuta Saito     if (&SecB != &FixupSection) {
518aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
519aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
520aa0c571aSYuta Saito                           "' can not be placed in a different section");
521aa0c571aSYuta Saito       return;
522aa0c571aSYuta Saito     }
523aa0c571aSYuta Saito     IsLocRel = true;
524aa0c571aSYuta Saito     C += FixupOffset - Layout.getSymbolOffset(SymB);
525aa0c571aSYuta Saito   }
526aa0c571aSYuta Saito 
527d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
528d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
529ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
530d934cb88SDan Gohman 
5313ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
5327d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
5333ea1c62cSSam Clegg     SymA->setUsedInInitArray();
5343ea1c62cSSam Clegg     return;
5353ea1c62cSSam Clegg   }
5363ea1c62cSSam Clegg 
537ecc5e808SSam Clegg   if (SymA->isVariable()) {
538d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
5397ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
5406ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5416ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
542d934cb88SDan Gohman   }
543d934cb88SDan Gohman 
544d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
545d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
546d934cb88SDan Gohman   // be negative and don't wrap.
547d934cb88SDan Gohman   FixedValue = 0;
548d934cb88SDan Gohman 
549ad1f5457SDerek Schuff   unsigned Type =
550ad1f5457SDerek Schuff       TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
5519d24fb7fSSam Clegg 
5524d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5534d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5544d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
555ad1f5457SDerek Schuff   if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
55616f02431SWouter van Oortmerssen        Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
557ad1f5457SDerek Schuff        Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
558ad1f5457SDerek Schuff       SymA->isDefined()) {
559ad1f5457SDerek Schuff     // SymA can be a temp data symbol that represents a function (in which case
560ad1f5457SDerek Schuff     // it needs to be replaced by the section symbol), [XXX and it apparently
561ad1f5457SDerek Schuff     // later gets changed again to a func symbol?] or it can be a real
562ad1f5457SDerek Schuff     // function symbol, in which case it can be left as-is.
563ad1f5457SDerek Schuff 
5644d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5654d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5664d57fbd0SSam Clegg                          "only supported in metadata sections");
5674d57fbd0SSam Clegg 
5684d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5694d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5705e5b2cb1SWouter van Oortmerssen     if (SecA.getKind().isText()) {
5715e5b2cb1SWouter van Oortmerssen       auto SecSymIt = SectionFunctions.find(&SecA);
5725e5b2cb1SWouter van Oortmerssen       if (SecSymIt == SectionFunctions.end())
5735e5b2cb1SWouter van Oortmerssen         report_fatal_error("section doesn\'t have defining symbol");
5745e5b2cb1SWouter van Oortmerssen       SectionSymbol = SecSymIt->second;
5755e5b2cb1SWouter van Oortmerssen     } else {
5764d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5775e5b2cb1SWouter van Oortmerssen     }
5784d57fbd0SSam Clegg     if (!SectionSymbol)
5794d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5804d57fbd0SSam Clegg 
5814d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5824d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5834d57fbd0SSam Clegg   }
5844d57fbd0SSam Clegg 
585feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
5863a293cbfSWouter van Oortmerssen       Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
587feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
588feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
589feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
590feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
591feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
5922632ba6aSAndy Wingo     // We require the function table to have already been defined.
593feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
594feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
595f23b259eSSam Clegg     if (!Sym) {
596f23b259eSSam Clegg       report_fatal_error("missing indirect function table symbol");
597feac819eSAndy Wingo     } else {
598f23b259eSSam Clegg       if (!Sym->isFunctionTable())
599f23b259eSSam Clegg         report_fatal_error("__indirect_function_table symbol has wrong type");
6002632ba6aSAndy Wingo       // Ensure that __indirect_function_table reaches the output.
6012632ba6aSAndy Wingo       Sym->setNoStrip();
6027dc98adbSAndy Wingo       Asm.registerSymbol(*Sym);
603861dbe1aSAndy Wingo     }
6042632ba6aSAndy Wingo   }
605feac819eSAndy Wingo 
606d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
6074d57fbd0SSam Clegg   // against a named symbol.
608d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
6094d57fbd0SSam Clegg     if (SymA->getName().empty())
6104d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
6114d57fbd0SSam Clegg                          "supported by wasm");
6124d57fbd0SSam Clegg 
6134d57fbd0SSam Clegg     SymA->setUsedInReloc();
6144d57fbd0SSam Clegg   }
615ae03c1e7SSam Clegg 
616ef8c9135SSam Clegg   switch (RefA->getKind()) {
617ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_GOT:
618ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_WASM_GOT_TLS:
619492f7529SSam Clegg     SymA->setUsedInGOT();
620ef8c9135SSam Clegg     break;
621ef8c9135SSam Clegg   default:
622ef8c9135SSam Clegg     break;
623ef8c9135SSam Clegg   }
624492f7529SSam Clegg 
625d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
626d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
627d934cb88SDan Gohman 
6286a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
629d934cb88SDan Gohman     DataRelocations.push_back(Rec);
6306a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
63112fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
6326a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
6336a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
6346a31a0d6SSam Clegg   } else {
63512fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
636d934cb88SDan Gohman   }
6376a31a0d6SSam Clegg }
638d934cb88SDan Gohman 
639d934cb88SDan Gohman // Compute a value to write into the code at the location covered
64060ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
64160ec3034SSam Clegg // to make the object format more readable and more likely to be directly
64260ec3034SSam Clegg // useable.
6433b29376eSWouter van Oortmerssen uint64_t
6447ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
6457ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
64648139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
64748139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
64848139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
649492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
650492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
651492f7529SSam Clegg   }
652492f7529SSam Clegg 
65360ec3034SSam Clegg   switch (RelEntry.Type) {
6542a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
6553a293cbfSWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
656d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
657cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
658cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
659cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
660f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
6617ee758d6SSam Clegg     const MCSymbolWasm *Base =
6627ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
6637ee758d6SSam Clegg     assert(Base->isFunction());
6643a293cbfSWouter van Oortmerssen     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
6653a293cbfSWouter van Oortmerssen         RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
6667ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
66781443ac1SSam Clegg     else
6687ee758d6SSam Clegg       return TableIndices[Base];
669f9edbe95SSam Clegg   }
670d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
6716c899ba6SSam Clegg     // Provisional value is same as the index
67260ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
673d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
674d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
67548139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
6761d891d44SHeejin Ahn   case wasm::R_WASM_TAG_INDEX_LEB:
67769e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
6781d891d44SHeejin Ahn     // Provisional value is function/global/tag Wasm index
679492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6806c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
681d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
68216f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
683d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
684ad1f5457SDerek Schuff     if (!RelEntry.Symbol->isDefined())
685ad1f5457SDerek Schuff       return 0;
6866a31a0d6SSam Clegg     const auto &Section =
6876a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6886a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6896a31a0d6SSam Clegg   }
690d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6913b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6923b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6933b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6942a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6953b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6963b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
697a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
698aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
699670944fbSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
700aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
7019c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
702270ed1b3SSam Clegg     // For undefined symbols, use zero
70301a48535SSam Clegg     if (!RelEntry.Symbol->isDefined())
704270ed1b3SSam Clegg       return 0;
70501a48535SSam Clegg     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
70601a48535SSam Clegg     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
707d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
70801a48535SSam Clegg     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
70960ec3034SSam Clegg   }
71060ec3034SSam Clegg   default:
71160ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
71260ec3034SSam Clegg   }
713d934cb88SDan Gohman }
714d934cb88SDan Gohman 
715759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
71663ebb813SSam Clegg                     MCSectionWasm &DataSection) {
7177d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
718759631c7SSam Clegg 
71963ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
72063ebb813SSam Clegg 
721759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
722759631c7SSam Clegg     if (Frag.hasInstructions())
723759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
724759631c7SSam Clegg 
725759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
726759631c7SSam Clegg       if (Align->getValueSize() != 1)
727759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
728759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
729759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
730f208f631SHeejin Ahn       uint64_t Size =
731f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
732f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
733759631c7SSam Clegg       DataBytes.resize(Size, Value);
734759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
735588fad4dSNirav Dave       int64_t NumValues;
736588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
737d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
738588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
739588fad4dSNirav Dave                        Fill->getValue());
74024faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
74124faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
7421d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
743759631c7SSam Clegg     } else {
744759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
745759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
7461d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
747759631c7SSam Clegg     }
748759631c7SSam Clegg   }
749759631c7SSam Clegg 
750d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
751759631c7SSam Clegg }
752759631c7SSam Clegg 
75360ec3034SSam Clegg uint32_t
75460ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
755d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
756b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
757b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
758b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
759acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
760acd7d2b0SSam Clegg   }
76160ec3034SSam Clegg 
76225d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
763acd7d2b0SSam Clegg }
764acd7d2b0SSam Clegg 
765d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
766d934cb88SDan Gohman // directly.
767acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
7687ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
7697ee758d6SSam Clegg     const MCAsmLayout &Layout) {
7700ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
771d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
772d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
773d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
774d934cb88SDan Gohman                       RelEntry.Offset;
775d934cb88SDan Gohman 
776d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
777*4c75521cSSam Clegg     uint64_t Value = getProvisionalValue(RelEntry, Layout);
77860ec3034SSam Clegg 
779acd7d2b0SSam Clegg     switch (RelEntry.Type) {
780d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
781d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
782d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
783d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
7841d891d44SHeejin Ahn     case wasm::R_WASM_TAG_INDEX_LEB:
78569e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
786*4c75521cSSam Clegg       writePatchableU32(Stream, Value, Offset);
7873b29376eSWouter van Oortmerssen       break;
7883b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
789*4c75521cSSam Clegg       writePatchableU64(Stream, Value, Offset);
790d934cb88SDan Gohman       break;
791d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
792d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
793d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
794d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
79548139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
796aa0c571aSYuta Saito     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
7970a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
798d934cb88SDan Gohman       break;
799cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
8003b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
80116f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
8023b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
8033b29376eSWouter van Oortmerssen       break;
804d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
8052a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
806d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
8072a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
808a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
809*4c75521cSSam Clegg       writePatchableS32(Stream, Value, Offset);
8103b29376eSWouter van Oortmerssen       break;
811cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
8123a293cbfSWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
8133b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
8143b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
815670944fbSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
816*4c75521cSSam Clegg       writePatchableS64(Stream, Value, Offset);
81760ec3034SSam Clegg       break;
818d934cb88SDan Gohman     default:
8199d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
820d934cb88SDan Gohman     }
821d934cb88SDan Gohman   }
82218eafb6cSDan Gohman }
82318eafb6cSDan Gohman 
8244c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
8254c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
826da419bdbSHeejin Ahn   if (Signatures.empty())
8279e15f359SSam Clegg     return;
8289e15f359SSam Clegg 
8299e15f359SSam Clegg   SectionBookkeeping Section;
8309e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
8319e15f359SSam Clegg 
8320ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
8339e15f359SSam Clegg 
8344c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
8350ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
8360ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
837da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
8389e15f359SSam Clegg       writeValueType(Ty);
8390ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
840da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
8419e15f359SSam Clegg       writeValueType(Ty);
8429e15f359SSam Clegg   }
8439e15f359SSam Clegg 
8449e15f359SSam Clegg   endSection(Section);
8459e15f359SSam Clegg }
8469e15f359SSam Clegg 
8478defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
8484d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
849f950b24aSSam Clegg                                           uint32_t NumElements) {
8509e15f359SSam Clegg   if (Imports.empty())
8519e15f359SSam Clegg     return;
8529e15f359SSam Clegg 
8534d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
854f950b24aSSam Clegg 
8559e15f359SSam Clegg   SectionBookkeeping Section;
8569e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
8579e15f359SSam Clegg 
8580ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
8598defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
8608defa952SSam Clegg     writeString(Import.Module);
8618defa952SSam Clegg     writeString(Import.Field);
8620ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
8639e15f359SSam Clegg 
8649e15f359SSam Clegg     switch (Import.Kind) {
8659e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
8660ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
8679e15f359SSam Clegg       break;
8689e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
8690ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
8700ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
8719e15f359SSam Clegg       break;
872f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
8730ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
8740ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
875f950b24aSSam Clegg       break;
876f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
8770ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
8780ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
8790ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
880f950b24aSSam Clegg       break;
8811d891d44SHeejin Ahn     case wasm::WASM_EXTERNAL_TAG:
8823ec1760dSHeejin Ahn       W->OS << char(0); // Reserved 'attribute' field
8833ec1760dSHeejin Ahn       encodeULEB128(Import.SigIndex, W->OS);
884da419bdbSHeejin Ahn       break;
8859e15f359SSam Clegg     default:
8869e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
8879e15f359SSam Clegg     }
8889e15f359SSam Clegg   }
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   endSection(Section);
8919e15f359SSam Clegg }
8929e15f359SSam Clegg 
893457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8949e15f359SSam Clegg   if (Functions.empty())
8959e15f359SSam Clegg     return;
8969e15f359SSam Clegg 
8979e15f359SSam Clegg   SectionBookkeeping Section;
8989e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8999e15f359SSam Clegg 
9000ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9019e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
9020ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
9039e15f359SSam Clegg 
9049e15f359SSam Clegg   endSection(Section);
9059e15f359SSam Clegg }
9069e15f359SSam Clegg 
9073ec1760dSHeejin Ahn void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) {
9083ec1760dSHeejin Ahn   if (TagTypes.empty())
909da419bdbSHeejin Ahn     return;
910da419bdbSHeejin Ahn 
911da419bdbSHeejin Ahn   SectionBookkeeping Section;
9121d891d44SHeejin Ahn   startSection(Section, wasm::WASM_SEC_TAG);
913da419bdbSHeejin Ahn 
9143ec1760dSHeejin Ahn   encodeULEB128(TagTypes.size(), W->OS);
9153ec1760dSHeejin Ahn   for (uint32_t Index : TagTypes) {
9163ec1760dSHeejin Ahn     W->OS << char(0); // Reserved 'attribute' field
9173ec1760dSHeejin Ahn     encodeULEB128(Index, W->OS);
918da419bdbSHeejin Ahn   }
919da419bdbSHeejin Ahn 
920da419bdbSHeejin Ahn   endSection(Section);
921da419bdbSHeejin Ahn }
922da419bdbSHeejin Ahn 
9230a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
9240a6c4d8dSSam Clegg   if (Globals.empty())
9250a6c4d8dSSam Clegg     return;
9260a6c4d8dSSam Clegg 
9270a6c4d8dSSam Clegg   SectionBookkeeping Section;
9280a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
9290a6c4d8dSSam Clegg 
9300ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
9310a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
9320ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
9330ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
9340ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
9350a6c4d8dSSam Clegg     switch (Global.Type.Type) {
9360a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
9370ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
9380a6c4d8dSSam Clegg       break;
9390a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
9400ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
9410a6c4d8dSSam Clegg       break;
9420a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
9430a6c4d8dSSam Clegg       writeI32(0);
9440a6c4d8dSSam Clegg       break;
9450a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
9460a6c4d8dSSam Clegg       writeI64(0);
9470a6c4d8dSSam Clegg       break;
94879aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
94979aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
95079aad89dSSam Clegg       break;
9510a6c4d8dSSam Clegg     default:
9520a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
9530a6c4d8dSSam Clegg     }
9540ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
9550a6c4d8dSSam Clegg   }
9560a6c4d8dSSam Clegg 
9570a6c4d8dSSam Clegg   endSection(Section);
9580a6c4d8dSSam Clegg }
9590a6c4d8dSSam Clegg 
960388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
961388fb67bSPaulo Matos   if (Tables.empty())
962388fb67bSPaulo Matos     return;
963388fb67bSPaulo Matos 
964388fb67bSPaulo Matos   SectionBookkeeping Section;
965388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
966388fb67bSPaulo Matos 
967388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
968388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
9691933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
9701933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
9719ac5620cSAndy Wingo     encodeULEB128(Table.Type.Limits.Minimum, W->OS);
9721933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
9731933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
974388fb67bSPaulo Matos   }
975388fb67bSPaulo Matos   endSection(Section);
976388fb67bSPaulo Matos }
977388fb67bSPaulo Matos 
9788defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
9799e15f359SSam Clegg   if (Exports.empty())
9809e15f359SSam Clegg     return;
9819e15f359SSam Clegg 
9829e15f359SSam Clegg   SectionBookkeeping Section;
9839e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
9849e15f359SSam Clegg 
9850ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
9868defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
9878defa952SSam Clegg     writeString(Export.Name);
9880ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
9890ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
9909e15f359SSam Clegg   }
9919e15f359SSam Clegg 
9929e15f359SSam Clegg   endSection(Section);
9939e15f359SSam Clegg }
9949e15f359SSam Clegg 
995a5a3659dSAndy Wingo void WasmObjectWriter::writeElemSection(
996a5a3659dSAndy Wingo     const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
9979e15f359SSam Clegg   if (TableElems.empty())
9989e15f359SSam Clegg     return;
9999e15f359SSam Clegg 
1000a5a3659dSAndy Wingo   assert(IndirectFunctionTable);
1001a5a3659dSAndy Wingo 
10029e15f359SSam Clegg   SectionBookkeeping Section;
10039e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
10049e15f359SSam Clegg 
10050ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
1006a5a3659dSAndy Wingo 
1007a5a3659dSAndy Wingo   assert(WasmIndices.count(IndirectFunctionTable));
1008a5a3659dSAndy Wingo   uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
1009a5a3659dSAndy Wingo   uint32_t Flags = 0;
1010a5a3659dSAndy Wingo   if (TableNumber)
1011a5a3659dSAndy Wingo     Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
1012a5a3659dSAndy Wingo   encodeULEB128(Flags, W->OS);
1013a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
1014a5a3659dSAndy Wingo     encodeULEB128(TableNumber, W->OS); // the table number
10159e15f359SSam Clegg 
10169e15f359SSam Clegg   // init expr for starting offset
10170ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
10180ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
10190ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
10209e15f359SSam Clegg 
1021a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
1022a5a3659dSAndy Wingo     // We only write active function table initializers, for which the elem kind
1023a5a3659dSAndy Wingo     // is specified to be written as 0x00 and interpreted to mean "funcref".
1024a5a3659dSAndy Wingo     const uint8_t ElemKind = 0;
1025a5a3659dSAndy Wingo     W->OS << ElemKind;
1026a5a3659dSAndy Wingo   }
1027a5a3659dSAndy Wingo 
10280ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
10299e15f359SSam Clegg   for (uint32_t Elem : TableElems)
10300ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
10319e15f359SSam Clegg 
10329e15f359SSam Clegg   endSection(Section);
10339e15f359SSam Clegg }
10349e15f359SSam Clegg 
1035fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
1036fef8de66SThomas Lively   if (DataSegments.empty())
1037fef8de66SThomas Lively     return;
1038fef8de66SThomas Lively 
1039fef8de66SThomas Lively   SectionBookkeeping Section;
1040fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
10410ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
1042fef8de66SThomas Lively   endSection(Section);
1043fef8de66SThomas Lively }
1044fef8de66SThomas Lively 
1045e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
1046457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
1047457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
10489e15f359SSam Clegg   if (Functions.empty())
1049e49584a3SSam Clegg     return 0;
10509e15f359SSam Clegg 
10519e15f359SSam Clegg   SectionBookkeeping Section;
10529e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
10539e15f359SSam Clegg 
10540ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
10559e15f359SSam Clegg 
10569e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
1057fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
10589e15f359SSam Clegg 
10599e15f359SSam Clegg     int64_t Size = 0;
10609e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
10619e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
10629e15f359SSam Clegg 
10630ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
10640ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10650ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
10669e15f359SSam Clegg   }
10679e15f359SSam Clegg 
10689e15f359SSam Clegg   // Apply fixups.
10697ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
10709e15f359SSam Clegg 
10719e15f359SSam Clegg   endSection(Section);
1072e49584a3SSam Clegg   return Section.Index;
10739e15f359SSam Clegg }
10749e15f359SSam Clegg 
1075e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
10766c899ba6SSam Clegg   if (DataSegments.empty())
1077e49584a3SSam Clegg     return 0;
10789e15f359SSam Clegg 
10799e15f359SSam Clegg   SectionBookkeeping Section;
10809e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
10819e15f359SSam Clegg 
10820ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
10837c395943SSam Clegg 
10846c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
10850ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
1086831a143eSAndy Wingo     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
10870ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
1088831a143eSAndy Wingo     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
10890d9b17d0SWouter van Oortmerssen       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
10904d135b04SWouter van Oortmerssen                               : wasm::WASM_OPCODE_I32_CONST);
10910ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
10920ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
10932e150409SThomas Lively     }
10940ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
10950ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10960ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
10977c395943SSam Clegg   }
10989e15f359SSam Clegg 
10999e15f359SSam Clegg   // Apply fixups.
11007ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
11019e15f359SSam Clegg 
11029e15f359SSam Clegg   endSection(Section);
1103e49584a3SSam Clegg   return Section.Index;
11049e15f359SSam Clegg }
11059e15f359SSam Clegg 
11066f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
11076f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
1108f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
1109c71fbdd8SQuinn Pham   // See: https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md
11109e15f359SSam Clegg   // for descriptions of the reloc sections.
11119e15f359SSam Clegg 
1112f77dc2a8SSam Clegg   if (Relocs.empty())
11139e15f359SSam Clegg     return;
11149e15f359SSam Clegg 
1115f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1116f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1117f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1118f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1119f77dc2a8SSam Clegg   // not the sections order.
1120efd94c56SFangrui Song   llvm::stable_sort(
1121efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1122f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1123f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1124f77dc2a8SSam Clegg       });
1125f77dc2a8SSam Clegg 
11269e15f359SSam Clegg   SectionBookkeeping Section;
11276f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
11289e15f359SSam Clegg 
11290ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
11300ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1131f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1132f208f631SHeejin Ahn     uint64_t Offset =
1133f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
11346f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
11359e15f359SSam Clegg 
11360ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
11370ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
11380ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
11396f08c84aSSam Clegg     if (RelEntry.hasAddend())
11400ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
11419e15f359SSam Clegg   }
11429e15f359SSam Clegg 
11439e15f359SSam Clegg   endSection(Section);
11449e15f359SSam Clegg }
11459e15f359SSam Clegg 
11466a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
11476a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
11486a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
11496a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
11506a31a0d6SSam Clegg   }
11516a31a0d6SSam Clegg }
11526a31a0d6SSam Clegg 
11539e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
115486b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1155ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1156ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
11579e15f359SSam Clegg   SectionBookkeeping Section;
11582322a937SSam Clegg   startCustomSection(Section, "linking");
11590ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
11609e15f359SSam Clegg 
11616bb5a41fSSam Clegg   SectionBookkeeping SubSection;
11626c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
11636c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
11640ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
11656c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
11660ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
11670ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
11686c899ba6SSam Clegg       switch (Sym.Kind) {
11696c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
11706c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
11711d891d44SHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_TAG:
1172388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
11730ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
117429874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
117529874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
11766c899ba6SSam Clegg           writeString(Sym.Name);
11776c899ba6SSam Clegg         break;
11786c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
11796c899ba6SSam Clegg         writeString(Sym.Name);
11806c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
11810ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
11820ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
11830ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
11846c899ba6SSam Clegg         }
11856c899ba6SSam Clegg         break;
11866a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
11876a31a0d6SSam Clegg         const uint32_t SectionIndex =
11886a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
11890ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
11906a31a0d6SSam Clegg         break;
11916a31a0d6SSam Clegg       }
11926c899ba6SSam Clegg       default:
11936c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
11946c899ba6SSam Clegg       }
1195b7787fd0SSam Clegg     }
1196b7787fd0SSam Clegg     endSection(SubSection);
1197b7787fd0SSam Clegg   }
11989e15f359SSam Clegg 
11996c899ba6SSam Clegg   if (DataSegments.size()) {
120063ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
12010ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
12026c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1203d95ed959SSam Clegg       writeString(Segment.Name);
12040ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
12053b8d2be5SSam Clegg       encodeULEB128(Segment.LinkingFlags, W->OS);
120663ebb813SSam Clegg     }
1207d95ed959SSam Clegg     endSection(SubSection);
1208d95ed959SSam Clegg   }
1209d95ed959SSam Clegg 
1210bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1211bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
12120ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1213bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
12140ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
12150ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1216bafe6902SSam Clegg     }
1217bafe6902SSam Clegg     endSection(SubSection);
1218bafe6902SSam Clegg   }
1219bafe6902SSam Clegg 
1220ea7caceeSSam Clegg   if (Comdats.size()) {
1221ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
12220ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1223ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1224ea7caceeSSam Clegg       writeString(C.first);
12250ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
12260ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1227ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
12280ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
12290ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1230ea7caceeSSam Clegg       }
1231ea7caceeSSam Clegg     }
1232ea7caceeSSam Clegg     endSection(SubSection);
1233ea7caceeSSam Clegg   }
1234ea7caceeSSam Clegg 
12359e15f359SSam Clegg   endSection(Section);
12369e15f359SSam Clegg }
12379e15f359SSam Clegg 
1238cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1239cbda16ebSThomas Lively                                           const MCAssembler &Asm,
12406a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1241cfd44a2eSSam Clegg   SectionBookkeeping Section;
12426a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
12432322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
12446a31a0d6SSam Clegg 
12450ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
12460ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
12476a31a0d6SSam Clegg 
12486a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
12496a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
12506a31a0d6SSam Clegg 
1251cfd44a2eSSam Clegg   endSection(Section);
12526a31a0d6SSam Clegg 
12536a31a0d6SSam Clegg   // Apply fixups.
12544d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
12557ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
12566a31a0d6SSam Clegg }
12576a31a0d6SSam Clegg 
12585e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
12595e3d33a7SSam Clegg   assert(Symbol.isFunction());
12605e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
12615e3d33a7SSam Clegg   return TypeIndices[&Symbol];
12625e3d33a7SSam Clegg }
12635e3d33a7SSam Clegg 
12641d891d44SHeejin Ahn uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) {
12651d891d44SHeejin Ahn   assert(Symbol.isTag());
1266da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1267da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1268da419bdbSHeejin Ahn }
1269da419bdbSHeejin Ahn 
127038b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
12715e3d33a7SSam Clegg   assert(Symbol.isFunction());
12725e3d33a7SSam Clegg 
12734c41fb5aSHeejin Ahn   wasm::WasmSignature S;
12747ee758d6SSam Clegg 
12757ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1276da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1277da419bdbSHeejin Ahn     S.Params = Sig->Params;
127877a7a380SDerek Schuff   }
12795e3d33a7SSam Clegg 
1280da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
12815e3d33a7SSam Clegg   if (Pair.second)
1282da419bdbSHeejin Ahn     Signatures.push_back(S);
12835e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
12845e3d33a7SSam Clegg 
1285d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1286d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1287d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
12885e3d33a7SSam Clegg }
12895e3d33a7SSam Clegg 
12901d891d44SHeejin Ahn void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) {
12911d891d44SHeejin Ahn   assert(Symbol.isTag());
1292da419bdbSHeejin Ahn 
1293da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1294da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
12954c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1296da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1297da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1298da419bdbSHeejin Ahn     S.Params = Sig->Params;
1299da419bdbSHeejin Ahn   }
1300da419bdbSHeejin Ahn 
1301da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1302da419bdbSHeejin Ahn   if (Pair.second)
1303da419bdbSHeejin Ahn     Signatures.push_back(S);
1304da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1305da419bdbSHeejin Ahn 
13061d891d44SHeejin Ahn   LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.second
1307da419bdbSHeejin Ahn                     << "\n");
1308da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1309da419bdbSHeejin Ahn }
1310da419bdbSHeejin Ahn 
13114d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
13123ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
13134d57fbd0SSam Clegg     return true;
13144d57fbd0SSam Clegg 
13154d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
13164d57fbd0SSam Clegg     return false;
13174d57fbd0SSam Clegg 
13183ea1c62cSSam Clegg   if (Sym.isTemporary())
13194d57fbd0SSam Clegg     return false;
13204d57fbd0SSam Clegg 
13214d57fbd0SSam Clegg   if (Sym.isSection())
13224d57fbd0SSam Clegg     return false;
13234d57fbd0SSam Clegg 
13242632ba6aSAndy Wingo   if (Sym.omitFromLinkingSection())
13252632ba6aSAndy Wingo     return false;
13262632ba6aSAndy Wingo 
13274d57fbd0SSam Clegg   return true;
13284d57fbd0SSam Clegg }
132930d314aaSSam Clegg 
13300ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
13310ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
133218eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1333f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1334f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1335f950b24aSSam Clegg   // it if there are no loads or stores.
13368defa952SSam Clegg   wasm::WasmImport MemImport;
13371ed3a046SSam Clegg   MemImport.Module = "env";
13381ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1339f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1340fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1341fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1342f950b24aSSam Clegg   Imports.push_back(MemImport);
1343f950b24aSSam Clegg 
1344da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1345586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1346586320c0SNicholas Wilson   // symbols.
134732ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
134832ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
134932ce5ca0SDan Gohman 
135032ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
13519f3fe42eSSam Clegg     // (because wasm always needs a type signature).
13527ee758d6SSam Clegg     if (WS.isFunction()) {
13539c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
13549c7b5808SDominic Chen       if (!BS)
13559c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
13569c7b5808SDominic Chen                            ": absolute addressing not supported!");
13579c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
13587ee758d6SSam Clegg     }
135932ce5ca0SDan Gohman 
13601d891d44SHeejin Ahn     if (WS.isTag())
13611d891d44SHeejin Ahn       registerTagType(WS);
1362da419bdbSHeejin Ahn 
136332ce5ca0SDan Gohman     if (WS.isTemporary())
136432ce5ca0SDan Gohman       continue;
136532ce5ca0SDan Gohman 
136632ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
13676c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
13686c899ba6SSam Clegg       if (WS.isFunction()) {
13698defa952SSam Clegg         wasm::WasmImport Import;
1370f726e445SDan Gohman         Import.Module = WS.getImportModule();
1371f726e445SDan Gohman         Import.Field = WS.getImportName();
137232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
13738defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
13746c899ba6SSam Clegg         Imports.push_back(Import);
1375492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13766c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
13776c899ba6SSam Clegg       } else if (WS.isGlobal()) {
137815f349f7SNicholas Wilson         if (WS.isWeak())
137915f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
138015f349f7SNicholas Wilson 
13816c899ba6SSam Clegg         wasm::WasmImport Import;
1382f726e445SDan Gohman         Import.Field = WS.getImportName();
138332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1384492f7529SSam Clegg         Import.Module = WS.getImportModule();
13856c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
13866c899ba6SSam Clegg         Imports.push_back(Import);
1387492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13886c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
13891d891d44SHeejin Ahn       } else if (WS.isTag()) {
1390da419bdbSHeejin Ahn         if (WS.isWeak())
13911d891d44SHeejin Ahn           report_fatal_error("undefined tag symbol cannot be weak");
1392da419bdbSHeejin Ahn 
1393da419bdbSHeejin Ahn         wasm::WasmImport Import;
1394f726e445SDan Gohman         Import.Module = WS.getImportModule();
1395f726e445SDan Gohman         Import.Field = WS.getImportName();
13961d891d44SHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_TAG;
13973ec1760dSHeejin Ahn         Import.SigIndex = getTagType(WS);
1398da419bdbSHeejin Ahn         Imports.push_back(Import);
1399492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
14001d891d44SHeejin Ahn         WasmIndices[&WS] = NumTagImports++;
1401feac819eSAndy Wingo       } else if (WS.isTable()) {
1402feac819eSAndy Wingo         if (WS.isWeak())
1403feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1404feac819eSAndy Wingo 
1405feac819eSAndy Wingo         wasm::WasmImport Import;
1406feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1407feac819eSAndy Wingo         Import.Field = WS.getImportName();
1408feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1409c9801db2SAndy Wingo         Import.Table = WS.getTableType();
1410feac819eSAndy Wingo         Imports.push_back(Import);
1411feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1412feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
141332ce5ca0SDan Gohman       }
141432ce5ca0SDan Gohman     }
141532ce5ca0SDan Gohman   }
141632ce5ca0SDan Gohman 
1417492f7529SSam Clegg   // Add imports for GOT globals
1418492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1419492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1420492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1421492f7529SSam Clegg       wasm::WasmImport Import;
1422492f7529SSam Clegg       if (WS.isFunction())
1423492f7529SSam Clegg         Import.Module = "GOT.func";
1424492f7529SSam Clegg       else
1425492f7529SSam Clegg         Import.Module = "GOT.mem";
1426492f7529SSam Clegg       Import.Field = WS.getName();
1427492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1428492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1429492f7529SSam Clegg       Imports.push_back(Import);
1430492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1431492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1432492f7529SSam Clegg     }
1433492f7529SSam Clegg   }
14340ff28fa6SDerek Schuff }
1435492f7529SSam Clegg 
14360ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
14370ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
14380ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
14390ff28fa6SDerek Schuff   W = &MainWriter;
14400ff28fa6SDerek Schuff   if (IsSplitDwarf) {
14410ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
14420ff28fa6SDerek Schuff     assert(DwoOS);
14430ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
14440ff28fa6SDerek Schuff     W = &DwoWriter;
14450ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
14460ff28fa6SDerek Schuff   } else {
14470ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
14480ff28fa6SDerek Schuff   }
14490ff28fa6SDerek Schuff }
14500ff28fa6SDerek Schuff 
14510ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
14520ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
14530ff28fa6SDerek Schuff                                           DwoMode Mode) {
14540ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
14550ff28fa6SDerek Schuff   SectionCount = 0;
14560ff28fa6SDerek Schuff   CustomSections.clear();
14570ff28fa6SDerek Schuff 
14580ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
14590ff28fa6SDerek Schuff 
14600ff28fa6SDerek Schuff   // Collect information from the available symbols.
14610ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
14620ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
14630ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
14640ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
14653ec1760dSHeejin Ahn   SmallVector<uint32_t, 2> TagTypes;
14660ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1467388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
14680ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
14690ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
14700ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
14710ff28fa6SDerek Schuff   uint64_t DataSize = 0;
14720ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
14730ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
14740ff28fa6SDerek Schuff   }
147530d314aaSSam Clegg 
14764d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
14774d57fbd0SSam Clegg   // populating DataLocations.
1478759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1479759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
14807d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1481759631c7SSam Clegg 
14820ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
14830ff28fa6SDerek Schuff       continue;
14840ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
14850ff28fa6SDerek Schuff       continue;
14860ff28fa6SDerek Schuff 
14878d396acaSDerek Schuff     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
14888d396acaSDerek Schuff                       << Section.getGroup() << "\n";);
14898d396acaSDerek Schuff 
1490bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
14914d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1492bafe6902SSam Clegg       continue;
1493bafe6902SSam Clegg 
14944d57fbd0SSam Clegg     // Code is handled separately
14954d57fbd0SSam Clegg     if (Section.getKind().isText())
14964d57fbd0SSam Clegg       continue;
14974d57fbd0SSam Clegg 
14984d57fbd0SSam Clegg     if (Section.isWasmData()) {
1499329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1500759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1501759631c7SSam Clegg       DataSegments.emplace_back();
1502759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
15034d57fbd0SSam Clegg       Segment.Name = SectionName;
1504831a143eSAndy Wingo       Segment.InitFlags = Section.getPassive()
1505831a143eSAndy Wingo                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1506831a143eSAndy Wingo                               : 0;
1507759631c7SSam Clegg       Segment.Offset = DataSize;
1508759631c7SSam Clegg       Segment.Section = &Section;
150963ebb813SSam Clegg       addData(Segment.Data, Section);
151056c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
15113b8d2be5SSam Clegg       Segment.LinkingFlags = Section.getSegmentFlags();
1512759631c7SSam Clegg       DataSize += Segment.Data.size();
15136c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1514ea7caceeSSam Clegg 
1515ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1516ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1517329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1518ea7caceeSSam Clegg       }
15194d57fbd0SSam Clegg     } else {
15204d57fbd0SSam Clegg       // Create custom sections
15214d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
15224d57fbd0SSam Clegg 
15234d57fbd0SSam Clegg       StringRef Name = SectionName;
15244d57fbd0SSam Clegg 
15254d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
15264d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
15274d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
15284d57fbd0SSam Clegg 
15294d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1530fb807d4dSSam Clegg       if (Begin) {
153130d314aaSSam Clegg         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
15324d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1533fb807d4dSSam Clegg       }
1534cbda16ebSThomas Lively 
1535f6f4f843SThomas Lively       // Separate out the producers and target features sections
1536cbda16ebSThomas Lively       if (Name == "producers") {
15370eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1538cbda16ebSThomas Lively         continue;
1539cbda16ebSThomas Lively       }
1540f6f4f843SThomas Lively       if (Name == "target_features") {
1541f6f4f843SThomas Lively         TargetFeaturesSection =
15420eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1543f6f4f843SThomas Lively         continue;
1544f6f4f843SThomas Lively       }
1545cbda16ebSThomas Lively 
15460a391060SDerek Schuff       // Custom sections can also belong to COMDAT groups. In this case the
15470a391060SDerek Schuff       // decriptor's "index" field is the section index (in the final object
15480a391060SDerek Schuff       // file), but that is not known until after layout, so it must be fixed up
15490a391060SDerek Schuff       // later
15500a391060SDerek Schuff       if (const MCSymbolWasm *C = Section.getGroup()) {
15510a391060SDerek Schuff         Comdats[C->getName()].emplace_back(
15520a391060SDerek Schuff             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
15530a391060SDerek Schuff                             static_cast<uint32_t>(CustomSections.size())});
15540a391060SDerek Schuff       }
15550a391060SDerek Schuff 
15564d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1557759631c7SSam Clegg     }
15586a31a0d6SSam Clegg   }
15596a31a0d6SSam Clegg 
156030d314aaSSam Clegg   if (Mode != DwoMode::DwoOnly) {
1561586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for defined symbols.
1562d934cb88SDan Gohman     for (const MCSymbol &S : Asm.symbols()) {
1563d934cb88SDan Gohman       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1564d934cb88SDan Gohman       // or used in relocations.
1565d934cb88SDan Gohman       if (S.isTemporary() && S.getName().empty())
1566d934cb88SDan Gohman         continue;
1567b7787fd0SSam Clegg 
1568d934cb88SDan Gohman       const auto &WS = static_cast<const MCSymbolWasm &>(S);
15695e5b2cb1SWouter van Oortmerssen       LLVM_DEBUG(dbgs()
15705e5b2cb1SWouter van Oortmerssen                  << "MCSymbol: "
15715e5b2cb1SWouter van Oortmerssen                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
15725e5b2cb1SWouter van Oortmerssen                  << " '" << S << "'"
1573d34e60caSNicola Zaghen                  << " isDefined=" << S.isDefined() << " isExternal="
1574d34e60caSNicola Zaghen                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1575d34e60caSNicola Zaghen                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1576b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1577b7787fd0SSam Clegg 
15785e3d33a7SSam Clegg       if (WS.isVariable())
15795e3d33a7SSam Clegg         continue;
15806c899ba6SSam Clegg       if (WS.isComdat() && !WS.isDefined())
15816c899ba6SSam Clegg         continue;
1582b7787fd0SSam Clegg 
1583d934cb88SDan Gohman       if (WS.isFunction()) {
15846c899ba6SSam Clegg         unsigned Index;
1585cd65f698SSam Clegg         if (WS.isDefined()) {
1586b7787fd0SSam Clegg           if (WS.getOffset() != 0)
1587b7787fd0SSam Clegg             report_fatal_error(
1588b7787fd0SSam Clegg                 "function sections must contain one function each");
1589b7787fd0SSam Clegg 
159018c56a07SHeejin Ahn           if (WS.getSize() == nullptr)
1591b7787fd0SSam Clegg             report_fatal_error(
1592b7787fd0SSam Clegg                 "function symbols must have a size set with .size");
1593b7787fd0SSam Clegg 
15946c899ba6SSam Clegg           // A definition. Write out the function body.
15959f3fe42eSSam Clegg           Index = NumFunctionImports + Functions.size();
1596d934cb88SDan Gohman           WasmFunction Func;
1597da419bdbSHeejin Ahn           Func.SigIndex = getFunctionType(WS);
1598d934cb88SDan Gohman           Func.Sym = &WS;
159930d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
16006c899ba6SSam Clegg           WasmIndices[&WS] = Index;
1601d934cb88SDan Gohman           Functions.push_back(Func);
16026c899ba6SSam Clegg 
16036c899ba6SSam Clegg           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
16046c899ba6SSam Clegg           if (const MCSymbolWasm *C = Section.getGroup()) {
16056c899ba6SSam Clegg             Comdats[C->getName()].emplace_back(
16066c899ba6SSam Clegg                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
16076c899ba6SSam Clegg           }
1608881d8778SSam Clegg 
1609881d8778SSam Clegg           if (WS.hasExportName()) {
1610881d8778SSam Clegg             wasm::WasmExport Export;
1611881d8778SSam Clegg             Export.Name = WS.getExportName();
1612881d8778SSam Clegg             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1613881d8778SSam Clegg             Export.Index = Index;
1614881d8778SSam Clegg             Exports.push_back(Export);
1615881d8778SSam Clegg           }
1616d934cb88SDan Gohman         } else {
1617d934cb88SDan Gohman           // An import; the index was assigned above.
16186c899ba6SSam Clegg           Index = WasmIndices.find(&WS)->second;
1619d934cb88SDan Gohman         }
1620d934cb88SDan Gohman 
1621d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1622da419bdbSHeejin Ahn 
16236c899ba6SSam Clegg       } else if (WS.isData()) {
1624f3feb6adSWouter van Oortmerssen         if (!isInSymtab(WS))
1625c38e947eSSam Clegg           continue;
1626c38e947eSSam Clegg 
16276c899ba6SSam Clegg         if (!WS.isDefined()) {
1628d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1629d34e60caSNicola Zaghen                             << "\n");
1630fe6414b0SSam Clegg           continue;
16316c899ba6SSam Clegg         }
1632fe6414b0SSam Clegg 
1633d934cb88SDan Gohman         if (!WS.getSize())
1634c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1635c38e947eSSam Clegg                              WS.getName());
1636d934cb88SDan Gohman 
1637d934cb88SDan Gohman         int64_t Size = 0;
1638d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1639d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1640d934cb88SDan Gohman 
1641759631c7SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1642079cba04SSam Clegg         if (!DataSection.isWasmData())
1643079cba04SSam Clegg           report_fatal_error("data symbols must live in a data section: " +
1644079cba04SSam Clegg                              WS.getName());
16457c395943SSam Clegg 
16466c899ba6SSam Clegg         // For each data symbol, export it in the symtab as a reference to the
16476c899ba6SSam Clegg         // corresponding Wasm data segment.
16486c899ba6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16493b29376eSWouter van Oortmerssen             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
16503b29376eSWouter van Oortmerssen             static_cast<uint64_t>(Size)};
165130d314aaSSam Clegg         assert(DataLocations.count(&WS) == 0);
16526c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1653d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1654da419bdbSHeejin Ahn 
1655a165f2d6SSam Clegg       } else if (WS.isGlobal()) {
16566c899ba6SSam Clegg         // A "true" Wasm global (currently just __stack_pointer)
16570a6c4d8dSSam Clegg         if (WS.isDefined()) {
16580a6c4d8dSSam Clegg           wasm::WasmGlobal Global;
16590a6c4d8dSSam Clegg           Global.Type = WS.getGlobalType();
16600a6c4d8dSSam Clegg           Global.Index = NumGlobalImports + Globals.size();
16610a6c4d8dSSam Clegg           switch (Global.Type.Type) {
16620a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I32:
16630a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
16640a6c4d8dSSam Clegg             break;
16650a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I64:
16660a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
16670a6c4d8dSSam Clegg             break;
16680a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F32:
16690a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
16700a6c4d8dSSam Clegg             break;
16710a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F64:
16720a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
16730a6c4d8dSSam Clegg             break;
167479aad89dSSam Clegg           case wasm::WASM_TYPE_EXTERNREF:
167579aad89dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
167679aad89dSSam Clegg             break;
16770a6c4d8dSSam Clegg           default:
16780a6c4d8dSSam Clegg             llvm_unreachable("unexpected type");
16790a6c4d8dSSam Clegg           }
168030d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
16810a6c4d8dSSam Clegg           WasmIndices[&WS] = Global.Index;
16820a6c4d8dSSam Clegg           Globals.push_back(Global);
16830a6c4d8dSSam Clegg         } else {
1684545932beSEric Christopher           // An import; the index was assigned above
1685d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> global index: "
1686d34e60caSNicola Zaghen                             << WasmIndices.find(&WS)->second << "\n");
16870a6c4d8dSSam Clegg         }
1688388fb67bSPaulo Matos       } else if (WS.isTable()) {
1689388fb67bSPaulo Matos         if (WS.isDefined()) {
1690388fb67bSPaulo Matos           wasm::WasmTable Table;
1691388fb67bSPaulo Matos           Table.Index = NumTableImports + Tables.size();
1692c9801db2SAndy Wingo           Table.Type = WS.getTableType();
169330d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1694388fb67bSPaulo Matos           WasmIndices[&WS] = Table.Index;
1695388fb67bSPaulo Matos           Tables.push_back(Table);
1696388fb67bSPaulo Matos         }
169730d314aaSSam Clegg         LLVM_DEBUG(dbgs() << " -> table index: "
169830d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
16991d891d44SHeejin Ahn       } else if (WS.isTag()) {
170028780e59SHeejin Ahn         // C++ exception symbol (__cpp_exception) or longjmp symbol
170128780e59SHeejin Ahn         // (__c_longjmp)
1702da419bdbSHeejin Ahn         unsigned Index;
1703da419bdbSHeejin Ahn         if (WS.isDefined()) {
17043ec1760dSHeejin Ahn           Index = NumTagImports + TagTypes.size();
17053ec1760dSHeejin Ahn           uint32_t SigIndex = getTagType(WS);
170630d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1707da419bdbSHeejin Ahn           WasmIndices[&WS] = Index;
17083ec1760dSHeejin Ahn           TagTypes.push_back(SigIndex);
1709da419bdbSHeejin Ahn         } else {
1710da419bdbSHeejin Ahn           // An import; the index was assigned above.
1711492f7529SSam Clegg           assert(WasmIndices.count(&WS) > 0);
1712da419bdbSHeejin Ahn         }
17131d891d44SHeejin Ahn         LLVM_DEBUG(dbgs() << "  -> tag index: " << WasmIndices.find(&WS)->second
17141d891d44SHeejin Ahn                           << "\n");
1715da419bdbSHeejin Ahn 
1716a165f2d6SSam Clegg       } else {
1717a165f2d6SSam Clegg         assert(WS.isSection());
1718d934cb88SDan Gohman       }
1719d934cb88SDan Gohman     }
1720d934cb88SDan Gohman 
1721586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1722586320c0SNicholas Wilson     // process these in a separate pass because we need to have processed the
1723586320c0SNicholas Wilson     // target of the alias before the alias itself and the symbols are not
1724586320c0SNicholas Wilson     // necessarily ordered in this way.
1725b7787fd0SSam Clegg     for (const MCSymbol &S : Asm.symbols()) {
1726b7787fd0SSam Clegg       if (!S.isVariable())
1727b7787fd0SSam Clegg         continue;
172831a2c809SSam Clegg 
1729cd65f698SSam Clegg       assert(S.isDefined());
1730b7787fd0SSam Clegg 
17319c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
17329c7b5808SDominic Chen       if (!BS)
17339c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
17349c7b5808SDominic Chen                            ": absolute addressing not supported!");
17359c7b5808SDominic Chen       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
17367ee758d6SSam Clegg 
17375e3d33a7SSam Clegg       // Find the target symbol of this weak alias and export that index
1738aff1c4dfSSam Clegg       const auto &WS = static_cast<const MCSymbolWasm &>(S);
173930d314aaSSam Clegg       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
174030d314aaSSam Clegg                         << "'\n");
1741b7787fd0SSam Clegg 
17427ee758d6SSam Clegg       if (Base->isFunction()) {
17437ee758d6SSam Clegg         assert(WasmIndices.count(Base) > 0);
17447ee758d6SSam Clegg         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1745492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
17466c899ba6SSam Clegg         WasmIndices[&WS] = WasmIndex;
1747d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
17487ee758d6SSam Clegg       } else if (Base->isData()) {
17497ee758d6SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
17507ee758d6SSam Clegg         uint64_t Offset = Layout.getSymbolOffset(S);
17517ee758d6SSam Clegg         int64_t Size = 0;
17527ee758d6SSam Clegg         // For data symbol alias we use the size of the base symbol as the
17537ee758d6SSam Clegg         // size of the alias.  When an offset from the base is involved this
17547ee758d6SSam Clegg         // can result in a offset + size goes past the end of the data section
17557ee758d6SSam Clegg         // which out object format doesn't support.  So we must clamp it.
17567ee758d6SSam Clegg         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
17577ee758d6SSam Clegg           report_fatal_error(".size expression must be evaluatable");
17587ee758d6SSam Clegg         const WasmDataSegment &Segment =
17597ee758d6SSam Clegg             DataSegments[DataSection.getSegmentIndex()];
17607ee758d6SSam Clegg         Size =
17617ee758d6SSam Clegg             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
17627ee758d6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
17637ee758d6SSam Clegg             DataSection.getSegmentIndex(),
17647ee758d6SSam Clegg             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
17657ee758d6SSam Clegg             static_cast<uint32_t>(Size)};
17666c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1767d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
17686c899ba6SSam Clegg       } else {
17691d891d44SHeejin Ahn         report_fatal_error("don't yet support global/tag aliases");
17706c899ba6SSam Clegg       }
1771586320c0SNicholas Wilson     }
177230d314aaSSam Clegg   }
177331a2c809SSam Clegg 
1774586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1775586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1776586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
177725d8e68bSSam Clegg     if (!isInSymtab(WS)) {
177818c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1779586320c0SNicholas Wilson       continue;
178025d8e68bSSam Clegg     }
1781d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1782586320c0SNicholas Wilson 
1783586320c0SNicholas Wilson     uint32_t Flags = 0;
1784586320c0SNicholas Wilson     if (WS.isWeak())
1785586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1786586320c0SNicholas Wilson     if (WS.isHidden())
1787586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1788586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1789586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1790586320c0SNicholas Wilson     if (WS.isUndefined())
1791586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1792da84b688SDan Gohman     if (WS.isNoStrip()) {
1793da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1794da84b688SDan Gohman       if (isEmscripten()) {
1795d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1796da84b688SDan Gohman       }
1797da84b688SDan Gohman     }
1798b4f4e370SSam Clegg     if (WS.hasImportName())
179929874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1800881d8778SSam Clegg     if (WS.hasExportName())
1801881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
180244177e5fSSam Clegg     if (WS.isTLS())
180344177e5fSSam Clegg       Flags |= wasm::WASM_SYMBOL_TLS;
1804586320c0SNicholas Wilson 
1805586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1806586320c0SNicholas Wilson     Info.Name = WS.getName();
18075e5b2cb1SWouter van Oortmerssen     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1808586320c0SNicholas Wilson     Info.Flags = Flags;
18094d57fbd0SSam Clegg     if (!WS.isData()) {
18104d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1811586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
18124d57fbd0SSam Clegg     } else if (WS.isDefined()) {
18134d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1814586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
18154d57fbd0SSam Clegg     }
181625d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1817586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1818b7787fd0SSam Clegg   }
1819b7787fd0SSam Clegg 
18206006e091SSam Clegg   {
18216006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1822f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1823f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1824f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1825d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1826cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
182781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1828cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
18293a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB &&
18303a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
1831f9edbe95SSam Clegg         return;
1832f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
18337ee758d6SSam Clegg       const MCSymbolWasm *Base =
18347ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
18357ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
183618c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
18377ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
18387ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1839f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
18406c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
18417ee758d6SSam Clegg         registerFunctionType(*Base);
18426006e091SSam Clegg       }
18436006e091SSam Clegg     };
1844970d02c4SDan Gohman 
18456006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
18466006e091SSam Clegg       HandleReloc(RelEntry);
18476006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
18486006e091SSam Clegg       HandleReloc(RelEntry);
1849d934cb88SDan Gohman   }
1850d934cb88SDan Gohman 
1851bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1852bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1853bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
18547d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1855bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
18567d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1857bafe6902SSam Clegg       continue;
1858bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1859bafe6902SSam Clegg       continue;
1860b210c64bSSam Clegg 
1861b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1862b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1863bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1864b210c64bSSam Clegg 
1865b210c64bSSam Clegg     auto IT = WS.begin();
1866b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1867b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1868b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1869b210c64bSSam Clegg 
1870b210c64bSSam Clegg     IT = std::next(IT);
1871b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1872bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1873bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1874bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1875bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1876b210c64bSSam Clegg 
1877b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1878bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1879bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1880b210c64bSSam Clegg 
1881bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
18824d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
18837d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
18847d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1885f208f631SHeejin Ahn         report_fatal_error(
1886f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
18877d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1888bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1889bafe6902SSam Clegg     }
1890bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1891bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1892f208f631SHeejin Ahn     for (const uint8_t *
189318c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
189418c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
189518c56a07SHeejin Ahn          P != End; ++P) {
189618c56a07SHeejin Ahn       if (*P != 0)
1897bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1898bafe6902SSam Clegg     }
1899bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1900f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1901f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1902bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
19038fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
19048fffa1dfSSam Clegg       if (!SymRef)
1905bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
19068fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
19078fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
19083ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
19098fffa1dfSSam Clegg       if (!TargetSym.isFunction())
19108fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
191125d8e68bSSam Clegg       InitFuncs.push_back(
19128fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1913bafe6902SSam Clegg     }
1914bafe6902SSam Clegg   }
1915bafe6902SSam Clegg 
191618eafb6cSDan Gohman   // Write out the Wasm header.
191718eafb6cSDan Gohman   writeHeader(Asm);
191818eafb6cSDan Gohman 
19190ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
19200ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1921da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1922f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
19239e15f359SSam Clegg     writeFunctionSection(Functions);
1924d823cc7cSAndy Wingo     writeTableSection(Tables);
1925f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
19263ec1760dSHeejin Ahn     writeTagSection(TagTypes);
19270a6c4d8dSSam Clegg     writeGlobalSection(Globals);
19289e15f359SSam Clegg     writeExportSection(Exports);
1929a5a3659dSAndy Wingo     const MCSymbol *IndirectFunctionTable =
1930a5a3659dSAndy Wingo         Asm.getContext().lookupSymbol("__indirect_function_table");
1931a5a3659dSAndy Wingo     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1932a5a3659dSAndy Wingo                      TableElems);
1933fef8de66SThomas Lively     writeDataCountSection();
19340ff28fa6SDerek Schuff 
19350ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
19360ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
19370ff28fa6SDerek Schuff   }
19380ff28fa6SDerek Schuff 
19390a391060SDerek Schuff   // The Sections in the COMDAT list have placeholder indices (their index among
19400a391060SDerek Schuff   // custom sections, rather than among all sections). Fix them up here.
19410a391060SDerek Schuff   for (auto &Group : Comdats) {
19420a391060SDerek Schuff     for (auto &Entry : Group.second) {
19430a391060SDerek Schuff       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
19440a391060SDerek Schuff         Entry.Index += SectionCount;
19450ff28fa6SDerek Schuff       }
19460a391060SDerek Schuff     }
19470a391060SDerek Schuff   }
19480a391060SDerek Schuff   for (auto &CustomSection : CustomSections)
19490a391060SDerek Schuff     writeCustomSection(CustomSection, Asm, Layout);
19500ff28fa6SDerek Schuff 
19510ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1952c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
19530ff28fa6SDerek Schuff 
19546f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
19556f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
19560ff28fa6SDerek Schuff   }
19576a31a0d6SSam Clegg   writeCustomRelocSections();
1958cbda16ebSThomas Lively   if (ProducersSection)
1959cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1960f6f4f843SThomas Lively   if (TargetFeaturesSection)
1961f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1962970d02c4SDan Gohman 
1963d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
19640ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
196518eafb6cSDan Gohman }
196618eafb6cSDan Gohman 
196760fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
19681301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
196918eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
19700eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
197118eafb6cSDan Gohman }
19720ff28fa6SDerek Schuff 
19730ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
19740ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
19750ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
19760ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
19770ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
19780ff28fa6SDerek Schuff }
1979