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"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.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 "llvm/Support/StringSaver.h"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
385e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3918eafb6cSDan Gohman 
4018eafb6cSDan Gohman namespace {
419e15f359SSam Clegg 
4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4418c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4530e1bbc1SSam Clegg 
46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
48d934cb88SDan Gohman // locations within the section.
49d934cb88SDan Gohman struct SectionBookkeeping {
50d934cb88SDan Gohman   // Where the size of the section is written.
51d934cb88SDan Gohman   uint64_t SizeOffset;
526a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
536a31a0d6SSam Clegg   uint64_t PayloadOffset;
546a31a0d6SSam Clegg   // Where the contents of the section starts.
55d934cb88SDan Gohman   uint64_t ContentsOffset;
566f08c84aSSam Clegg   uint32_t Index;
57d934cb88SDan Gohman };
58d934cb88SDan Gohman 
59da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
60da419bdbSHeejin Ahn // as a DenseMap key.
61da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
62da419bdbSHeejin Ahn struct WasmSignature {
639e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6418c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
659e15f359SSam Clegg 
669e15f359SSam Clegg   // The return types of the function.
679e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
689e15f359SSam Clegg 
699e15f359SSam Clegg   // The parameter types of the function.
709e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
719e15f359SSam Clegg 
72da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
739e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
749e15f359SSam Clegg            Params == Other.Params;
759e15f359SSam Clegg   }
769e15f359SSam Clegg };
779e15f359SSam Clegg 
78da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
79da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
80da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
81da419bdbSHeejin Ahn     WasmSignature Sig;
82da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
83da419bdbSHeejin Ahn     return Sig;
849e15f359SSam Clegg   }
85da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
86da419bdbSHeejin Ahn     WasmSignature Sig;
87da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
88da419bdbSHeejin Ahn     return Sig;
899e15f359SSam Clegg   }
90da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
91da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
92da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
934808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
94da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
954808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
969e15f359SSam Clegg     return Value;
979e15f359SSam Clegg   }
98da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
999e15f359SSam Clegg     return LHS == RHS;
1009e15f359SSam Clegg   }
1019e15f359SSam Clegg };
1029e15f359SSam Clegg 
1037c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1047c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1057c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1067c395943SSam Clegg // wasm data segment.
1077c395943SSam Clegg struct WasmDataSegment {
1087c395943SSam Clegg   MCSectionWasm *Section;
109d95ed959SSam Clegg   StringRef Name;
1102e150409SThomas Lively   uint32_t InitFlags;
1117c395943SSam Clegg   uint32_t Offset;
11263ebb813SSam Clegg   uint32_t Alignment;
1132e150409SThomas Lively   uint32_t LinkerFlags;
1147c395943SSam Clegg   SmallVector<char, 4> Data;
1157c395943SSam Clegg };
1167c395943SSam Clegg 
1179e15f359SSam Clegg // A wasm function to be written into the function section.
1189e15f359SSam Clegg struct WasmFunction {
119da419bdbSHeejin Ahn   uint32_t SigIndex;
1209e15f359SSam Clegg   const MCSymbolWasm *Sym;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm global to be written into the global section.
1249e15f359SSam Clegg struct WasmGlobal {
1256e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1269e15f359SSam Clegg   uint64_t InitialValue;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
131ea7caceeSSam Clegg // WasmComdatEntry.
132ea7caceeSSam Clegg struct WasmComdatEntry {
133ea7caceeSSam Clegg   unsigned Kind;
134ea7caceeSSam Clegg   uint32_t Index;
135ea7caceeSSam Clegg };
136ea7caceeSSam Clegg 
1376dc65e91SSam Clegg // Information about a single relocation.
1386dc65e91SSam Clegg struct WasmRelocationEntry {
1396dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1406dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1416dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1426dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
143fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1446dc65e91SSam Clegg 
1456dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1466dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
147fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1486dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1496dc65e91SSam Clegg         FixupSection(FixupSection) {}
1506dc65e91SSam Clegg 
151cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
152acd7d2b0SSam Clegg 
1536dc65e91SSam Clegg   void print(raw_ostream &Out) const {
154f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
155f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1567d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1576dc65e91SSam Clegg   }
158b7787fd0SSam Clegg 
159615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161b7787fd0SSam Clegg #endif
1626dc65e91SSam Clegg };
1636dc65e91SSam Clegg 
16418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
16525d8e68bSSam Clegg 
166cfd44a2eSSam Clegg struct WasmCustomSection {
167cfd44a2eSSam Clegg 
1686a31a0d6SSam Clegg   StringRef Name;
1696a31a0d6SSam Clegg   MCSectionWasm *Section;
1706a31a0d6SSam Clegg 
1716a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1726a31a0d6SSam Clegg   uint32_t OutputIndex;
1736a31a0d6SSam Clegg 
1746a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1756a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
17618c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
177cfd44a2eSSam Clegg };
178cfd44a2eSSam Clegg 
1791fb8daa6SSam Clegg #if !defined(NDEBUG)
1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181b7787fd0SSam Clegg   Rel.print(OS);
182b7787fd0SSam Clegg   return OS;
183b7787fd0SSam Clegg }
1841fb8daa6SSam Clegg #endif
185b7787fd0SSam Clegg 
18619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
18719e8befaSSam Clegg // to allow patching.
188*3b29376eSWouter van Oortmerssen template <int W>
189*3b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
190*3b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
191*3b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
192*3b29376eSWouter van Oortmerssen   assert(SizeLen == W);
19319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
19419e8befaSSam Clegg }
19519e8befaSSam Clegg 
19619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
19719e8befaSSam Clegg // to allow patching.
198*3b29376eSWouter van Oortmerssen template <int W>
199*3b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
200*3b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
201*3b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
202*3b29376eSWouter van Oortmerssen   assert(SizeLen == W);
20319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20419e8befaSSam Clegg }
20519e8befaSSam Clegg 
20619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
2070a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
20819e8befaSSam Clegg   uint8_t Buffer[4];
20919e8befaSSam Clegg   support::endian::write32le(Buffer, X);
21019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
21119e8befaSSam Clegg }
21219e8befaSSam Clegg 
213*3b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
214*3b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
215*3b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
216*3b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
217*3b29376eSWouter van Oortmerssen }
218*3b29376eSWouter van Oortmerssen 
21918eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
220f17b149dSPeter Collingbourne   support::endian::Writer W;
221f17b149dSPeter Collingbourne 
22218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22418eafb6cSDan Gohman 
225d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
226d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2276f08c84aSSam Clegg   uint32_t CodeSectionIndex;
228d934cb88SDan Gohman 
229d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
230d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2316f08c84aSSam Clegg   uint32_t DataSectionIndex;
232d934cb88SDan Gohman 
233d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
234acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
235acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
236d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
237d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
238f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
239da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
240da419bdbSHeejin Ahn   // space.
2416c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
242492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2436c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2446c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2456a31a0d6SSam Clegg 
2466a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2476a31a0d6SSam Clegg   // section.
2486a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
249cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
250f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2516a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2526a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2536a31a0d6SSam Clegg       CustomSectionsRelocations;
254acd7d2b0SSam Clegg 
255c0d41195SSam Clegg   // Map from section to defining function symbol.
2566ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2576ccb59b3SSam Clegg 
258da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
259da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2606c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2619f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2627c395943SSam Clegg   unsigned NumGlobalImports = 0;
263da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2647e1c3345SChandler Carruth   uint32_t SectionCount = 0;
265d934cb88SDan Gohman 
26618eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26718eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
268da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
26918eafb6cSDan Gohman 
2702322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2712322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
272d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
273d934cb88SDan Gohman 
27418eafb6cSDan Gohman public:
2751301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2761301a878SLang Hames                    raw_pwrite_stream &OS)
27759a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
27818eafb6cSDan Gohman 
2790917c9e4SDan Gohman private:
280acd7d2b0SSam Clegg   void reset() override {
281acd7d2b0SSam Clegg     CodeRelocations.clear();
282acd7d2b0SSam Clegg     DataRelocations.clear();
283acd7d2b0SSam Clegg     TypeIndices.clear();
2846c899ba6SSam Clegg     WasmIndices.clear();
285492f7529SSam Clegg     GOTIndices.clear();
286f9edbe95SSam Clegg     TableIndices.clear();
2876c899ba6SSam Clegg     DataLocations.clear();
288cbda16ebSThomas Lively     CustomSections.clear();
289cbda16ebSThomas Lively     ProducersSection.reset();
290f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2916a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
292da419bdbSHeejin Ahn     SignatureIndices.clear();
293da419bdbSHeejin Ahn     Signatures.clear();
2946c899ba6SSam Clegg     DataSegments.clear();
2956ccb59b3SSam Clegg     SectionFunctions.clear();
2969f3fe42eSSam Clegg     NumFunctionImports = 0;
2977c395943SSam Clegg     NumGlobalImports = 0;
298105bdc25SSam Clegg     MCObjectWriter::reset();
299acd7d2b0SSam Clegg   }
300acd7d2b0SSam Clegg 
30118eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30218eafb6cSDan Gohman 
30318eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30418eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
305ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30618eafb6cSDan Gohman 
30718eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30818eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30918eafb6cSDan Gohman 
310438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3119e15f359SSam Clegg 
312b7787fd0SSam Clegg   void writeString(const StringRef Str) {
313f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
314f17b149dSPeter Collingbourne     W.OS << Str;
315b7787fd0SSam Clegg   }
316b7787fd0SSam Clegg 
3170a6c4d8dSSam Clegg   void writeI32(int32_t val) {
3180a6c4d8dSSam Clegg     char Buffer[4];
3190a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3200a6c4d8dSSam Clegg     W.OS.write(Buffer, sizeof(Buffer));
3210a6c4d8dSSam Clegg   }
3220a6c4d8dSSam Clegg 
3230a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3240a6c4d8dSSam Clegg     char Buffer[8];
3250a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3260a6c4d8dSSam Clegg     W.OS.write(Buffer, sizeof(Buffer));
3270a6c4d8dSSam Clegg   }
3280a6c4d8dSSam Clegg 
329f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3309e15f359SSam Clegg 
331da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3328defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
333f950b24aSSam Clegg                           uint32_t NumElements);
334457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3358defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
336457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
337fef8de66SThomas Lively   void writeDataCountSection();
3389e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
339457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3406c899ba6SSam Clegg   void writeDataSection();
341da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3420a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
3436f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
344f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
34531a2c809SSam Clegg   void writeLinkingMetaDataSection(
34686b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
347ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
348ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
349cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
350cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3516a31a0d6SSam Clegg   void writeCustomRelocSections();
3526a31a0d6SSam Clegg   void
3536a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3546a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
355acd7d2b0SSam Clegg 
356*3b29376eSWouter van Oortmerssen   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
357acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
358acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
359acd7d2b0SSam Clegg 
360acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3615e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
362da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
36338b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
36438b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
36518eafb6cSDan Gohman };
3669e15f359SSam Clegg 
36718eafb6cSDan Gohman } // end anonymous namespace
36818eafb6cSDan Gohman 
369d934cb88SDan Gohman // Write out a section header and a patchable section size field.
370d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3712322a937SSam Clegg                                     unsigned SectionId) {
372d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
373f17b149dSPeter Collingbourne   W.OS << char(SectionId);
374d934cb88SDan Gohman 
375f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
376d934cb88SDan Gohman 
377d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
378d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
37919e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
380d934cb88SDan Gohman 
381d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
382f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
383f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3846f08c84aSSam Clegg   Section.Index = SectionCount++;
385d934cb88SDan Gohman }
3862322a937SSam Clegg 
3872322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3882322a937SSam Clegg                                           StringRef Name) {
389d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3902322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3916a31a0d6SSam Clegg 
3926a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
393f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3946a31a0d6SSam Clegg 
3952322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3962322a937SSam Clegg   writeString(Name);
3976a31a0d6SSam Clegg 
3986a31a0d6SSam Clegg   // The position where the custom section starts.
399f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
400d934cb88SDan Gohman }
401d934cb88SDan Gohman 
402d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
403d934cb88SDan Gohman // section size field at the start of the section.
404d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
405c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
406c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
407c0affde8SSam Clegg   // Simply skip this patching in that case.
408c0affde8SSam Clegg   if (!Size)
409c0affde8SSam Clegg     return;
410c0affde8SSam Clegg 
411c0affde8SSam Clegg   Size -= Section.PayloadOffset;
412d934cb88SDan Gohman   if (uint32_t(Size) != Size)
413d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
414d934cb88SDan Gohman 
415d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
416d934cb88SDan Gohman 
417d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
418d934cb88SDan Gohman   // the section id byte.
419*3b29376eSWouter van Oortmerssen   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W.OS), Size,
420f17b149dSPeter Collingbourne                        Section.SizeOffset);
421d934cb88SDan Gohman }
422d934cb88SDan Gohman 
42318eafb6cSDan Gohman // Emit the Wasm header.
42418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
425f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
426f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
42718eafb6cSDan Gohman }
42818eafb6cSDan Gohman 
42918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
43018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4316ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4326ccb59b3SSam Clegg   // in recordRelocation.
4336ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4346ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4356ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4366ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4376ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4386ccb59b3SSam Clegg       if (!Pair.second)
4396ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4407d1ff446SFangrui Song                            Sec.getName());
4416ccb59b3SSam Clegg     }
4426ccb59b3SSam Clegg   }
44318eafb6cSDan Gohman }
44418eafb6cSDan Gohman 
44518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
44618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
44718eafb6cSDan Gohman                                         const MCFragment *Fragment,
44818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
449ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
450ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
451e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
452ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
453ecc5e808SSam Clegg 
454fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
455d934cb88SDan Gohman   uint64_t C = Target.getConstant();
456d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
457d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
458d934cb88SDan Gohman 
459d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
460ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
461ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
462ecc5e808SSam Clegg     // support either of those cases.
463ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
464d934cb88SDan Gohman     Ctx.reportError(
465d934cb88SDan Gohman         Fixup.getLoc(),
466d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
467ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
468d934cb88SDan Gohman     return;
469d934cb88SDan Gohman   }
470d934cb88SDan Gohman 
471d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
472d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
473ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
474d934cb88SDan Gohman 
4753ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4767d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4773ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4783ea1c62cSSam Clegg     return;
4793ea1c62cSSam Clegg   }
4803ea1c62cSSam Clegg 
481ecc5e808SSam Clegg   if (SymA->isVariable()) {
482d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4836ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4846ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4856ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
486d934cb88SDan Gohman   }
487d934cb88SDan Gohman 
488d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
489d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
490d934cb88SDan Gohman   // be negative and don't wrap.
491d934cb88SDan Gohman   FixedValue = 0;
492d934cb88SDan Gohman 
493a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4949d24fb7fSSam Clegg 
4954d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4964d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4974d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
498d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
499d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
5004d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5014d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5024d57fbd0SSam Clegg                          "only supported in metadata sections");
5034d57fbd0SSam Clegg 
5044d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5054d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5064d57fbd0SSam Clegg     if (SecA.getKind().isText())
5076ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
5084d57fbd0SSam Clegg     else
5094d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5104d57fbd0SSam Clegg     if (!SectionSymbol)
5114d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5124d57fbd0SSam Clegg 
5134d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5144d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5154d57fbd0SSam Clegg   }
5164d57fbd0SSam Clegg 
517d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5184d57fbd0SSam Clegg   // against a named symbol.
519d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5204d57fbd0SSam Clegg     if (SymA->getName().empty())
5214d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5224d57fbd0SSam Clegg                          "supported by wasm");
5234d57fbd0SSam Clegg 
5244d57fbd0SSam Clegg     SymA->setUsedInReloc();
5254d57fbd0SSam Clegg   }
526ae03c1e7SSam Clegg 
527492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
528492f7529SSam Clegg     SymA->setUsedInGOT();
529492f7529SSam Clegg 
530d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
531d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
532d934cb88SDan Gohman 
5336a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
534d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5356a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
53612fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5376a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5386a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5396a31a0d6SSam Clegg   } else {
54012fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
541d934cb88SDan Gohman   }
5426a31a0d6SSam Clegg }
543d934cb88SDan Gohman 
54418c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
545ffba00bdSSam Clegg   const MCSymbolWasm* Ret = &Symbol;
546ffba00bdSSam Clegg   while (Ret->isVariable()) {
547ffba00bdSSam Clegg     const MCExpr *Expr = Ret->getVariableValue();
548aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
549ffba00bdSSam Clegg     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
550aff1c4dfSSam Clegg   }
551ffba00bdSSam Clegg   return Ret;
552aff1c4dfSSam Clegg }
553aff1c4dfSSam Clegg 
554d934cb88SDan Gohman // Compute a value to write into the code at the location covered
55560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
55660ec3034SSam Clegg // to make the object format more readable and more likely to be directly
55760ec3034SSam Clegg // useable.
558*3b29376eSWouter van Oortmerssen uint64_t
5597c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
56048139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
56148139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
56248139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
563492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
564492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
565492f7529SSam Clegg   }
566492f7529SSam Clegg 
56760ec3034SSam Clegg   switch (RelEntry.Type) {
5682a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
569d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
570d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_I32: {
571f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
57218c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
573f9edbe95SSam Clegg     assert(Sym->isFunction());
57481443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
57581443ac1SSam Clegg       return TableIndices[Sym] - InitialTableOffset;
57681443ac1SSam Clegg     else
577f9edbe95SSam Clegg       return TableIndices[Sym];
578f9edbe95SSam Clegg   }
579d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5806c899ba6SSam Clegg     // Provisional value is same as the index
58160ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
582d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
583d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
58448139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
585d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
586da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
587492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5886c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
589d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
590d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5916a31a0d6SSam Clegg     const auto &Section =
5926a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5936a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5946a31a0d6SSam Clegg   }
595d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
596*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
597*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
598*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5992a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
600*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
601*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
602*3b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I64: {
603f9edbe95SSam Clegg     // Provisional value is address of the global
60418c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
605270ed1b3SSam Clegg     // For undefined symbols, use zero
606cd65f698SSam Clegg     if (!Sym->isDefined())
607270ed1b3SSam Clegg       return 0;
6086c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6096c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
610d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6116c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61260ec3034SSam Clegg   }
61360ec3034SSam Clegg   default:
61460ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61560ec3034SSam Clegg   }
616d934cb88SDan Gohman }
617d934cb88SDan Gohman 
618759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
61963ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6207d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
621759631c7SSam Clegg 
62263ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62363ebb813SSam Clegg 
624759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
625759631c7SSam Clegg     if (Frag.hasInstructions())
626759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
627759631c7SSam Clegg 
628759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
629759631c7SSam Clegg       if (Align->getValueSize() != 1)
630759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
631759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
632759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
633f208f631SHeejin Ahn       uint64_t Size =
634f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
635f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
636759631c7SSam Clegg       DataBytes.resize(Size, Value);
637759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
638588fad4dSNirav Dave       int64_t NumValues;
639588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
640d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
641588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
642588fad4dSNirav Dave                        Fill->getValue());
64324faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
64424faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
64524faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
646759631c7SSam Clegg     } else {
647759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
648759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
649759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
650759631c7SSam Clegg     }
651759631c7SSam Clegg   }
652759631c7SSam Clegg 
653d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
654759631c7SSam Clegg }
655759631c7SSam Clegg 
65660ec3034SSam Clegg uint32_t
65760ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
658d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
659b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
660b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
661b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
662acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
663acd7d2b0SSam Clegg   }
66460ec3034SSam Clegg 
66525d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
666acd7d2b0SSam Clegg }
667acd7d2b0SSam Clegg 
668d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
669d934cb88SDan Gohman // directly.
670acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
671acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
672f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
673d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
674d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
675d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
676d934cb88SDan Gohman                       RelEntry.Offset;
677d934cb88SDan Gohman 
678d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
679*3b29376eSWouter van Oortmerssen     auto Value = getProvisionalValue(RelEntry);
68060ec3034SSam Clegg 
681acd7d2b0SSam Clegg     switch (RelEntry.Type) {
682d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
683d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
684d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
685d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
686d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
687*3b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
688*3b29376eSWouter van Oortmerssen       break;
689*3b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
690*3b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
691d934cb88SDan Gohman       break;
692d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
693d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
694d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
695d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
69648139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6970a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
698d934cb88SDan Gohman       break;
699*3b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
700*3b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
701*3b29376eSWouter van Oortmerssen       break;
702d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7032a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
704d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7052a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
706*3b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
707*3b29376eSWouter van Oortmerssen       break;
708*3b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
709*3b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
710*3b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
71160ec3034SSam Clegg       break;
712d934cb88SDan Gohman     default:
7139d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
714d934cb88SDan Gohman     }
715d934cb88SDan Gohman   }
71618eafb6cSDan Gohman }
71718eafb6cSDan Gohman 
718da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
719da419bdbSHeejin Ahn   if (Signatures.empty())
7209e15f359SSam Clegg     return;
7219e15f359SSam Clegg 
7229e15f359SSam Clegg   SectionBookkeeping Section;
7239e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7249e15f359SSam Clegg 
725da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
7269e15f359SSam Clegg 
727da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
728f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
729da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
730da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7319e15f359SSam Clegg       writeValueType(Ty);
732da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
733da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7349e15f359SSam Clegg       writeValueType(Ty);
7359e15f359SSam Clegg   }
7369e15f359SSam Clegg 
7379e15f359SSam Clegg   endSection(Section);
7389e15f359SSam Clegg }
7399e15f359SSam Clegg 
7408defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
741f950b24aSSam Clegg                                           uint32_t DataSize,
742f950b24aSSam Clegg                                           uint32_t NumElements) {
7439e15f359SSam Clegg   if (Imports.empty())
7449e15f359SSam Clegg     return;
7459e15f359SSam Clegg 
746f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
747f950b24aSSam Clegg 
7489e15f359SSam Clegg   SectionBookkeeping Section;
7499e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7509e15f359SSam Clegg 
751f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7528defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7538defa952SSam Clegg     writeString(Import.Module);
7548defa952SSam Clegg     writeString(Import.Field);
755f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7569e15f359SSam Clegg 
7579e15f359SSam Clegg     switch (Import.Kind) {
7589e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
759f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7609e15f359SSam Clegg       break;
7619e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
762f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
763f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7649e15f359SSam Clegg       break;
765f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
766f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
767f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
768f950b24aSSam Clegg       break;
769f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
770f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
771f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
772f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
773f950b24aSSam Clegg       break;
774da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
775da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
776da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
777da419bdbSHeejin Ahn       break;
7789e15f359SSam Clegg     default:
7799e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7809e15f359SSam Clegg     }
7819e15f359SSam Clegg   }
7829e15f359SSam Clegg 
7839e15f359SSam Clegg   endSection(Section);
7849e15f359SSam Clegg }
7859e15f359SSam Clegg 
786457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7879e15f359SSam Clegg   if (Functions.empty())
7889e15f359SSam Clegg     return;
7899e15f359SSam Clegg 
7909e15f359SSam Clegg   SectionBookkeeping Section;
7919e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7929e15f359SSam Clegg 
793f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7949e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
795da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7969e15f359SSam Clegg 
7979e15f359SSam Clegg   endSection(Section);
7989e15f359SSam Clegg }
7999e15f359SSam Clegg 
800da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
801da419bdbSHeejin Ahn   if (Events.empty())
802da419bdbSHeejin Ahn     return;
803da419bdbSHeejin Ahn 
804da419bdbSHeejin Ahn   SectionBookkeeping Section;
805da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
806da419bdbSHeejin Ahn 
807da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
808da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
809da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
810da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
811da419bdbSHeejin Ahn   }
812da419bdbSHeejin Ahn 
813da419bdbSHeejin Ahn   endSection(Section);
814da419bdbSHeejin Ahn }
815da419bdbSHeejin Ahn 
8160a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8170a6c4d8dSSam Clegg   if (Globals.empty())
8180a6c4d8dSSam Clegg     return;
8190a6c4d8dSSam Clegg 
8200a6c4d8dSSam Clegg   SectionBookkeeping Section;
8210a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8220a6c4d8dSSam Clegg 
8230a6c4d8dSSam Clegg   encodeULEB128(Globals.size(), W.OS);
8240a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8250a6c4d8dSSam Clegg     encodeULEB128(Global.Type.Type, W.OS);
8260a6c4d8dSSam Clegg     W.OS << char(Global.Type.Mutable);
8270a6c4d8dSSam Clegg     W.OS << char(Global.InitExpr.Opcode);
8280a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8290a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8300a6c4d8dSSam Clegg       encodeSLEB128(0, W.OS);
8310a6c4d8dSSam Clegg       break;
8320a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8330a6c4d8dSSam Clegg       encodeSLEB128(0, W.OS);
8340a6c4d8dSSam Clegg       break;
8350a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8360a6c4d8dSSam Clegg       writeI32(0);
8370a6c4d8dSSam Clegg       break;
8380a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8390a6c4d8dSSam Clegg       writeI64(0);
8400a6c4d8dSSam Clegg       break;
8410a6c4d8dSSam Clegg     default:
8420a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8430a6c4d8dSSam Clegg     }
8440a6c4d8dSSam Clegg     W.OS << char(wasm::WASM_OPCODE_END);
8450a6c4d8dSSam Clegg   }
8460a6c4d8dSSam Clegg 
8470a6c4d8dSSam Clegg   endSection(Section);
8480a6c4d8dSSam Clegg }
8490a6c4d8dSSam Clegg 
8508defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8519e15f359SSam Clegg   if (Exports.empty())
8529e15f359SSam Clegg     return;
8539e15f359SSam Clegg 
8549e15f359SSam Clegg   SectionBookkeeping Section;
8559e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8569e15f359SSam Clegg 
857f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
8588defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8598defa952SSam Clegg     writeString(Export.Name);
860f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
861f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
8629e15f359SSam Clegg   }
8639e15f359SSam Clegg 
8649e15f359SSam Clegg   endSection(Section);
8659e15f359SSam Clegg }
8669e15f359SSam Clegg 
867457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8689e15f359SSam Clegg   if (TableElems.empty())
8699e15f359SSam Clegg     return;
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   SectionBookkeeping Section;
8729e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8739e15f359SSam Clegg 
874f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
875f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8769e15f359SSam Clegg 
8779e15f359SSam Clegg   // init expr for starting offset
878f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
87918c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
880f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8819e15f359SSam Clegg 
882f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8839e15f359SSam Clegg   for (uint32_t Elem : TableElems)
884f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8859e15f359SSam Clegg 
8869e15f359SSam Clegg   endSection(Section);
8879e15f359SSam Clegg }
8889e15f359SSam Clegg 
889fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
890fef8de66SThomas Lively   if (DataSegments.empty())
891fef8de66SThomas Lively     return;
892fef8de66SThomas Lively 
893fef8de66SThomas Lively   SectionBookkeeping Section;
894fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
895fef8de66SThomas Lively   encodeULEB128(DataSegments.size(), W.OS);
896fef8de66SThomas Lively   endSection(Section);
897fef8de66SThomas Lively }
898fef8de66SThomas Lively 
899457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
900457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
901457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
9029e15f359SSam Clegg   if (Functions.empty())
9039e15f359SSam Clegg     return;
9049e15f359SSam Clegg 
9059e15f359SSam Clegg   SectionBookkeeping Section;
9069e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9076f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
9089e15f359SSam Clegg 
909f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
9109e15f359SSam Clegg 
9119e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
912fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9139e15f359SSam Clegg 
9149e15f359SSam Clegg     int64_t Size = 0;
9159e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9169e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9179e15f359SSam Clegg 
918f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
919f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
920f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
9219e15f359SSam Clegg   }
9229e15f359SSam Clegg 
9239e15f359SSam Clegg   // Apply fixups.
924acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
9259e15f359SSam Clegg 
9269e15f359SSam Clegg   endSection(Section);
9279e15f359SSam Clegg }
9289e15f359SSam Clegg 
9296c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
9306c899ba6SSam Clegg   if (DataSegments.empty())
9317c395943SSam Clegg     return;
9329e15f359SSam Clegg 
9339e15f359SSam Clegg   SectionBookkeeping Section;
9349e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9356f08c84aSSam Clegg   DataSectionIndex = Section.Index;
9369e15f359SSam Clegg 
937f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
9387c395943SSam Clegg 
9396c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9402e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
9412e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
942f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
9432e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
944f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
945f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
946f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
9472e150409SThomas Lively     }
948f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
949f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
950f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
9517c395943SSam Clegg   }
9529e15f359SSam Clegg 
9539e15f359SSam Clegg   // Apply fixups.
9547c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
9559e15f359SSam Clegg 
9569e15f359SSam Clegg   endSection(Section);
9579e15f359SSam Clegg }
9589e15f359SSam Clegg 
9596f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9606f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
961f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9629e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9639e15f359SSam Clegg   // for descriptions of the reloc sections.
9649e15f359SSam Clegg 
965f77dc2a8SSam Clegg   if (Relocs.empty())
9669e15f359SSam Clegg     return;
9679e15f359SSam Clegg 
968f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
969f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
970f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
971f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
972f77dc2a8SSam Clegg   // not the sections order.
973efd94c56SFangrui Song   llvm::stable_sort(
974efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
975f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
976f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
977f77dc2a8SSam Clegg       });
978f77dc2a8SSam Clegg 
9799e15f359SSam Clegg   SectionBookkeeping Section;
9806f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9819e15f359SSam Clegg 
982f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
983f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
984f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
985f208f631SHeejin Ahn     uint64_t Offset =
986f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9876f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9889e15f359SSam Clegg 
989f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
990f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
991f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9926f08c84aSSam Clegg     if (RelEntry.hasAddend())
993f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9949e15f359SSam Clegg   }
9959e15f359SSam Clegg 
9969e15f359SSam Clegg   endSection(Section);
9979e15f359SSam Clegg }
9989e15f359SSam Clegg 
9996a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10006a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10016a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10026a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10036a31a0d6SSam Clegg   }
10046a31a0d6SSam Clegg }
10056a31a0d6SSam Clegg 
10069e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
100786b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1008ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1009ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10109e15f359SSam Clegg   SectionBookkeeping Section;
10112322a937SSam Clegg   startCustomSection(Section, "linking");
1012f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
10139e15f359SSam Clegg 
10146bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10156c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10166c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1017f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
10186c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1019f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
1020f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
10216c899ba6SSam Clegg       switch (Sym.Kind) {
10226c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10236c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1024da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1025f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
102629874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
102729874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10286c899ba6SSam Clegg           writeString(Sym.Name);
10296c899ba6SSam Clegg         break;
10306c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10316c899ba6SSam Clegg         writeString(Sym.Name);
10326c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1033f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
1034f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
1035f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
10366c899ba6SSam Clegg         }
10376c899ba6SSam Clegg         break;
10386a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10396a31a0d6SSam Clegg         const uint32_t SectionIndex =
10406a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
1041f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
10426a31a0d6SSam Clegg         break;
10436a31a0d6SSam Clegg       }
10446c899ba6SSam Clegg       default:
10456c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10466c899ba6SSam Clegg       }
1047b7787fd0SSam Clegg     }
1048b7787fd0SSam Clegg     endSection(SubSection);
1049b7787fd0SSam Clegg   }
10509e15f359SSam Clegg 
10516c899ba6SSam Clegg   if (DataSegments.size()) {
105263ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1053f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
10546c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1055d95ed959SSam Clegg       writeString(Segment.Name);
1056f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
10572e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
105863ebb813SSam Clegg     }
1059d95ed959SSam Clegg     endSection(SubSection);
1060d95ed959SSam Clegg   }
1061d95ed959SSam Clegg 
1062bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1063bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1064f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
1065bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1066f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
1067f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
1068bafe6902SSam Clegg     }
1069bafe6902SSam Clegg     endSection(SubSection);
1070bafe6902SSam Clegg   }
1071bafe6902SSam Clegg 
1072ea7caceeSSam Clegg   if (Comdats.size()) {
1073ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1074f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1075ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1076ea7caceeSSam Clegg       writeString(C.first);
1077f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1078f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1079ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1080f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1081f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1082ea7caceeSSam Clegg       }
1083ea7caceeSSam Clegg     }
1084ea7caceeSSam Clegg     endSection(SubSection);
1085ea7caceeSSam Clegg   }
1086ea7caceeSSam Clegg 
10879e15f359SSam Clegg   endSection(Section);
10889e15f359SSam Clegg }
10899e15f359SSam Clegg 
1090cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1091cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10926a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1093cfd44a2eSSam Clegg   SectionBookkeeping Section;
10946a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10952322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10966a31a0d6SSam Clegg 
1097f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1098f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
10996a31a0d6SSam Clegg 
11006a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11016a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11026a31a0d6SSam Clegg 
1103cfd44a2eSSam Clegg   endSection(Section);
11046a31a0d6SSam Clegg 
11056a31a0d6SSam Clegg   // Apply fixups.
11064d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11074d57fbd0SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
11086a31a0d6SSam Clegg }
11096a31a0d6SSam Clegg 
11105e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11115e3d33a7SSam Clegg   assert(Symbol.isFunction());
11125e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11135e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11145e3d33a7SSam Clegg }
11155e3d33a7SSam Clegg 
1116da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1117da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1118da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1119da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1120da419bdbSHeejin Ahn }
1121da419bdbSHeejin Ahn 
112238b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11235e3d33a7SSam Clegg   assert(Symbol.isFunction());
11245e3d33a7SSam Clegg 
1125da419bdbSHeejin Ahn   WasmSignature S;
112618c56a07SHeejin Ahn   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
112777a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
1128da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1129da419bdbSHeejin Ahn     S.Params = Sig->Params;
113077a7a380SDerek Schuff   }
11315e3d33a7SSam Clegg 
1132da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11335e3d33a7SSam Clegg   if (Pair.second)
1134da419bdbSHeejin Ahn     Signatures.push_back(S);
11355e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11365e3d33a7SSam Clegg 
1137d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1138d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1139d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11405e3d33a7SSam Clegg }
11415e3d33a7SSam Clegg 
114238b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1143da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1144da419bdbSHeejin Ahn 
1145da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1146da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1147da419bdbSHeejin Ahn   WasmSignature S;
1148da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1149da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1150da419bdbSHeejin Ahn     S.Params = Sig->Params;
1151da419bdbSHeejin Ahn   }
1152da419bdbSHeejin Ahn 
1153da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1154da419bdbSHeejin Ahn   if (Pair.second)
1155da419bdbSHeejin Ahn     Signatures.push_back(S);
1156da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1157da419bdbSHeejin Ahn 
1158da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1159da419bdbSHeejin Ahn                     << "\n");
1160da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1161da419bdbSHeejin Ahn }
1162da419bdbSHeejin Ahn 
11634d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11643ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11654d57fbd0SSam Clegg     return true;
11664d57fbd0SSam Clegg 
11674d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11684d57fbd0SSam Clegg     return false;
11694d57fbd0SSam Clegg 
11703ea1c62cSSam Clegg   if (Sym.isTemporary())
11714d57fbd0SSam Clegg     return false;
11724d57fbd0SSam Clegg 
11734d57fbd0SSam Clegg   if (Sym.isSection())
11744d57fbd0SSam Clegg     return false;
11754d57fbd0SSam Clegg 
11764d57fbd0SSam Clegg   return true;
11774d57fbd0SSam Clegg }
11784d57fbd0SSam Clegg 
1179438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
118018eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1181438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1182438390faSPeter Collingbourne 
1183d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1184d934cb88SDan Gohman 
1185d934cb88SDan Gohman   // Collect information from the available symbols.
1186d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1187d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11888defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11898defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1190da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11910a6c4d8dSSam Clegg   SmallVector<wasm::WasmGlobal, 1> Globals;
11926c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1193bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1194ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11957c395943SSam Clegg   uint32_t DataSize = 0;
1196d934cb88SDan Gohman 
1197f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1198f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1199f950b24aSSam Clegg   // it if there are no loads or stores.
12008defa952SSam Clegg   wasm::WasmImport MemImport;
12011ed3a046SSam Clegg   MemImport.Module = "env";
12021ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1203f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1204f950b24aSSam Clegg   Imports.push_back(MemImport);
1205f950b24aSSam Clegg 
1206f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1207f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1208f950b24aSSam Clegg   // it if there are no indirect calls.
12098defa952SSam Clegg   wasm::WasmImport TableImport;
12101ed3a046SSam Clegg   TableImport.Module = "env";
12111ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1212f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12136a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1214f950b24aSSam Clegg   Imports.push_back(TableImport);
1215f950b24aSSam Clegg 
1216da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1217586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1218586320c0SNicholas Wilson   // symbols.
121932ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
122032ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
122132ce5ca0SDan Gohman 
122232ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12239f3fe42eSSam Clegg     // (because wasm always needs a type signature).
122432ce5ca0SDan Gohman     if (WS.isFunction())
122532ce5ca0SDan Gohman       registerFunctionType(WS);
122632ce5ca0SDan Gohman 
1227da419bdbSHeejin Ahn     if (WS.isEvent())
1228da419bdbSHeejin Ahn       registerEventType(WS);
1229da419bdbSHeejin Ahn 
123032ce5ca0SDan Gohman     if (WS.isTemporary())
123132ce5ca0SDan Gohman       continue;
123232ce5ca0SDan Gohman 
123332ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12346c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12356c899ba6SSam Clegg       if (WS.isFunction()) {
12368defa952SSam Clegg         wasm::WasmImport Import;
1237f726e445SDan Gohman         Import.Module = WS.getImportModule();
1238f726e445SDan Gohman         Import.Field = WS.getImportName();
123932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12408defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12416c899ba6SSam Clegg         Imports.push_back(Import);
1242492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12436c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12446c899ba6SSam Clegg       } else if (WS.isGlobal()) {
124515f349f7SNicholas Wilson         if (WS.isWeak())
124615f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
124715f349f7SNicholas Wilson 
12486c899ba6SSam Clegg         wasm::WasmImport Import;
1249f726e445SDan Gohman         Import.Field = WS.getImportName();
125032ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1251492f7529SSam Clegg         Import.Module = WS.getImportModule();
12526c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12536c899ba6SSam Clegg         Imports.push_back(Import);
1254492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12556c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1256da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1257da419bdbSHeejin Ahn         if (WS.isWeak())
1258da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1259da419bdbSHeejin Ahn 
1260da419bdbSHeejin Ahn         wasm::WasmImport Import;
1261f726e445SDan Gohman         Import.Module = WS.getImportModule();
1262f726e445SDan Gohman         Import.Field = WS.getImportName();
1263da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1264da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1265da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1266da419bdbSHeejin Ahn         Imports.push_back(Import);
1267492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1268da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
126932ce5ca0SDan Gohman       }
127032ce5ca0SDan Gohman     }
127132ce5ca0SDan Gohman   }
127232ce5ca0SDan Gohman 
1273492f7529SSam Clegg   // Add imports for GOT globals
1274492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1275492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1276492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1277492f7529SSam Clegg       wasm::WasmImport Import;
1278492f7529SSam Clegg       if (WS.isFunction())
1279492f7529SSam Clegg         Import.Module = "GOT.func";
1280492f7529SSam Clegg       else
1281492f7529SSam Clegg         Import.Module = "GOT.mem";
1282492f7529SSam Clegg       Import.Field = WS.getName();
1283492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1284492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1285492f7529SSam Clegg       Imports.push_back(Import);
1286492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1287492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1288492f7529SSam Clegg     }
1289492f7529SSam Clegg   }
1290492f7529SSam Clegg 
12914d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12924d57fbd0SSam Clegg   // populating DataLocations.
1293759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1294759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
12957d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1296759631c7SSam Clegg 
1297bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
12984d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1299bafe6902SSam Clegg       continue;
1300bafe6902SSam Clegg 
13014d57fbd0SSam Clegg     // Code is handled separately
13024d57fbd0SSam Clegg     if (Section.getKind().isText())
13034d57fbd0SSam Clegg       continue;
13044d57fbd0SSam Clegg 
13054d57fbd0SSam Clegg     if (Section.isWasmData()) {
1306329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1307759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1308759631c7SSam Clegg       DataSegments.emplace_back();
1309759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13104d57fbd0SSam Clegg       Segment.Name = SectionName;
13119b49f36aSSimon Pilgrim       Segment.InitFlags =
13129b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1313759631c7SSam Clegg       Segment.Offset = DataSize;
1314759631c7SSam Clegg       Segment.Section = &Section;
131563ebb813SSam Clegg       addData(Segment.Data, Section);
131656c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13172e150409SThomas Lively       Segment.LinkerFlags = 0;
1318759631c7SSam Clegg       DataSize += Segment.Data.size();
13196c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1320ea7caceeSSam Clegg 
1321ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1322ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1323329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1324ea7caceeSSam Clegg       }
13254d57fbd0SSam Clegg     } else {
13264d57fbd0SSam Clegg       // Create custom sections
13274d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13284d57fbd0SSam Clegg 
13294d57fbd0SSam Clegg       StringRef Name = SectionName;
13304d57fbd0SSam Clegg 
13314d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13324d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13334d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13344d57fbd0SSam Clegg 
13354d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1336fb807d4dSSam Clegg       if (Begin) {
13374d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1338b210c64bSSam Clegg         if (SectionName != Begin->getName())
1339fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1340b210c64bSSam Clegg                              Twine(SectionName));
1341fb807d4dSSam Clegg       }
1342cbda16ebSThomas Lively 
1343f6f4f843SThomas Lively       // Separate out the producers and target features sections
1344cbda16ebSThomas Lively       if (Name == "producers") {
13450eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1346cbda16ebSThomas Lively         continue;
1347cbda16ebSThomas Lively       }
1348f6f4f843SThomas Lively       if (Name == "target_features") {
1349f6f4f843SThomas Lively         TargetFeaturesSection =
13500eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1351f6f4f843SThomas Lively         continue;
1352f6f4f843SThomas Lively       }
1353cbda16ebSThomas Lively 
13544d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1355759631c7SSam Clegg     }
13566a31a0d6SSam Clegg   }
13576a31a0d6SSam Clegg 
1358586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1359d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1360d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1361d934cb88SDan Gohman     // or used in relocations.
1362d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1363d934cb88SDan Gohman       continue;
1364b7787fd0SSam Clegg 
1365d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1366d34e60caSNicola Zaghen     LLVM_DEBUG(
1367d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1368d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1369d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1370d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1371b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1372b7787fd0SSam Clegg 
13735e3d33a7SSam Clegg     if (WS.isVariable())
13745e3d33a7SSam Clegg       continue;
13756c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13766c899ba6SSam Clegg       continue;
1377b7787fd0SSam Clegg 
1378d934cb88SDan Gohman     if (WS.isFunction()) {
13796c899ba6SSam Clegg       unsigned Index;
1380cd65f698SSam Clegg       if (WS.isDefined()) {
1381b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1382b7787fd0SSam Clegg           report_fatal_error(
1383b7787fd0SSam Clegg               "function sections must contain one function each");
1384b7787fd0SSam Clegg 
138518c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1386b7787fd0SSam Clegg           report_fatal_error(
1387b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1388b7787fd0SSam Clegg 
13896c899ba6SSam Clegg         // A definition. Write out the function body.
13909f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1391d934cb88SDan Gohman         WasmFunction Func;
1392da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1393d934cb88SDan Gohman         Func.Sym = &WS;
13946c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1395d934cb88SDan Gohman         Functions.push_back(Func);
13966c899ba6SSam Clegg 
13976c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13986c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
13996c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14006c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14016c899ba6SSam Clegg         }
1402881d8778SSam Clegg 
1403881d8778SSam Clegg         if (WS.hasExportName()) {
1404881d8778SSam Clegg           wasm::WasmExport Export;
1405881d8778SSam Clegg           Export.Name = WS.getExportName();
1406881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1407881d8778SSam Clegg           Export.Index = Index;
1408881d8778SSam Clegg           Exports.push_back(Export);
1409881d8778SSam Clegg         }
1410d934cb88SDan Gohman       } else {
1411d934cb88SDan Gohman         // An import; the index was assigned above.
14126c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1413d934cb88SDan Gohman       }
1414d934cb88SDan Gohman 
1415d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1416da419bdbSHeejin Ahn 
14176c899ba6SSam Clegg     } else if (WS.isData()) {
1418f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1419c38e947eSSam Clegg         continue;
1420c38e947eSSam Clegg 
14216c899ba6SSam Clegg       if (!WS.isDefined()) {
1422d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1423d34e60caSNicola Zaghen                           << "\n");
1424fe6414b0SSam Clegg         continue;
14256c899ba6SSam Clegg       }
1426fe6414b0SSam Clegg 
1427d934cb88SDan Gohman       if (!WS.getSize())
1428c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1429c38e947eSSam Clegg                            WS.getName());
1430d934cb88SDan Gohman 
1431d934cb88SDan Gohman       int64_t Size = 0;
1432d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1433d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1434d934cb88SDan Gohman 
1435759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1436079cba04SSam Clegg       if (!DataSection.isWasmData())
1437079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1438079cba04SSam Clegg                            WS.getName());
14397c395943SSam Clegg 
14406c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14416c899ba6SSam Clegg       // corresponding Wasm data segment.
14426c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1443*3b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1444*3b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14456c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1446d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1447da419bdbSHeejin Ahn 
1448a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14496c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14500a6c4d8dSSam Clegg       if (WS.isDefined()) {
14510a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14520a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14530a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14540a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
14550a6c4d8dSSam Clegg         switch (Global.Type.Type) {
14560a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
14570a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
14580a6c4d8dSSam Clegg           break;
14590a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
14600a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
14610a6c4d8dSSam Clegg           break;
14620a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
14630a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
14640a6c4d8dSSam Clegg           break;
14650a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
14660a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
14670a6c4d8dSSam Clegg           break;
14680a6c4d8dSSam Clegg         default:
14690a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
14700a6c4d8dSSam Clegg         }
14710a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
14720a6c4d8dSSam Clegg         Globals.push_back(Global);
14730a6c4d8dSSam Clegg       } else {
1474545932beSEric Christopher         // An import; the index was assigned above
1475d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1476d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
14770a6c4d8dSSam Clegg       }
1478da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1479da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1480da419bdbSHeejin Ahn       unsigned Index;
1481da419bdbSHeejin Ahn       if (WS.isDefined()) {
14820a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1483da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1484da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1485da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1486da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1487da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1488da419bdbSHeejin Ahn         Events.push_back(Event);
1489da419bdbSHeejin Ahn       } else {
1490da419bdbSHeejin Ahn         // An import; the index was assigned above.
1491492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1492da419bdbSHeejin Ahn       }
1493da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1494da419bdbSHeejin Ahn                         << "\n");
1495da419bdbSHeejin Ahn 
1496a165f2d6SSam Clegg     } else {
1497a165f2d6SSam Clegg       assert(WS.isSection());
1498d934cb88SDan Gohman     }
1499d934cb88SDan Gohman   }
1500d934cb88SDan Gohman 
1501586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1502586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1503586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1504586320c0SNicholas Wilson   // necessarily ordered in this way.
1505b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1506b7787fd0SSam Clegg     if (!S.isVariable())
1507b7787fd0SSam Clegg       continue;
150831a2c809SSam Clegg 
1509cd65f698SSam Clegg     assert(S.isDefined());
1510b7787fd0SSam Clegg 
15115e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1512aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
151318c56a07SHeejin Ahn     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1514d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1515d34e60caSNicola Zaghen                       << "'\n");
1516b7787fd0SSam Clegg 
1517ffba00bdSSam Clegg     if (ResolvedSym->isFunction()) {
15186c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
15196c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1520492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15216c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1522d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1523ffba00bdSSam Clegg     } else if (ResolvedSym->isData()) {
15246c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
15256c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
15266c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
15276c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1528d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
15296c899ba6SSam Clegg     } else {
1530da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
15316c899ba6SSam Clegg     }
1532586320c0SNicholas Wilson   }
153331a2c809SSam Clegg 
1534586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1535586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1536586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
153725d8e68bSSam Clegg     if (!isInSymtab(WS)) {
153818c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1539586320c0SNicholas Wilson       continue;
154025d8e68bSSam Clegg     }
1541d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1542586320c0SNicholas Wilson 
1543586320c0SNicholas Wilson     uint32_t Flags = 0;
1544586320c0SNicholas Wilson     if (WS.isWeak())
1545586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1546586320c0SNicholas Wilson     if (WS.isHidden())
1547586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1548586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1549586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1550586320c0SNicholas Wilson     if (WS.isUndefined())
1551586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1552da84b688SDan Gohman     if (WS.isNoStrip()) {
1553da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1554da84b688SDan Gohman       if (isEmscripten()) {
1555d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1556da84b688SDan Gohman       }
1557da84b688SDan Gohman     }
1558b4f4e370SSam Clegg     if (WS.hasImportName())
155929874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1560881d8778SSam Clegg     if (WS.hasExportName())
1561881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1562586320c0SNicholas Wilson 
1563586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1564586320c0SNicholas Wilson     Info.Name = WS.getName();
1565586320c0SNicholas Wilson     Info.Kind = WS.getType();
1566586320c0SNicholas Wilson     Info.Flags = Flags;
15674d57fbd0SSam Clegg     if (!WS.isData()) {
15684d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1569586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
15704d57fbd0SSam Clegg     } else if (WS.isDefined()) {
15714d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1572586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
15734d57fbd0SSam Clegg     }
157425d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1575586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1576b7787fd0SSam Clegg   }
1577b7787fd0SSam Clegg 
15786006e091SSam Clegg   {
15796006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1580f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1581f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1582f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1583d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
158481443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
158581443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1586f9edbe95SSam Clegg         return;
1587f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
158818c56a07SHeejin Ahn       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
15896c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
159018c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1591f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1592d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1593f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
15946c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
15956006e091SSam Clegg         registerFunctionType(WS);
15966006e091SSam Clegg       }
15976006e091SSam Clegg     };
1598970d02c4SDan Gohman 
15996006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16006006e091SSam Clegg       HandleReloc(RelEntry);
16016006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16026006e091SSam Clegg       HandleReloc(RelEntry);
1603d934cb88SDan Gohman   }
1604d934cb88SDan Gohman 
1605bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1606bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1607bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16087d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1609bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16107d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1611bafe6902SSam Clegg       continue;
1612bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1613bafe6902SSam Clegg       continue;
1614b210c64bSSam Clegg 
1615b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1616b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1617bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1618b210c64bSSam Clegg 
1619b210c64bSSam Clegg     auto IT = WS.begin();
1620b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1621b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1622b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1623b210c64bSSam Clegg 
1624b210c64bSSam Clegg     IT = std::next(IT);
1625b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1626bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1627bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1628bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1629bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1630b210c64bSSam Clegg 
1631b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1632bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1633bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1634b210c64bSSam Clegg 
1635bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
16364d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
16377d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
16387d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1639f208f631SHeejin Ahn         report_fatal_error(
1640f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
16417d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1642bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1643bafe6902SSam Clegg     }
1644bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1645bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1646f208f631SHeejin Ahn     for (const uint8_t *
164718c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
164818c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
164918c56a07SHeejin Ahn          P != End; ++P) {
165018c56a07SHeejin Ahn       if (*P != 0)
1651bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1652bafe6902SSam Clegg     }
1653bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1654f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1655f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1656bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
16578fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
16588fffa1dfSSam Clegg       if (!SymRef)
1659bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
16608fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
16618fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
16623ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
16638fffa1dfSSam Clegg       if (!TargetSym.isFunction())
16648fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
166525d8e68bSSam Clegg       InitFuncs.push_back(
16668fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1667bafe6902SSam Clegg     }
1668bafe6902SSam Clegg   }
1669bafe6902SSam Clegg 
167018eafb6cSDan Gohman   // Write out the Wasm header.
167118eafb6cSDan Gohman   writeHeader(Asm);
167218eafb6cSDan Gohman 
1673da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1674f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
16759e15f359SSam Clegg   writeFunctionSection(Functions);
1676f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1677f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1678da419bdbSHeejin Ahn   writeEventSection(Events);
16790a6c4d8dSSam Clegg   writeGlobalSection(Globals);
16809e15f359SSam Clegg   writeExportSection(Exports);
16819e15f359SSam Clegg   writeElemSection(TableElems);
1682fef8de66SThomas Lively   writeDataCountSection();
1683acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
16846c899ba6SSam Clegg   writeDataSection();
1685cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1686cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1687c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
16886f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
16896f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
16906a31a0d6SSam Clegg   writeCustomRelocSections();
1691cbda16ebSThomas Lively   if (ProducersSection)
1692cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1693f6f4f843SThomas Lively   if (TargetFeaturesSection)
1694f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1695970d02c4SDan Gohman 
1696d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1697438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
169818eafb6cSDan Gohman }
169918eafb6cSDan Gohman 
170060fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17011301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
170218eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17030eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
170418eafb6cSDan Gohman }
1705