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"
16b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.h"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.h"
31bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
33d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3518eafb6cSDan Gohman #include <vector>
3618eafb6cSDan Gohman 
3718eafb6cSDan Gohman using namespace llvm;
3818eafb6cSDan Gohman 
395e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
4018eafb6cSDan Gohman 
4118eafb6cSDan Gohman namespace {
429e15f359SSam Clegg 
43*feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is
44*feac819eSAndy Wingo // and empty slot at 0 and therefore calling a null function pointer will trap.
4518c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4630e1bbc1SSam Clegg 
47d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
48d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
49d934cb88SDan Gohman // locations within the section.
50d934cb88SDan Gohman struct SectionBookkeeping {
51d934cb88SDan Gohman   // Where the size of the section is written.
52d934cb88SDan Gohman   uint64_t SizeOffset;
536a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
546a31a0d6SSam Clegg   uint64_t PayloadOffset;
556a31a0d6SSam Clegg   // Where the contents of the section starts.
56d934cb88SDan Gohman   uint64_t ContentsOffset;
576f08c84aSSam Clegg   uint32_t Index;
58d934cb88SDan Gohman };
59d934cb88SDan Gohman 
607c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
617c395943SSam Clegg // but that can contain many segments, each with their own virtual location
627c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
637c395943SSam Clegg // wasm data segment.
647c395943SSam Clegg struct WasmDataSegment {
657c395943SSam Clegg   MCSectionWasm *Section;
66d95ed959SSam Clegg   StringRef Name;
672e150409SThomas Lively   uint32_t InitFlags;
684d135b04SWouter van Oortmerssen   uint64_t Offset;
6963ebb813SSam Clegg   uint32_t Alignment;
702e150409SThomas Lively   uint32_t LinkerFlags;
717c395943SSam Clegg   SmallVector<char, 4> Data;
727c395943SSam Clegg };
737c395943SSam Clegg 
749e15f359SSam Clegg // A wasm function to be written into the function section.
759e15f359SSam Clegg struct WasmFunction {
76da419bdbSHeejin Ahn   uint32_t SigIndex;
779e15f359SSam Clegg   const MCSymbolWasm *Sym;
789e15f359SSam Clegg };
799e15f359SSam Clegg 
809e15f359SSam Clegg // A wasm global to be written into the global section.
819e15f359SSam Clegg struct WasmGlobal {
826e7f1826SSam Clegg   wasm::WasmGlobalType Type;
839e15f359SSam Clegg   uint64_t InitialValue;
849e15f359SSam Clegg };
859e15f359SSam Clegg 
86ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
87ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
88ea7caceeSSam Clegg // WasmComdatEntry.
89ea7caceeSSam Clegg struct WasmComdatEntry {
90ea7caceeSSam Clegg   unsigned Kind;
91ea7caceeSSam Clegg   uint32_t Index;
92ea7caceeSSam Clegg };
93ea7caceeSSam Clegg 
946dc65e91SSam Clegg // Information about a single relocation.
956dc65e91SSam Clegg struct WasmRelocationEntry {
966dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
976dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
986dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
996dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
100fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1016dc65e91SSam Clegg 
1026dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1036dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
104fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1056dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1066dc65e91SSam Clegg         FixupSection(FixupSection) {}
1076dc65e91SSam Clegg 
108cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109acd7d2b0SSam Clegg 
1106dc65e91SSam Clegg   void print(raw_ostream &Out) const {
111f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1137d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1146dc65e91SSam Clegg   }
115b7787fd0SSam Clegg 
116615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118b7787fd0SSam Clegg #endif
1196dc65e91SSam Clegg };
1206dc65e91SSam Clegg 
12118c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12225d8e68bSSam Clegg 
123cfd44a2eSSam Clegg struct WasmCustomSection {
124cfd44a2eSSam Clegg 
1256a31a0d6SSam Clegg   StringRef Name;
1266a31a0d6SSam Clegg   MCSectionWasm *Section;
1276a31a0d6SSam Clegg 
1286a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1296a31a0d6SSam Clegg   uint32_t OutputIndex;
1306a31a0d6SSam Clegg 
1316a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1326a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
13318c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
134cfd44a2eSSam Clegg };
135cfd44a2eSSam Clegg 
1361fb8daa6SSam Clegg #if !defined(NDEBUG)
1377f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138b7787fd0SSam Clegg   Rel.print(OS);
139b7787fd0SSam Clegg   return OS;
140b7787fd0SSam Clegg }
1411fb8daa6SSam Clegg #endif
142b7787fd0SSam Clegg 
14319e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
14419e8befaSSam Clegg // to allow patching.
1453b29376eSWouter van Oortmerssen template <int W>
1463b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1473b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1483b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1493b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15119e8befaSSam Clegg }
15219e8befaSSam Clegg 
15319e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
15419e8befaSSam Clegg // to allow patching.
1553b29376eSWouter van Oortmerssen template <int W>
1563b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
1573b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1583b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
1593b29376eSWouter van Oortmerssen   assert(SizeLen == W);
16019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
16119e8befaSSam Clegg }
16219e8befaSSam Clegg 
16319e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
1640a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
16519e8befaSSam Clegg   uint8_t Buffer[4];
16619e8befaSSam Clegg   support::endian::write32le(Buffer, X);
16719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
16819e8befaSSam Clegg }
16919e8befaSSam Clegg 
1703b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1713b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
1723b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
1733b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1743b29376eSWouter van Oortmerssen }
1753b29376eSWouter van Oortmerssen 
1760ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1770ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1780ff28fa6SDerek Schuff }
1790ff28fa6SDerek Schuff 
18018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
1810ff28fa6SDerek Schuff   support::endian::Writer *W;
182f17b149dSPeter Collingbourne 
18318eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18418eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18518eafb6cSDan Gohman 
186d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
187d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
188d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
189d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
190d934cb88SDan Gohman 
191d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
192acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
193acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
195d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
196f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197388fb67bSPaulo Matos   // Maps function/global/table symbols to the
198388fb67bSPaulo Matos   // function/global/table/event/section index space.
1996c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
200492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2016c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2026c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2036a31a0d6SSam Clegg 
2046a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2056a31a0d6SSam Clegg   // section.
2066a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
207cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
208f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2096a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2106a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2116a31a0d6SSam Clegg       CustomSectionsRelocations;
212acd7d2b0SSam Clegg 
213c0d41195SSam Clegg   // Map from section to defining function symbol.
2146ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2156ccb59b3SSam Clegg 
2164c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2174c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2186c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2199f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2207c395943SSam Clegg   unsigned NumGlobalImports = 0;
221*feac819eSAndy Wingo   unsigned NumTableImports = 0;
222da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2237e1c3345SChandler Carruth   uint32_t SectionCount = 0;
224d934cb88SDan Gohman 
2250ff28fa6SDerek Schuff   enum class DwoMode {
2260ff28fa6SDerek Schuff     AllSections,
2270ff28fa6SDerek Schuff     NonDwoOnly,
2280ff28fa6SDerek Schuff     DwoOnly,
2290ff28fa6SDerek Schuff   };
2300ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2310ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2320ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2330ff28fa6SDerek Schuff 
2340ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
23518eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
236da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
23718eafb6cSDan Gohman 
2382322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2392322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
240d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
241d934cb88SDan Gohman 
24218eafb6cSDan Gohman public:
2431301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2440ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2450ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2460ff28fa6SDerek Schuff 
2470ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2480ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2490ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2500ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
25118eafb6cSDan Gohman 
2520917c9e4SDan Gohman private:
253acd7d2b0SSam Clegg   void reset() override {
254acd7d2b0SSam Clegg     CodeRelocations.clear();
255acd7d2b0SSam Clegg     DataRelocations.clear();
256acd7d2b0SSam Clegg     TypeIndices.clear();
2576c899ba6SSam Clegg     WasmIndices.clear();
258492f7529SSam Clegg     GOTIndices.clear();
259f9edbe95SSam Clegg     TableIndices.clear();
2606c899ba6SSam Clegg     DataLocations.clear();
261cbda16ebSThomas Lively     CustomSections.clear();
262cbda16ebSThomas Lively     ProducersSection.reset();
263f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2646a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
265da419bdbSHeejin Ahn     SignatureIndices.clear();
266da419bdbSHeejin Ahn     Signatures.clear();
2676c899ba6SSam Clegg     DataSegments.clear();
2686ccb59b3SSam Clegg     SectionFunctions.clear();
2699f3fe42eSSam Clegg     NumFunctionImports = 0;
2707c395943SSam Clegg     NumGlobalImports = 0;
271*feac819eSAndy Wingo     NumTableImports = 0;
272105bdc25SSam Clegg     MCObjectWriter::reset();
273acd7d2b0SSam Clegg   }
274acd7d2b0SSam Clegg 
27518eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
27618eafb6cSDan Gohman 
27718eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
27818eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
279ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
28018eafb6cSDan Gohman 
28118eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28218eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
2830ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
2840ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
285438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2869e15f359SSam Clegg 
2870ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
2880ff28fa6SDerek Schuff                           DwoMode Mode);
2890ff28fa6SDerek Schuff 
290b7787fd0SSam Clegg   void writeString(const StringRef Str) {
2910ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
2920ff28fa6SDerek Schuff     W->OS << Str;
293b7787fd0SSam Clegg   }
294b7787fd0SSam Clegg 
2950a6c4d8dSSam Clegg   void writeI32(int32_t val) {
2960a6c4d8dSSam Clegg     char Buffer[4];
2970a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
2980ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
2990a6c4d8dSSam Clegg   }
3000a6c4d8dSSam Clegg 
3010a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3020a6c4d8dSSam Clegg     char Buffer[8];
3030a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3040ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3050a6c4d8dSSam Clegg   }
3060a6c4d8dSSam Clegg 
3070ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3089e15f359SSam Clegg 
3094c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3104d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
311f950b24aSSam Clegg                           uint32_t NumElements);
312457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3138defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
314457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
315fef8de66SThomas Lively   void writeDataCountSection();
316e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
317457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
318e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
319da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3200a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
321388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3226f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
323f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32431a2c809SSam Clegg   void writeLinkingMetaDataSection(
32586b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
326ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
327ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
328cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
329cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3306a31a0d6SSam Clegg   void writeCustomRelocSections();
3316a31a0d6SSam Clegg   void
3326a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3336a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
334acd7d2b0SSam Clegg 
3357ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3367ee758d6SSam Clegg                                const MCAsmLayout &Layout);
337acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3387ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
339acd7d2b0SSam Clegg 
340acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3415e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
342da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34338b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34438b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34518eafb6cSDan Gohman };
3469e15f359SSam Clegg 
34718eafb6cSDan Gohman } // end anonymous namespace
34818eafb6cSDan Gohman 
349d934cb88SDan Gohman // Write out a section header and a patchable section size field.
350d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3512322a937SSam Clegg                                     unsigned SectionId) {
352d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3530ff28fa6SDerek Schuff   W->OS << char(SectionId);
354d934cb88SDan Gohman 
3550ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
356d934cb88SDan Gohman 
357d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
358d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3590ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
360d934cb88SDan Gohman 
361d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3620ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3630ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3646f08c84aSSam Clegg   Section.Index = SectionCount++;
365d934cb88SDan Gohman }
3662322a937SSam Clegg 
3672322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3682322a937SSam Clegg                                           StringRef Name) {
369d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3702322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3716a31a0d6SSam Clegg 
3726a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3730ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3746a31a0d6SSam Clegg 
3752322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3762322a937SSam Clegg   writeString(Name);
3776a31a0d6SSam Clegg 
3786a31a0d6SSam Clegg   // The position where the custom section starts.
3790ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
380d934cb88SDan Gohman }
381d934cb88SDan Gohman 
382d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
383d934cb88SDan Gohman // section size field at the start of the section.
384d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3850ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
386c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
387c0affde8SSam Clegg   // Simply skip this patching in that case.
388c0affde8SSam Clegg   if (!Size)
389c0affde8SSam Clegg     return;
390c0affde8SSam Clegg 
391c0affde8SSam Clegg   Size -= Section.PayloadOffset;
392d934cb88SDan Gohman   if (uint32_t(Size) != Size)
393d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
394d934cb88SDan Gohman 
395d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
396d934cb88SDan Gohman 
397d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
398d934cb88SDan Gohman   // the section id byte.
3990ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
400f17b149dSPeter Collingbourne                        Section.SizeOffset);
401d934cb88SDan Gohman }
402d934cb88SDan Gohman 
40318eafb6cSDan Gohman // Emit the Wasm header.
40418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4050ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4060ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40718eafb6cSDan Gohman }
40818eafb6cSDan Gohman 
40918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4116ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4126ccb59b3SSam Clegg   // in recordRelocation.
4136ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4146ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4156ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4166ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4176ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4186ccb59b3SSam Clegg       if (!Pair.second)
4196ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4207d1ff446SFangrui Song                            Sec.getName());
4216ccb59b3SSam Clegg     }
4226ccb59b3SSam Clegg   }
42318eafb6cSDan Gohman }
42418eafb6cSDan Gohman 
42518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42718eafb6cSDan Gohman                                         const MCFragment *Fragment,
42818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
429ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
430ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
431e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
432ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
433ecc5e808SSam Clegg 
434fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
435d934cb88SDan Gohman   uint64_t C = Target.getConstant();
436d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
437d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
438d934cb88SDan Gohman 
439d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
440ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
441ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
442ecc5e808SSam Clegg     // support either of those cases.
443ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
444d934cb88SDan Gohman     Ctx.reportError(
445d934cb88SDan Gohman         Fixup.getLoc(),
446d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
447ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
448d934cb88SDan Gohman     return;
449d934cb88SDan Gohman   }
450d934cb88SDan Gohman 
451d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
452d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
453ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
454d934cb88SDan Gohman 
4553ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4567d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4573ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4583ea1c62cSSam Clegg     return;
4593ea1c62cSSam Clegg   }
4603ea1c62cSSam Clegg 
461ecc5e808SSam Clegg   if (SymA->isVariable()) {
462d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4637ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4646ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4656ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
466d934cb88SDan Gohman   }
467d934cb88SDan Gohman 
468d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
469d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
470d934cb88SDan Gohman   // be negative and don't wrap.
471d934cb88SDan Gohman   FixedValue = 0;
472d934cb88SDan Gohman 
473a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4749d24fb7fSSam Clegg 
4754d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4764d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4774d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
478d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
47916f02431SWouter van Oortmerssen       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
480d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4814d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4824d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4834d57fbd0SSam Clegg                          "only supported in metadata sections");
4844d57fbd0SSam Clegg 
4854d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4864d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4874d57fbd0SSam Clegg     if (SecA.getKind().isText())
4886ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4894d57fbd0SSam Clegg     else
4904d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4914d57fbd0SSam Clegg     if (!SectionSymbol)
4924d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4934d57fbd0SSam Clegg 
4944d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4954d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4964d57fbd0SSam Clegg   }
4974d57fbd0SSam Clegg 
498*feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
499*feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
500*feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
501*feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
502*feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
503*feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
504*feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
505*feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
506*feac819eSAndy Wingo     if (Sym) {
507*feac819eSAndy Wingo       if (!Sym->isFunctionTable())
508*feac819eSAndy Wingo         Ctx.reportError(
509*feac819eSAndy Wingo             Fixup.getLoc(),
510*feac819eSAndy Wingo             "symbol '__indirect_function_table' is not a function table");
511*feac819eSAndy Wingo     } else {
512*feac819eSAndy Wingo       Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(TableName));
513*feac819eSAndy Wingo       Sym->setFunctionTable();
514*feac819eSAndy Wingo       // The default function table is synthesized by the linker.
515*feac819eSAndy Wingo       Sym->setUndefined();
516*feac819eSAndy Wingo     }
517*feac819eSAndy Wingo     Sym->setUsedInReloc();
518*feac819eSAndy Wingo     Asm.registerSymbol(*Sym);
519*feac819eSAndy Wingo   }
520*feac819eSAndy Wingo 
521d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5224d57fbd0SSam Clegg   // against a named symbol.
523d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5244d57fbd0SSam Clegg     if (SymA->getName().empty())
5254d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5264d57fbd0SSam Clegg                          "supported by wasm");
5274d57fbd0SSam Clegg 
5284d57fbd0SSam Clegg     SymA->setUsedInReloc();
5294d57fbd0SSam Clegg   }
530ae03c1e7SSam Clegg 
531492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
532492f7529SSam Clegg     SymA->setUsedInGOT();
533492f7529SSam Clegg 
534d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
535d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
536d934cb88SDan Gohman 
5376a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
538d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5396a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
54012fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5416a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5426a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5436a31a0d6SSam Clegg   } else {
54412fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
545d934cb88SDan Gohman   }
5466a31a0d6SSam Clegg }
547d934cb88SDan Gohman 
548d934cb88SDan Gohman // Compute a value to write into the code at the location covered
54960ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
55060ec3034SSam Clegg // to make the object format more readable and more likely to be directly
55160ec3034SSam Clegg // useable.
5523b29376eSWouter van Oortmerssen uint64_t
5537ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5547ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
55548139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
55648139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
55748139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
558492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
559492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
560492f7529SSam Clegg   }
561492f7529SSam Clegg 
56260ec3034SSam Clegg   switch (RelEntry.Type) {
5632a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
564d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
565cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
566cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
567cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
568f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5697ee758d6SSam Clegg     const MCSymbolWasm *Base =
5707ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5717ee758d6SSam Clegg     assert(Base->isFunction());
57281443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5737ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
57481443ac1SSam Clegg     else
5757ee758d6SSam Clegg       return TableIndices[Base];
576f9edbe95SSam Clegg   }
577d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5786c899ba6SSam Clegg     // Provisional value is same as the index
57960ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
580d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
581d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
58248139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
583d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
58469e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
585da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
586492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5876c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
588d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
58916f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
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:
5963b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5973b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5983b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5992a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6003b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6013b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
602a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
603a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
6049c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
6057ee758d6SSam Clegg     const MCSymbolWasm *Base =
6067ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
607270ed1b3SSam Clegg     // For undefined symbols, use zero
6087ee758d6SSam Clegg     if (!Base->isDefined())
609270ed1b3SSam Clegg       return 0;
6109c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
6119c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
6129c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
613d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6149c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
61560ec3034SSam Clegg   }
61660ec3034SSam Clegg   default:
61760ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61860ec3034SSam Clegg   }
619d934cb88SDan Gohman }
620d934cb88SDan Gohman 
621759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62263ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6237d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
624759631c7SSam Clegg 
62563ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62663ebb813SSam Clegg 
627759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
628759631c7SSam Clegg     if (Frag.hasInstructions())
629759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
630759631c7SSam Clegg 
631759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
632759631c7SSam Clegg       if (Align->getValueSize() != 1)
633759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
634759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
635759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
636f208f631SHeejin Ahn       uint64_t Size =
637f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
638f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
639759631c7SSam Clegg       DataBytes.resize(Size, Value);
640759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
641588fad4dSNirav Dave       int64_t NumValues;
642588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
643d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
644588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
645588fad4dSNirav Dave                        Fill->getValue());
64624faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
64724faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
64824faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
649759631c7SSam Clegg     } else {
650759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
651759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
652759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
653759631c7SSam Clegg     }
654759631c7SSam Clegg   }
655759631c7SSam Clegg 
656d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
657759631c7SSam Clegg }
658759631c7SSam Clegg 
65960ec3034SSam Clegg uint32_t
66060ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
661d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
662b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
663b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
664b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
665acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
666acd7d2b0SSam Clegg   }
66760ec3034SSam Clegg 
66825d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
669acd7d2b0SSam Clegg }
670acd7d2b0SSam Clegg 
671d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
672d934cb88SDan Gohman // directly.
673acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6747ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6757ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6760ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
677d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
678d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
679d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
680d934cb88SDan Gohman                       RelEntry.Offset;
681d934cb88SDan Gohman 
682d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6837ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
68460ec3034SSam Clegg 
685acd7d2b0SSam Clegg     switch (RelEntry.Type) {
686d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
687d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
688d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
689d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
690d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
69169e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
6923b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6933b29376eSWouter van Oortmerssen       break;
6943b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6953b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
696d934cb88SDan Gohman       break;
697d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
698d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
699d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
700d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
70148139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
7020a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
703d934cb88SDan Gohman       break;
704cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7053b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
70616f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
7073b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7083b29376eSWouter van Oortmerssen       break;
709d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7102a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
711d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7122a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
713a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
7143b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7153b29376eSWouter van Oortmerssen       break;
716cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7173b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7183b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7193b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
72060ec3034SSam Clegg       break;
721d934cb88SDan Gohman     default:
7229d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
723d934cb88SDan Gohman     }
724d934cb88SDan Gohman   }
72518eafb6cSDan Gohman }
72618eafb6cSDan Gohman 
7274c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7284c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
729da419bdbSHeejin Ahn   if (Signatures.empty())
7309e15f359SSam Clegg     return;
7319e15f359SSam Clegg 
7329e15f359SSam Clegg   SectionBookkeeping Section;
7339e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7349e15f359SSam Clegg 
7350ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7369e15f359SSam Clegg 
7374c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7380ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7390ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
740da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7419e15f359SSam Clegg       writeValueType(Ty);
7420ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
743da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7449e15f359SSam Clegg       writeValueType(Ty);
7459e15f359SSam Clegg   }
7469e15f359SSam Clegg 
7479e15f359SSam Clegg   endSection(Section);
7489e15f359SSam Clegg }
7499e15f359SSam Clegg 
7508defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7514d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
752f950b24aSSam Clegg                                           uint32_t NumElements) {
7539e15f359SSam Clegg   if (Imports.empty())
7549e15f359SSam Clegg     return;
7559e15f359SSam Clegg 
7564d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
757f950b24aSSam Clegg 
7589e15f359SSam Clegg   SectionBookkeeping Section;
7599e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7609e15f359SSam Clegg 
7610ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7628defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7638defa952SSam Clegg     writeString(Import.Module);
7648defa952SSam Clegg     writeString(Import.Field);
7650ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7669e15f359SSam Clegg 
7679e15f359SSam Clegg     switch (Import.Kind) {
7689e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7690ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7709e15f359SSam Clegg       break;
7719e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7720ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7730ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7749e15f359SSam Clegg       break;
775f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7760ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7770ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
778f950b24aSSam Clegg       break;
779f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7800ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7810ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7820ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
783f950b24aSSam Clegg       break;
784da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7850ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7860ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
787da419bdbSHeejin Ahn       break;
7889e15f359SSam Clegg     default:
7899e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7909e15f359SSam Clegg     }
7919e15f359SSam Clegg   }
7929e15f359SSam Clegg 
7939e15f359SSam Clegg   endSection(Section);
7949e15f359SSam Clegg }
7959e15f359SSam Clegg 
796457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7979e15f359SSam Clegg   if (Functions.empty())
7989e15f359SSam Clegg     return;
7999e15f359SSam Clegg 
8009e15f359SSam Clegg   SectionBookkeeping Section;
8019e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8029e15f359SSam Clegg 
8030ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8049e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
8050ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   endSection(Section);
8089e15f359SSam Clegg }
8099e15f359SSam Clegg 
810da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
811da419bdbSHeejin Ahn   if (Events.empty())
812da419bdbSHeejin Ahn     return;
813da419bdbSHeejin Ahn 
814da419bdbSHeejin Ahn   SectionBookkeeping Section;
815da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
816da419bdbSHeejin Ahn 
8170ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
818da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
8190ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
8200ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
821da419bdbSHeejin Ahn   }
822da419bdbSHeejin Ahn 
823da419bdbSHeejin Ahn   endSection(Section);
824da419bdbSHeejin Ahn }
825da419bdbSHeejin Ahn 
8260a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8270a6c4d8dSSam Clegg   if (Globals.empty())
8280a6c4d8dSSam Clegg     return;
8290a6c4d8dSSam Clegg 
8300a6c4d8dSSam Clegg   SectionBookkeeping Section;
8310a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8320a6c4d8dSSam Clegg 
8330ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8340a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8350ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8360ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8370ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8380a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8390a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8400ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8410a6c4d8dSSam Clegg       break;
8420a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8430ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8440a6c4d8dSSam Clegg       break;
8450a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8460a6c4d8dSSam Clegg       writeI32(0);
8470a6c4d8dSSam Clegg       break;
8480a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8490a6c4d8dSSam Clegg       writeI64(0);
8500a6c4d8dSSam Clegg       break;
85179aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
85279aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
85379aad89dSSam Clegg       break;
8540a6c4d8dSSam Clegg     default:
8550a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8560a6c4d8dSSam Clegg     }
8570ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8580a6c4d8dSSam Clegg   }
8590a6c4d8dSSam Clegg 
8600a6c4d8dSSam Clegg   endSection(Section);
8610a6c4d8dSSam Clegg }
8620a6c4d8dSSam Clegg 
863388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
864388fb67bSPaulo Matos   if (Tables.empty())
865388fb67bSPaulo Matos     return;
866388fb67bSPaulo Matos 
867388fb67bSPaulo Matos   SectionBookkeeping Section;
868388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
869388fb67bSPaulo Matos 
870388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
871388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
8721933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
8731933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
8741933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Initial, W->OS);
8751933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
8761933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
877388fb67bSPaulo Matos   }
878388fb67bSPaulo Matos   endSection(Section);
879388fb67bSPaulo Matos }
880388fb67bSPaulo Matos 
8818defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8829e15f359SSam Clegg   if (Exports.empty())
8839e15f359SSam Clegg     return;
8849e15f359SSam Clegg 
8859e15f359SSam Clegg   SectionBookkeeping Section;
8869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8879e15f359SSam Clegg 
8880ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8898defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8908defa952SSam Clegg     writeString(Export.Name);
8910ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8920ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8939e15f359SSam Clegg   }
8949e15f359SSam Clegg 
8959e15f359SSam Clegg   endSection(Section);
8969e15f359SSam Clegg }
8979e15f359SSam Clegg 
898457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8999e15f359SSam Clegg   if (TableElems.empty())
9009e15f359SSam Clegg     return;
9019e15f359SSam Clegg 
9029e15f359SSam Clegg   SectionBookkeeping Section;
9039e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
9049e15f359SSam Clegg 
9050ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
9060ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
9079e15f359SSam Clegg 
9089e15f359SSam Clegg   // init expr for starting offset
9090ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
9100ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
9110ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9129e15f359SSam Clegg 
9130ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9149e15f359SSam Clegg   for (uint32_t Elem : TableElems)
9150ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9169e15f359SSam Clegg 
9179e15f359SSam Clegg   endSection(Section);
9189e15f359SSam Clegg }
9199e15f359SSam Clegg 
920fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
921fef8de66SThomas Lively   if (DataSegments.empty())
922fef8de66SThomas Lively     return;
923fef8de66SThomas Lively 
924fef8de66SThomas Lively   SectionBookkeeping Section;
925fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9260ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
927fef8de66SThomas Lively   endSection(Section);
928fef8de66SThomas Lively }
929fef8de66SThomas Lively 
930e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
931457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
932457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9339e15f359SSam Clegg   if (Functions.empty())
934e49584a3SSam Clegg     return 0;
9359e15f359SSam Clegg 
9369e15f359SSam Clegg   SectionBookkeeping Section;
9379e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9389e15f359SSam Clegg 
9390ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9409e15f359SSam Clegg 
9419e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
942fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9439e15f359SSam Clegg 
9449e15f359SSam Clegg     int64_t Size = 0;
9459e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9469e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9479e15f359SSam Clegg 
9480ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9490ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9500ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9519e15f359SSam Clegg   }
9529e15f359SSam Clegg 
9539e15f359SSam Clegg   // Apply fixups.
9547ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9559e15f359SSam Clegg 
9569e15f359SSam Clegg   endSection(Section);
957e49584a3SSam Clegg   return Section.Index;
9589e15f359SSam Clegg }
9599e15f359SSam Clegg 
960e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9616c899ba6SSam Clegg   if (DataSegments.empty())
962e49584a3SSam Clegg     return 0;
9639e15f359SSam Clegg 
9649e15f359SSam Clegg   SectionBookkeeping Section;
9659e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9669e15f359SSam Clegg 
9670ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9687c395943SSam Clegg 
9696c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9700ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9712e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9720ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9732e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9740ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9754d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9760ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9770ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9782e150409SThomas Lively     }
9790ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9800ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9810ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9827c395943SSam Clegg   }
9839e15f359SSam Clegg 
9849e15f359SSam Clegg   // Apply fixups.
9857ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9869e15f359SSam Clegg 
9879e15f359SSam Clegg   endSection(Section);
988e49584a3SSam Clegg   return Section.Index;
9899e15f359SSam Clegg }
9909e15f359SSam Clegg 
9916f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9926f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
993f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9949e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9959e15f359SSam Clegg   // for descriptions of the reloc sections.
9969e15f359SSam Clegg 
997f77dc2a8SSam Clegg   if (Relocs.empty())
9989e15f359SSam Clegg     return;
9999e15f359SSam Clegg 
1000f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1001f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1002f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1003f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1004f77dc2a8SSam Clegg   // not the sections order.
1005efd94c56SFangrui Song   llvm::stable_sort(
1006efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1007f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1008f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1009f77dc2a8SSam Clegg       });
1010f77dc2a8SSam Clegg 
10119e15f359SSam Clegg   SectionBookkeeping Section;
10126f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10139e15f359SSam Clegg 
10140ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
10150ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1016f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1017f208f631SHeejin Ahn     uint64_t Offset =
1018f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10196f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10209e15f359SSam Clegg 
10210ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10220ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10230ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10246f08c84aSSam Clegg     if (RelEntry.hasAddend())
10250ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10269e15f359SSam Clegg   }
10279e15f359SSam Clegg 
10289e15f359SSam Clegg   endSection(Section);
10299e15f359SSam Clegg }
10309e15f359SSam Clegg 
10316a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10326a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10336a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10346a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10356a31a0d6SSam Clegg   }
10366a31a0d6SSam Clegg }
10376a31a0d6SSam Clegg 
10389e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
103986b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1040ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1041ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10429e15f359SSam Clegg   SectionBookkeeping Section;
10432322a937SSam Clegg   startCustomSection(Section, "linking");
10440ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10459e15f359SSam Clegg 
10466bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10476c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10486c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10490ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10506c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10510ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10520ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10536c899ba6SSam Clegg       switch (Sym.Kind) {
10546c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10556c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1056da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1057388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10580ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
105929874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
106029874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10616c899ba6SSam Clegg           writeString(Sym.Name);
10626c899ba6SSam Clegg         break;
10636c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10646c899ba6SSam Clegg         writeString(Sym.Name);
10656c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10660ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10670ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10680ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10696c899ba6SSam Clegg         }
10706c899ba6SSam Clegg         break;
10716a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10726a31a0d6SSam Clegg         const uint32_t SectionIndex =
10736a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10740ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10756a31a0d6SSam Clegg         break;
10766a31a0d6SSam Clegg       }
10776c899ba6SSam Clegg       default:
10786c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10796c899ba6SSam Clegg       }
1080b7787fd0SSam Clegg     }
1081b7787fd0SSam Clegg     endSection(SubSection);
1082b7787fd0SSam Clegg   }
10839e15f359SSam Clegg 
10846c899ba6SSam Clegg   if (DataSegments.size()) {
108563ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10860ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10876c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1088d95ed959SSam Clegg       writeString(Segment.Name);
10890ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10900ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
109163ebb813SSam Clegg     }
1092d95ed959SSam Clegg     endSection(SubSection);
1093d95ed959SSam Clegg   }
1094d95ed959SSam Clegg 
1095bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1096bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10970ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1098bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10990ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
11000ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1101bafe6902SSam Clegg     }
1102bafe6902SSam Clegg     endSection(SubSection);
1103bafe6902SSam Clegg   }
1104bafe6902SSam Clegg 
1105ea7caceeSSam Clegg   if (Comdats.size()) {
1106ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
11070ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1108ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1109ea7caceeSSam Clegg       writeString(C.first);
11100ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
11110ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1112ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
11130ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
11140ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1115ea7caceeSSam Clegg       }
1116ea7caceeSSam Clegg     }
1117ea7caceeSSam Clegg     endSection(SubSection);
1118ea7caceeSSam Clegg   }
1119ea7caceeSSam Clegg 
11209e15f359SSam Clegg   endSection(Section);
11219e15f359SSam Clegg }
11229e15f359SSam Clegg 
1123cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1124cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11256a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1126cfd44a2eSSam Clegg   SectionBookkeeping Section;
11276a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11282322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11296a31a0d6SSam Clegg 
11300ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11310ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11326a31a0d6SSam Clegg 
11336a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11346a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11356a31a0d6SSam Clegg 
1136cfd44a2eSSam Clegg   endSection(Section);
11376a31a0d6SSam Clegg 
11386a31a0d6SSam Clegg   // Apply fixups.
11394d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11407ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11416a31a0d6SSam Clegg }
11426a31a0d6SSam Clegg 
11435e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11445e3d33a7SSam Clegg   assert(Symbol.isFunction());
11455e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11465e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11475e3d33a7SSam Clegg }
11485e3d33a7SSam Clegg 
1149da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1150da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1151da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1152da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1153da419bdbSHeejin Ahn }
1154da419bdbSHeejin Ahn 
115538b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11565e3d33a7SSam Clegg   assert(Symbol.isFunction());
11575e3d33a7SSam Clegg 
11584c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11597ee758d6SSam Clegg 
11607ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1161da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1162da419bdbSHeejin Ahn     S.Params = Sig->Params;
116377a7a380SDerek Schuff   }
11645e3d33a7SSam Clegg 
1165da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11665e3d33a7SSam Clegg   if (Pair.second)
1167da419bdbSHeejin Ahn     Signatures.push_back(S);
11685e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11695e3d33a7SSam Clegg 
1170d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1171d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1172d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11735e3d33a7SSam Clegg }
11745e3d33a7SSam Clegg 
117538b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1176da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1177da419bdbSHeejin Ahn 
1178da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1179da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11804c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1181da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1182da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1183da419bdbSHeejin Ahn     S.Params = Sig->Params;
1184da419bdbSHeejin Ahn   }
1185da419bdbSHeejin Ahn 
1186da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1187da419bdbSHeejin Ahn   if (Pair.second)
1188da419bdbSHeejin Ahn     Signatures.push_back(S);
1189da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1190da419bdbSHeejin Ahn 
1191da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1192da419bdbSHeejin Ahn                     << "\n");
1193da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1194da419bdbSHeejin Ahn }
1195da419bdbSHeejin Ahn 
11964d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11973ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11984d57fbd0SSam Clegg     return true;
11994d57fbd0SSam Clegg 
12004d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
12014d57fbd0SSam Clegg     return false;
12024d57fbd0SSam Clegg 
12033ea1c62cSSam Clegg   if (Sym.isTemporary())
12044d57fbd0SSam Clegg     return false;
12054d57fbd0SSam Clegg 
12064d57fbd0SSam Clegg   if (Sym.isSection())
12074d57fbd0SSam Clegg     return false;
12084d57fbd0SSam Clegg 
12094d57fbd0SSam Clegg   return true;
12104d57fbd0SSam Clegg }
12110ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
12120ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
121318eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1214f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1215f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1216f950b24aSSam Clegg   // it if there are no loads or stores.
12178defa952SSam Clegg   wasm::WasmImport MemImport;
12181ed3a046SSam Clegg   MemImport.Module = "env";
12191ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1220f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1221fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1222fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1223f950b24aSSam Clegg   Imports.push_back(MemImport);
1224f950b24aSSam Clegg 
1225da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1226586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1227586320c0SNicholas Wilson   // symbols.
122832ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
122932ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
123032ce5ca0SDan Gohman 
123132ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12329f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12337ee758d6SSam Clegg     if (WS.isFunction()) {
12349c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12359c7b5808SDominic Chen       if (!BS)
12369c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12379c7b5808SDominic Chen                            ": absolute addressing not supported!");
12389c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12397ee758d6SSam Clegg     }
124032ce5ca0SDan Gohman 
1241da419bdbSHeejin Ahn     if (WS.isEvent())
1242da419bdbSHeejin Ahn       registerEventType(WS);
1243da419bdbSHeejin Ahn 
124432ce5ca0SDan Gohman     if (WS.isTemporary())
124532ce5ca0SDan Gohman       continue;
124632ce5ca0SDan Gohman 
124732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12486c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12496c899ba6SSam Clegg       if (WS.isFunction()) {
12508defa952SSam Clegg         wasm::WasmImport Import;
1251f726e445SDan Gohman         Import.Module = WS.getImportModule();
1252f726e445SDan Gohman         Import.Field = WS.getImportName();
125332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12548defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12556c899ba6SSam Clegg         Imports.push_back(Import);
1256492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12576c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12586c899ba6SSam Clegg       } else if (WS.isGlobal()) {
125915f349f7SNicholas Wilson         if (WS.isWeak())
126015f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
126115f349f7SNicholas Wilson 
12626c899ba6SSam Clegg         wasm::WasmImport Import;
1263f726e445SDan Gohman         Import.Field = WS.getImportName();
126432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1265492f7529SSam Clegg         Import.Module = WS.getImportModule();
12666c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12676c899ba6SSam Clegg         Imports.push_back(Import);
1268492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12696c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1270da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1271da419bdbSHeejin Ahn         if (WS.isWeak())
1272da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1273da419bdbSHeejin Ahn 
1274da419bdbSHeejin Ahn         wasm::WasmImport Import;
1275f726e445SDan Gohman         Import.Module = WS.getImportModule();
1276f726e445SDan Gohman         Import.Field = WS.getImportName();
1277da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1278da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1279da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1280da419bdbSHeejin Ahn         Imports.push_back(Import);
1281492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1282da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
1283*feac819eSAndy Wingo       } else if (WS.isTable()) {
1284*feac819eSAndy Wingo         if (WS.isWeak())
1285*feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1286*feac819eSAndy Wingo 
1287*feac819eSAndy Wingo         wasm::WasmImport Import;
1288*feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1289*feac819eSAndy Wingo         Import.Field = WS.getImportName();
1290*feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1291*feac819eSAndy Wingo         wasm::ValType ElemType = WS.getTableType();
1292*feac819eSAndy Wingo         Import.Table.ElemType = uint8_t(ElemType);
1293*feac819eSAndy Wingo         // FIXME: Extend table type to include limits? For now we don't specify
1294*feac819eSAndy Wingo         // a min or max which does not place any restrictions on the size of the
1295*feac819eSAndy Wingo         // imported table.
1296*feac819eSAndy Wingo         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1297*feac819eSAndy Wingo         Imports.push_back(Import);
1298*feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1299*feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
130032ce5ca0SDan Gohman       }
130132ce5ca0SDan Gohman     }
130232ce5ca0SDan Gohman   }
130332ce5ca0SDan Gohman 
1304492f7529SSam Clegg   // Add imports for GOT globals
1305492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1306492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1307492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1308492f7529SSam Clegg       wasm::WasmImport Import;
1309492f7529SSam Clegg       if (WS.isFunction())
1310492f7529SSam Clegg         Import.Module = "GOT.func";
1311492f7529SSam Clegg       else
1312492f7529SSam Clegg         Import.Module = "GOT.mem";
1313492f7529SSam Clegg       Import.Field = WS.getName();
1314492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1315492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1316492f7529SSam Clegg       Imports.push_back(Import);
1317492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1318492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1319492f7529SSam Clegg     }
1320492f7529SSam Clegg   }
13210ff28fa6SDerek Schuff }
1322492f7529SSam Clegg 
13230ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
13240ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
13250ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
13260ff28fa6SDerek Schuff   W = &MainWriter;
13270ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13280ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13290ff28fa6SDerek Schuff     assert(DwoOS);
13300ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13310ff28fa6SDerek Schuff     W = &DwoWriter;
13320ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13330ff28fa6SDerek Schuff   } else {
13340ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13350ff28fa6SDerek Schuff   }
13360ff28fa6SDerek Schuff }
13370ff28fa6SDerek Schuff 
13380ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13390ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13400ff28fa6SDerek Schuff                                           DwoMode Mode) {
13410ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13420ff28fa6SDerek Schuff   SectionCount = 0;
13430ff28fa6SDerek Schuff   CustomSections.clear();
13440ff28fa6SDerek Schuff 
13450ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13460ff28fa6SDerek Schuff 
13470ff28fa6SDerek Schuff   // Collect information from the available symbols.
13480ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13490ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13500ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13510ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13520ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13530ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1354388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13550ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13560ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13570ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13580ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13590ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13600ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13610ff28fa6SDerek Schuff   }
13624d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13634d57fbd0SSam Clegg   // populating DataLocations.
1364759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1365759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13667d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1367759631c7SSam Clegg 
13680ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13690ff28fa6SDerek Schuff       continue;
13700ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13710ff28fa6SDerek Schuff       continue;
13720ff28fa6SDerek Schuff 
1373bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13744d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1375bafe6902SSam Clegg       continue;
1376bafe6902SSam Clegg 
13774d57fbd0SSam Clegg     // Code is handled separately
13784d57fbd0SSam Clegg     if (Section.getKind().isText())
13794d57fbd0SSam Clegg       continue;
13804d57fbd0SSam Clegg 
13814d57fbd0SSam Clegg     if (Section.isWasmData()) {
1382329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1383759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1384759631c7SSam Clegg       DataSegments.emplace_back();
1385759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13864d57fbd0SSam Clegg       Segment.Name = SectionName;
13879b49f36aSSimon Pilgrim       Segment.InitFlags =
13889b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1389759631c7SSam Clegg       Segment.Offset = DataSize;
1390759631c7SSam Clegg       Segment.Section = &Section;
139163ebb813SSam Clegg       addData(Segment.Data, Section);
139256c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13932e150409SThomas Lively       Segment.LinkerFlags = 0;
1394759631c7SSam Clegg       DataSize += Segment.Data.size();
13956c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1396ea7caceeSSam Clegg 
1397ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1398ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1399329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1400ea7caceeSSam Clegg       }
14014d57fbd0SSam Clegg     } else {
14024d57fbd0SSam Clegg       // Create custom sections
14034d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
14044d57fbd0SSam Clegg 
14054d57fbd0SSam Clegg       StringRef Name = SectionName;
14064d57fbd0SSam Clegg 
14074d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
14084d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
14094d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
14104d57fbd0SSam Clegg 
14114d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1412fb807d4dSSam Clegg       if (Begin) {
14134d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1414fb807d4dSSam Clegg       }
1415cbda16ebSThomas Lively 
1416f6f4f843SThomas Lively       // Separate out the producers and target features sections
1417cbda16ebSThomas Lively       if (Name == "producers") {
14180eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1419cbda16ebSThomas Lively         continue;
1420cbda16ebSThomas Lively       }
1421f6f4f843SThomas Lively       if (Name == "target_features") {
1422f6f4f843SThomas Lively         TargetFeaturesSection =
14230eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1424f6f4f843SThomas Lively         continue;
1425f6f4f843SThomas Lively       }
1426cbda16ebSThomas Lively 
14274d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1428759631c7SSam Clegg     }
14296a31a0d6SSam Clegg   }
14306a31a0d6SSam Clegg 
1431586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1432d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1433d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1434d934cb88SDan Gohman     // or used in relocations.
1435d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1436d934cb88SDan Gohman       continue;
1437b7787fd0SSam Clegg 
1438d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1439d34e60caSNicola Zaghen     LLVM_DEBUG(
1440d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1441d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1442d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1443d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1444b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1445b7787fd0SSam Clegg 
14465e3d33a7SSam Clegg     if (WS.isVariable())
14475e3d33a7SSam Clegg       continue;
14486c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14496c899ba6SSam Clegg       continue;
1450b7787fd0SSam Clegg 
1451d934cb88SDan Gohman     if (WS.isFunction()) {
14526c899ba6SSam Clegg       unsigned Index;
1453cd65f698SSam Clegg       if (WS.isDefined()) {
1454b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1455b7787fd0SSam Clegg           report_fatal_error(
1456b7787fd0SSam Clegg               "function sections must contain one function each");
1457b7787fd0SSam Clegg 
145818c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1459b7787fd0SSam Clegg           report_fatal_error(
1460b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1461b7787fd0SSam Clegg 
14626c899ba6SSam Clegg         // A definition. Write out the function body.
14639f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1464d934cb88SDan Gohman         WasmFunction Func;
1465da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1466d934cb88SDan Gohman         Func.Sym = &WS;
14676c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1468d934cb88SDan Gohman         Functions.push_back(Func);
14696c899ba6SSam Clegg 
14706c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14716c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14726c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14736c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14746c899ba6SSam Clegg         }
1475881d8778SSam Clegg 
1476881d8778SSam Clegg         if (WS.hasExportName()) {
1477881d8778SSam Clegg           wasm::WasmExport Export;
1478881d8778SSam Clegg           Export.Name = WS.getExportName();
1479881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1480881d8778SSam Clegg           Export.Index = Index;
1481881d8778SSam Clegg           Exports.push_back(Export);
1482881d8778SSam Clegg         }
1483d934cb88SDan Gohman       } else {
1484d934cb88SDan Gohman         // An import; the index was assigned above.
14856c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1486d934cb88SDan Gohman       }
1487d934cb88SDan Gohman 
1488d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1489da419bdbSHeejin Ahn 
14906c899ba6SSam Clegg     } else if (WS.isData()) {
1491f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1492c38e947eSSam Clegg         continue;
1493c38e947eSSam Clegg 
14946c899ba6SSam Clegg       if (!WS.isDefined()) {
1495d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1496d34e60caSNicola Zaghen                           << "\n");
1497fe6414b0SSam Clegg         continue;
14986c899ba6SSam Clegg       }
1499fe6414b0SSam Clegg 
1500d934cb88SDan Gohman       if (!WS.getSize())
1501c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1502c38e947eSSam Clegg                            WS.getName());
1503d934cb88SDan Gohman 
1504d934cb88SDan Gohman       int64_t Size = 0;
1505d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1506d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1507d934cb88SDan Gohman 
1508759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1509079cba04SSam Clegg       if (!DataSection.isWasmData())
1510079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1511079cba04SSam Clegg                            WS.getName());
15127c395943SSam Clegg 
15136c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
15146c899ba6SSam Clegg       // corresponding Wasm data segment.
15156c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
15163b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
15173b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
15186c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1519d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1520da419bdbSHeejin Ahn 
1521a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
15226c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
15230a6c4d8dSSam Clegg       if (WS.isDefined()) {
15240a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
15250a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
15260a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
15270a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
15280a6c4d8dSSam Clegg         switch (Global.Type.Type) {
15290a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
15300a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15310a6c4d8dSSam Clegg           break;
15320a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15330a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15340a6c4d8dSSam Clegg           break;
15350a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15360a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15370a6c4d8dSSam Clegg           break;
15380a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15390a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15400a6c4d8dSSam Clegg           break;
154179aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
154279aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
154379aad89dSSam Clegg           break;
15440a6c4d8dSSam Clegg         default:
15450a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15460a6c4d8dSSam Clegg         }
15470a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15480a6c4d8dSSam Clegg         Globals.push_back(Global);
15490a6c4d8dSSam Clegg       } else {
1550545932beSEric Christopher         // An import; the index was assigned above
1551d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1552d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15530a6c4d8dSSam Clegg       }
1554388fb67bSPaulo Matos     } else if (WS.isTable()) {
1555388fb67bSPaulo Matos       if (WS.isDefined()) {
1556388fb67bSPaulo Matos         assert(WasmIndices.count(&WS) == 0);
1557388fb67bSPaulo Matos         wasm::WasmTable Table;
1558388fb67bSPaulo Matos         Table.Index = NumTableImports + Tables.size();
15591933c9d4SAndy Wingo         Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1560388fb67bSPaulo Matos         // FIXME: Work on custom limits is ongoing
15611933c9d4SAndy Wingo         Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1562388fb67bSPaulo Matos 
1563388fb67bSPaulo Matos         WasmIndices[&WS] = Table.Index;
1564388fb67bSPaulo Matos         Tables.push_back(Table);
1565388fb67bSPaulo Matos       }
1566388fb67bSPaulo Matos       LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second
1567388fb67bSPaulo Matos                         << "\n");
1568da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1569da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1570da419bdbSHeejin Ahn       unsigned Index;
1571da419bdbSHeejin Ahn       if (WS.isDefined()) {
15720a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1573da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1574da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1575da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1576da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1577da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1578da419bdbSHeejin Ahn         Events.push_back(Event);
1579da419bdbSHeejin Ahn       } else {
1580da419bdbSHeejin Ahn         // An import; the index was assigned above.
1581492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1582da419bdbSHeejin Ahn       }
1583da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1584da419bdbSHeejin Ahn                         << "\n");
1585da419bdbSHeejin Ahn 
1586a165f2d6SSam Clegg     } else {
1587a165f2d6SSam Clegg       assert(WS.isSection());
1588d934cb88SDan Gohman     }
1589d934cb88SDan Gohman   }
1590d934cb88SDan Gohman 
1591586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1592586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1593586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1594586320c0SNicholas Wilson   // necessarily ordered in this way.
1595b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1596b7787fd0SSam Clegg     if (!S.isVariable())
1597b7787fd0SSam Clegg       continue;
159831a2c809SSam Clegg 
1599cd65f698SSam Clegg     assert(S.isDefined());
1600b7787fd0SSam Clegg 
16019c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
16029c7b5808SDominic Chen     if (!BS)
16039c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
16049c7b5808SDominic Chen                          ": absolute addressing not supported!");
16059c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
16067ee758d6SSam Clegg 
16075e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1608aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
16097ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1610b7787fd0SSam Clegg 
16117ee758d6SSam Clegg     if (Base->isFunction()) {
16127ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
16137ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1614492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
16156c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1616d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
16177ee758d6SSam Clegg     } else if (Base->isData()) {
16187ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
16197ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
16207ee758d6SSam Clegg       int64_t Size = 0;
16217ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
16227ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
16237ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
16247ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
16257ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
16267ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
16277ee758d6SSam Clegg       const WasmDataSegment &Segment =
16287ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
16297ee758d6SSam Clegg       Size =
16307ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16317ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
16327ee758d6SSam Clegg           DataSection.getSegmentIndex(),
16337ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16347ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
16356c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1636d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16376c899ba6SSam Clegg     } else {
1638da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16396c899ba6SSam Clegg     }
1640586320c0SNicholas Wilson   }
164131a2c809SSam Clegg 
1642586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1643586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1644586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
164525d8e68bSSam Clegg     if (!isInSymtab(WS)) {
164618c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1647586320c0SNicholas Wilson       continue;
164825d8e68bSSam Clegg     }
1649*feac819eSAndy Wingo     if (WS.isTable() && WS.getName() == "__indirect_function_table") {
1650*feac819eSAndy Wingo       // For the moment, don't emit table symbols -- wasm-ld can't handle them.
1651*feac819eSAndy Wingo       continue;
1652*feac819eSAndy Wingo     }
1653d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1654586320c0SNicholas Wilson 
1655586320c0SNicholas Wilson     uint32_t Flags = 0;
1656586320c0SNicholas Wilson     if (WS.isWeak())
1657586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1658586320c0SNicholas Wilson     if (WS.isHidden())
1659586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1660586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1661586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1662586320c0SNicholas Wilson     if (WS.isUndefined())
1663586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1664da84b688SDan Gohman     if (WS.isNoStrip()) {
1665da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1666da84b688SDan Gohman       if (isEmscripten()) {
1667d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1668da84b688SDan Gohman       }
1669da84b688SDan Gohman     }
1670b4f4e370SSam Clegg     if (WS.hasImportName())
167129874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1672881d8778SSam Clegg     if (WS.hasExportName())
1673881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1674586320c0SNicholas Wilson 
1675586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1676586320c0SNicholas Wilson     Info.Name = WS.getName();
1677586320c0SNicholas Wilson     Info.Kind = WS.getType();
1678586320c0SNicholas Wilson     Info.Flags = Flags;
16794d57fbd0SSam Clegg     if (!WS.isData()) {
16804d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1681586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16824d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16834d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1684586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16854d57fbd0SSam Clegg     }
168625d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1687586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1688b7787fd0SSam Clegg   }
1689b7787fd0SSam Clegg 
16906006e091SSam Clegg   {
16916006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1692f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1693f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1694f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1695d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1696cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
169781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1698cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
169981443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1700f9edbe95SSam Clegg         return;
1701f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
17027ee758d6SSam Clegg       const MCSymbolWasm *Base =
17037ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
17047ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
170518c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
17067ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
17077ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1708f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
17096c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
17107ee758d6SSam Clegg         registerFunctionType(*Base);
17116006e091SSam Clegg       }
17126006e091SSam Clegg     };
1713970d02c4SDan Gohman 
17146006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
17156006e091SSam Clegg       HandleReloc(RelEntry);
17166006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
17176006e091SSam Clegg       HandleReloc(RelEntry);
1718d934cb88SDan Gohman   }
1719d934cb88SDan Gohman 
1720bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1721bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1722bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
17237d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1724bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
17257d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1726bafe6902SSam Clegg       continue;
1727bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1728bafe6902SSam Clegg       continue;
1729b210c64bSSam Clegg 
1730b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1731b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1732bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1733b210c64bSSam Clegg 
1734b210c64bSSam Clegg     auto IT = WS.begin();
1735b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1736b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1737b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1738b210c64bSSam Clegg 
1739b210c64bSSam Clegg     IT = std::next(IT);
1740b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1741bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1742bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1743bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1744bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1745b210c64bSSam Clegg 
1746b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1747bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1748bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1749b210c64bSSam Clegg 
1750bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17514d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17527d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17537d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1754f208f631SHeejin Ahn         report_fatal_error(
1755f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17567d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1757bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1758bafe6902SSam Clegg     }
1759bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1760bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1761f208f631SHeejin Ahn     for (const uint8_t *
176218c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
176318c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
176418c56a07SHeejin Ahn          P != End; ++P) {
176518c56a07SHeejin Ahn       if (*P != 0)
1766bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1767bafe6902SSam Clegg     }
1768bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1769f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1770f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1771bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17728fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17738fffa1dfSSam Clegg       if (!SymRef)
1774bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17758fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17768fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17773ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17788fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17798fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
178025d8e68bSSam Clegg       InitFuncs.push_back(
17818fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1782bafe6902SSam Clegg     }
1783bafe6902SSam Clegg   }
1784bafe6902SSam Clegg 
178518eafb6cSDan Gohman   // Write out the Wasm header.
178618eafb6cSDan Gohman   writeHeader(Asm);
178718eafb6cSDan Gohman 
17880ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17890ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1790da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1791f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17929e15f359SSam Clegg     writeFunctionSection(Functions);
1793f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1794da419bdbSHeejin Ahn     writeEventSection(Events);
17950a6c4d8dSSam Clegg     writeGlobalSection(Globals);
1796388fb67bSPaulo Matos     writeTableSection(Tables);
17979e15f359SSam Clegg     writeExportSection(Exports);
17989e15f359SSam Clegg     writeElemSection(TableElems);
1799fef8de66SThomas Lively     writeDataCountSection();
18000ff28fa6SDerek Schuff 
18010ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
18020ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
18030ff28fa6SDerek Schuff   }
18040ff28fa6SDerek Schuff 
18050ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1806cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
18070ff28fa6SDerek Schuff   }
18080ff28fa6SDerek Schuff 
18090ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1810c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
18110ff28fa6SDerek Schuff 
18126f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
18136f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
18140ff28fa6SDerek Schuff   }
18156a31a0d6SSam Clegg   writeCustomRelocSections();
1816cbda16ebSThomas Lively   if (ProducersSection)
1817cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1818f6f4f843SThomas Lively   if (TargetFeaturesSection)
1819f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1820970d02c4SDan Gohman 
1821d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
18220ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
182318eafb6cSDan Gohman }
182418eafb6cSDan Gohman 
182560fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
18261301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
182718eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
18280eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
182918eafb6cSDan Gohman }
18300ff28fa6SDerek Schuff 
18310ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
18320ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18330ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
18340ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18350ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18360ff28fa6SDerek Schuff }
1837