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 
43feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is
44feac819eSAndy 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;
703b8d2be5SSam Clegg   uint32_t LinkingFlags;
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
1981d891d44SHeejin Ahn   // function/global/table/tag/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;
221feac819eSAndy Wingo   unsigned NumTableImports = 0;
2221d891d44SHeejin Ahn   unsigned NumTagImports = 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;
271feac819eSAndy 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);
314a5a3659dSAndy Wingo   void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
315a5a3659dSAndy Wingo                         ArrayRef<uint32_t> TableElems);
316fef8de66SThomas Lively   void writeDataCountSection();
317e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
318457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
319e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
320*3ec1760dSHeejin Ahn   void writeTagSection(ArrayRef<uint32_t> TagTypes);
3210a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
322388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3236f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
324f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32531a2c809SSam Clegg   void writeLinkingMetaDataSection(
32686b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
327ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
328ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
329cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
330cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3316a31a0d6SSam Clegg   void writeCustomRelocSections();
332acd7d2b0SSam Clegg 
3337ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3347ee758d6SSam Clegg                                const MCAsmLayout &Layout);
335acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3367ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
337acd7d2b0SSam Clegg 
338acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3395e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3401d891d44SHeejin Ahn   uint32_t getTagType(const MCSymbolWasm &Symbol);
34138b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
3421d891d44SHeejin Ahn   void registerTagType(const MCSymbolWasm &Symbol);
34318eafb6cSDan Gohman };
3449e15f359SSam Clegg 
34518eafb6cSDan Gohman } // end anonymous namespace
34618eafb6cSDan Gohman 
347d934cb88SDan Gohman // Write out a section header and a patchable section size field.
348d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3492322a937SSam Clegg                                     unsigned SectionId) {
350d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3510ff28fa6SDerek Schuff   W->OS << char(SectionId);
352d934cb88SDan Gohman 
3530ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
354d934cb88SDan Gohman 
355d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
356d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3570ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
358d934cb88SDan Gohman 
359d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3600ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3610ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3626f08c84aSSam Clegg   Section.Index = SectionCount++;
363d934cb88SDan Gohman }
3642322a937SSam Clegg 
3652322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3662322a937SSam Clegg                                           StringRef Name) {
367d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3682322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3696a31a0d6SSam Clegg 
3706a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3710ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3726a31a0d6SSam Clegg 
3732322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3742322a937SSam Clegg   writeString(Name);
3756a31a0d6SSam Clegg 
3766a31a0d6SSam Clegg   // The position where the custom section starts.
3770ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
378d934cb88SDan Gohman }
379d934cb88SDan Gohman 
380d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
381d934cb88SDan Gohman // section size field at the start of the section.
382d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3830ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
384c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
385c0affde8SSam Clegg   // Simply skip this patching in that case.
386c0affde8SSam Clegg   if (!Size)
387c0affde8SSam Clegg     return;
388c0affde8SSam Clegg 
389c0affde8SSam Clegg   Size -= Section.PayloadOffset;
390d934cb88SDan Gohman   if (uint32_t(Size) != Size)
391d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
392d934cb88SDan Gohman 
393d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
394d934cb88SDan Gohman 
395d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
396d934cb88SDan Gohman   // the section id byte.
3970ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
398f17b149dSPeter Collingbourne                        Section.SizeOffset);
399d934cb88SDan Gohman }
400d934cb88SDan Gohman 
40118eafb6cSDan Gohman // Emit the Wasm header.
40218eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4030ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4040ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40518eafb6cSDan Gohman }
40618eafb6cSDan Gohman 
40718eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
40818eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4092632ba6aSAndy Wingo   // Some compilation units require the indirect function table to be present
4102632ba6aSAndy Wingo   // but don't explicitly reference it.  This is the case for call_indirect
4112632ba6aSAndy Wingo   // without the reference-types feature, and also function bitcasts in all
4122632ba6aSAndy Wingo   // cases.  In those cases the __indirect_function_table has the
4132632ba6aSAndy Wingo   // WASM_SYMBOL_NO_STRIP attribute.  Here we make sure this symbol makes it to
4142632ba6aSAndy Wingo   // the assembler, if needed.
4152632ba6aSAndy Wingo   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
4162632ba6aSAndy Wingo     const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
4172632ba6aSAndy Wingo     if (WasmSym->isNoStrip())
41896ef4f30SSam Clegg       Asm.registerSymbol(*Sym);
4192632ba6aSAndy Wingo   }
42096ef4f30SSam Clegg 
4216ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4226ccb59b3SSam Clegg   // in recordRelocation.
4236ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4246ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4256ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4266ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4276ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4286ccb59b3SSam Clegg       if (!Pair.second)
4296ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4307d1ff446SFangrui Song                            Sec.getName());
4316ccb59b3SSam Clegg     }
4326ccb59b3SSam Clegg   }
43318eafb6cSDan Gohman }
43418eafb6cSDan Gohman 
43518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
43618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
43718eafb6cSDan Gohman                                         const MCFragment *Fragment,
43818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
439ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
440ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
441e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
442ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
443ecc5e808SSam Clegg 
444fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
445d934cb88SDan Gohman   uint64_t C = Target.getConstant();
446d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
447d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
448aa0c571aSYuta Saito   bool IsLocRel = false;
449d934cb88SDan Gohman 
450d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
451aa0c571aSYuta Saito 
452ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
453aa0c571aSYuta Saito 
454aa0c571aSYuta Saito     if (FixupSection.getKind().isText()) {
455aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
456d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
457aa0c571aSYuta Saito                           "' unsupported subtraction expression used in "
458aa0c571aSYuta Saito                           "relocation in code section.");
459d934cb88SDan Gohman       return;
460d934cb88SDan Gohman     }
461d934cb88SDan Gohman 
462aa0c571aSYuta Saito     if (SymB.isUndefined()) {
463aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
464aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
465aa0c571aSYuta Saito                           "' can not be undefined in a subtraction expression");
466aa0c571aSYuta Saito       return;
467aa0c571aSYuta Saito     }
468aa0c571aSYuta Saito     const MCSection &SecB = SymB.getSection();
469aa0c571aSYuta Saito     if (&SecB != &FixupSection) {
470aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
471aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
472aa0c571aSYuta Saito                           "' can not be placed in a different section");
473aa0c571aSYuta Saito       return;
474aa0c571aSYuta Saito     }
475aa0c571aSYuta Saito     IsLocRel = true;
476aa0c571aSYuta Saito     C += FixupOffset - Layout.getSymbolOffset(SymB);
477aa0c571aSYuta Saito   }
478aa0c571aSYuta Saito 
479d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
480d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
481ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
482d934cb88SDan Gohman 
4833ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4847d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4853ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4863ea1c62cSSam Clegg     return;
4873ea1c62cSSam Clegg   }
4883ea1c62cSSam Clegg 
489ecc5e808SSam Clegg   if (SymA->isVariable()) {
490d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4917ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4926ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4936ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
494d934cb88SDan Gohman   }
495d934cb88SDan Gohman 
496d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
497d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
498d934cb88SDan Gohman   // be negative and don't wrap.
499d934cb88SDan Gohman   FixedValue = 0;
500d934cb88SDan Gohman 
501ad1f5457SDerek Schuff   unsigned Type =
502ad1f5457SDerek Schuff       TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
5039d24fb7fSSam Clegg 
5044d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5054d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5064d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
507ad1f5457SDerek Schuff   if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
50816f02431SWouter van Oortmerssen        Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
509ad1f5457SDerek Schuff        Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
510ad1f5457SDerek Schuff       SymA->isDefined()) {
511ad1f5457SDerek Schuff     // SymA can be a temp data symbol that represents a function (in which case
512ad1f5457SDerek Schuff     // it needs to be replaced by the section symbol), [XXX and it apparently
513ad1f5457SDerek Schuff     // later gets changed again to a func symbol?] or it can be a real
514ad1f5457SDerek Schuff     // function symbol, in which case it can be left as-is.
515ad1f5457SDerek Schuff 
5164d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5174d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5184d57fbd0SSam Clegg                          "only supported in metadata sections");
5194d57fbd0SSam Clegg 
5204d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5214d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5225e5b2cb1SWouter van Oortmerssen     if (SecA.getKind().isText()) {
5235e5b2cb1SWouter van Oortmerssen       auto SecSymIt = SectionFunctions.find(&SecA);
5245e5b2cb1SWouter van Oortmerssen       if (SecSymIt == SectionFunctions.end())
5255e5b2cb1SWouter van Oortmerssen         report_fatal_error("section doesn\'t have defining symbol");
5265e5b2cb1SWouter van Oortmerssen       SectionSymbol = SecSymIt->second;
5275e5b2cb1SWouter van Oortmerssen     } else {
5284d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5295e5b2cb1SWouter van Oortmerssen     }
5304d57fbd0SSam Clegg     if (!SectionSymbol)
5314d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5324d57fbd0SSam Clegg 
5334d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5344d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5354d57fbd0SSam Clegg   }
5364d57fbd0SSam Clegg 
537feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
5383a293cbfSWouter van Oortmerssen       Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
539feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
540feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
541feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
542feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
543feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
5442632ba6aSAndy Wingo     // We require the function table to have already been defined.
545feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
546feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
547f23b259eSSam Clegg     if (!Sym) {
548f23b259eSSam Clegg       report_fatal_error("missing indirect function table symbol");
549feac819eSAndy Wingo     } else {
550f23b259eSSam Clegg       if (!Sym->isFunctionTable())
551f23b259eSSam Clegg         report_fatal_error("__indirect_function_table symbol has wrong type");
5522632ba6aSAndy Wingo       // Ensure that __indirect_function_table reaches the output.
5532632ba6aSAndy Wingo       Sym->setNoStrip();
5547dc98adbSAndy Wingo       Asm.registerSymbol(*Sym);
555861dbe1aSAndy Wingo     }
5562632ba6aSAndy Wingo   }
557feac819eSAndy Wingo 
558d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5594d57fbd0SSam Clegg   // against a named symbol.
560d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5614d57fbd0SSam Clegg     if (SymA->getName().empty())
5624d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5634d57fbd0SSam Clegg                          "supported by wasm");
5644d57fbd0SSam Clegg 
5654d57fbd0SSam Clegg     SymA->setUsedInReloc();
5664d57fbd0SSam Clegg   }
567ae03c1e7SSam Clegg 
568ef8c9135SSam Clegg   switch (RefA->getKind()) {
569ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_GOT:
570ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_WASM_GOT_TLS:
571492f7529SSam Clegg     SymA->setUsedInGOT();
572ef8c9135SSam Clegg     break;
573ef8c9135SSam Clegg   default:
574ef8c9135SSam Clegg     break;
575ef8c9135SSam Clegg   }
576492f7529SSam Clegg 
577d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
578d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
579d934cb88SDan Gohman 
5806a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
581d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5826a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
58312fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5846a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5856a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5866a31a0d6SSam Clegg   } else {
58712fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
588d934cb88SDan Gohman   }
5896a31a0d6SSam Clegg }
590d934cb88SDan Gohman 
591d934cb88SDan Gohman // Compute a value to write into the code at the location covered
59260ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
59360ec3034SSam Clegg // to make the object format more readable and more likely to be directly
59460ec3034SSam Clegg // useable.
5953b29376eSWouter van Oortmerssen uint64_t
5967ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5977ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
59848139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
59948139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
60048139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
601492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
602492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
603492f7529SSam Clegg   }
604492f7529SSam Clegg 
60560ec3034SSam Clegg   switch (RelEntry.Type) {
6062a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
6073a293cbfSWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
608d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
609cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
610cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
611cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
612f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
6137ee758d6SSam Clegg     const MCSymbolWasm *Base =
6147ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
6157ee758d6SSam Clegg     assert(Base->isFunction());
6163a293cbfSWouter van Oortmerssen     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
6173a293cbfSWouter van Oortmerssen         RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
6187ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
61981443ac1SSam Clegg     else
6207ee758d6SSam Clegg       return TableIndices[Base];
621f9edbe95SSam Clegg   }
622d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
6236c899ba6SSam Clegg     // Provisional value is same as the index
62460ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
625d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
626d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
62748139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
6281d891d44SHeejin Ahn   case wasm::R_WASM_TAG_INDEX_LEB:
62969e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
6301d891d44SHeejin Ahn     // Provisional value is function/global/tag Wasm index
631492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6326c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
633d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
63416f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
635d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
636ad1f5457SDerek Schuff     if (!RelEntry.Symbol->isDefined())
637ad1f5457SDerek Schuff       return 0;
6386a31a0d6SSam Clegg     const auto &Section =
6396a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6406a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6416a31a0d6SSam Clegg   }
642d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6433b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6443b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6453b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6462a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6473b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6483b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
649a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
650aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
651670944fbSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
652aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
6539c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
654270ed1b3SSam Clegg     // For undefined symbols, use zero
65501a48535SSam Clegg     if (!RelEntry.Symbol->isDefined())
656270ed1b3SSam Clegg       return 0;
65701a48535SSam Clegg     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
65801a48535SSam Clegg     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
659d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
66001a48535SSam Clegg     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
66160ec3034SSam Clegg   }
66260ec3034SSam Clegg   default:
66360ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
66460ec3034SSam Clegg   }
665d934cb88SDan Gohman }
666d934cb88SDan Gohman 
667759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
66863ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6697d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
670759631c7SSam Clegg 
67163ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
67263ebb813SSam Clegg 
673759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
674759631c7SSam Clegg     if (Frag.hasInstructions())
675759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
676759631c7SSam Clegg 
677759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
678759631c7SSam Clegg       if (Align->getValueSize() != 1)
679759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
680759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
681759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
682f208f631SHeejin Ahn       uint64_t Size =
683f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
684f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
685759631c7SSam Clegg       DataBytes.resize(Size, Value);
686759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
687588fad4dSNirav Dave       int64_t NumValues;
688588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
689d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
690588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
691588fad4dSNirav Dave                        Fill->getValue());
69224faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
69324faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
6941d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
695759631c7SSam Clegg     } else {
696759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
697759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
6981d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
699759631c7SSam Clegg     }
700759631c7SSam Clegg   }
701759631c7SSam Clegg 
702d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
703759631c7SSam Clegg }
704759631c7SSam Clegg 
70560ec3034SSam Clegg uint32_t
70660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
707d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
708b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
709b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
710b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
711acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
712acd7d2b0SSam Clegg   }
71360ec3034SSam Clegg 
71425d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
715acd7d2b0SSam Clegg }
716acd7d2b0SSam Clegg 
717d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
718d934cb88SDan Gohman // directly.
719acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
7207ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
7217ee758d6SSam Clegg     const MCAsmLayout &Layout) {
7220ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
723d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
724d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
725d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
726d934cb88SDan Gohman                       RelEntry.Offset;
727d934cb88SDan Gohman 
728d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
7297ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
73060ec3034SSam Clegg 
731acd7d2b0SSam Clegg     switch (RelEntry.Type) {
732d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
733d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
734d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
735d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
7361d891d44SHeejin Ahn     case wasm::R_WASM_TAG_INDEX_LEB:
73769e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
7383b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
7393b29376eSWouter van Oortmerssen       break;
7403b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7413b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
742d934cb88SDan Gohman       break;
743d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
744d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
745d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
746d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
74748139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
748aa0c571aSYuta Saito     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
7490a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
750d934cb88SDan Gohman       break;
751cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7523b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
75316f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
7543b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7553b29376eSWouter van Oortmerssen       break;
756d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7572a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
758d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7592a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
760a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
7613b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7623b29376eSWouter van Oortmerssen       break;
763cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7643a293cbfSWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
7653b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7663b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
767670944fbSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
7683b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
76960ec3034SSam Clegg       break;
770d934cb88SDan Gohman     default:
7719d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
772d934cb88SDan Gohman     }
773d934cb88SDan Gohman   }
77418eafb6cSDan Gohman }
77518eafb6cSDan Gohman 
7764c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7774c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
778da419bdbSHeejin Ahn   if (Signatures.empty())
7799e15f359SSam Clegg     return;
7809e15f359SSam Clegg 
7819e15f359SSam Clegg   SectionBookkeeping Section;
7829e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7839e15f359SSam Clegg 
7840ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7859e15f359SSam Clegg 
7864c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7870ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7880ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
789da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7909e15f359SSam Clegg       writeValueType(Ty);
7910ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
792da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7939e15f359SSam Clegg       writeValueType(Ty);
7949e15f359SSam Clegg   }
7959e15f359SSam Clegg 
7969e15f359SSam Clegg   endSection(Section);
7979e15f359SSam Clegg }
7989e15f359SSam Clegg 
7998defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
8004d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
801f950b24aSSam Clegg                                           uint32_t NumElements) {
8029e15f359SSam Clegg   if (Imports.empty())
8039e15f359SSam Clegg     return;
8049e15f359SSam Clegg 
8054d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
806f950b24aSSam Clegg 
8079e15f359SSam Clegg   SectionBookkeeping Section;
8089e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
8099e15f359SSam Clegg 
8100ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
8118defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
8128defa952SSam Clegg     writeString(Import.Module);
8138defa952SSam Clegg     writeString(Import.Field);
8140ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
8159e15f359SSam Clegg 
8169e15f359SSam Clegg     switch (Import.Kind) {
8179e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
8180ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
8199e15f359SSam Clegg       break;
8209e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
8210ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
8220ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
8239e15f359SSam Clegg       break;
824f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
8250ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
8260ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
827f950b24aSSam Clegg       break;
828f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
8290ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
8300ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
8310ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
832f950b24aSSam Clegg       break;
8331d891d44SHeejin Ahn     case wasm::WASM_EXTERNAL_TAG:
834*3ec1760dSHeejin Ahn       W->OS << char(0); // Reserved 'attribute' field
835*3ec1760dSHeejin Ahn       encodeULEB128(Import.SigIndex, W->OS);
836da419bdbSHeejin Ahn       break;
8379e15f359SSam Clegg     default:
8389e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
8399e15f359SSam Clegg     }
8409e15f359SSam Clegg   }
8419e15f359SSam Clegg 
8429e15f359SSam Clegg   endSection(Section);
8439e15f359SSam Clegg }
8449e15f359SSam Clegg 
845457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8469e15f359SSam Clegg   if (Functions.empty())
8479e15f359SSam Clegg     return;
8489e15f359SSam Clegg 
8499e15f359SSam Clegg   SectionBookkeeping Section;
8509e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8519e15f359SSam Clegg 
8520ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8539e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
8540ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   endSection(Section);
8579e15f359SSam Clegg }
8589e15f359SSam Clegg 
859*3ec1760dSHeejin Ahn void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) {
860*3ec1760dSHeejin Ahn   if (TagTypes.empty())
861da419bdbSHeejin Ahn     return;
862da419bdbSHeejin Ahn 
863da419bdbSHeejin Ahn   SectionBookkeeping Section;
8641d891d44SHeejin Ahn   startSection(Section, wasm::WASM_SEC_TAG);
865da419bdbSHeejin Ahn 
866*3ec1760dSHeejin Ahn   encodeULEB128(TagTypes.size(), W->OS);
867*3ec1760dSHeejin Ahn   for (uint32_t Index : TagTypes) {
868*3ec1760dSHeejin Ahn     W->OS << char(0); // Reserved 'attribute' field
869*3ec1760dSHeejin Ahn     encodeULEB128(Index, W->OS);
870da419bdbSHeejin Ahn   }
871da419bdbSHeejin Ahn 
872da419bdbSHeejin Ahn   endSection(Section);
873da419bdbSHeejin Ahn }
874da419bdbSHeejin Ahn 
8750a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8760a6c4d8dSSam Clegg   if (Globals.empty())
8770a6c4d8dSSam Clegg     return;
8780a6c4d8dSSam Clegg 
8790a6c4d8dSSam Clegg   SectionBookkeeping Section;
8800a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8810a6c4d8dSSam Clegg 
8820ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8830a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8840ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8850ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8860ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8870a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8880a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8890ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8900a6c4d8dSSam Clegg       break;
8910a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8920ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8930a6c4d8dSSam Clegg       break;
8940a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8950a6c4d8dSSam Clegg       writeI32(0);
8960a6c4d8dSSam Clegg       break;
8970a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8980a6c4d8dSSam Clegg       writeI64(0);
8990a6c4d8dSSam Clegg       break;
90079aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
90179aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
90279aad89dSSam Clegg       break;
9030a6c4d8dSSam Clegg     default:
9040a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
9050a6c4d8dSSam Clegg     }
9060ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
9070a6c4d8dSSam Clegg   }
9080a6c4d8dSSam Clegg 
9090a6c4d8dSSam Clegg   endSection(Section);
9100a6c4d8dSSam Clegg }
9110a6c4d8dSSam Clegg 
912388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
913388fb67bSPaulo Matos   if (Tables.empty())
914388fb67bSPaulo Matos     return;
915388fb67bSPaulo Matos 
916388fb67bSPaulo Matos   SectionBookkeeping Section;
917388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
918388fb67bSPaulo Matos 
919388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
920388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
9211933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
9221933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
9239ac5620cSAndy Wingo     encodeULEB128(Table.Type.Limits.Minimum, W->OS);
9241933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
9251933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
926388fb67bSPaulo Matos   }
927388fb67bSPaulo Matos   endSection(Section);
928388fb67bSPaulo Matos }
929388fb67bSPaulo Matos 
9308defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
9319e15f359SSam Clegg   if (Exports.empty())
9329e15f359SSam Clegg     return;
9339e15f359SSam Clegg 
9349e15f359SSam Clegg   SectionBookkeeping Section;
9359e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
9369e15f359SSam Clegg 
9370ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
9388defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
9398defa952SSam Clegg     writeString(Export.Name);
9400ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
9410ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
9429e15f359SSam Clegg   }
9439e15f359SSam Clegg 
9449e15f359SSam Clegg   endSection(Section);
9459e15f359SSam Clegg }
9469e15f359SSam Clegg 
947a5a3659dSAndy Wingo void WasmObjectWriter::writeElemSection(
948a5a3659dSAndy Wingo     const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
9499e15f359SSam Clegg   if (TableElems.empty())
9509e15f359SSam Clegg     return;
9519e15f359SSam Clegg 
952a5a3659dSAndy Wingo   assert(IndirectFunctionTable);
953a5a3659dSAndy Wingo 
9549e15f359SSam Clegg   SectionBookkeeping Section;
9559e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
9569e15f359SSam Clegg 
9570ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
958a5a3659dSAndy Wingo 
959a5a3659dSAndy Wingo   assert(WasmIndices.count(IndirectFunctionTable));
960a5a3659dSAndy Wingo   uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
961a5a3659dSAndy Wingo   uint32_t Flags = 0;
962a5a3659dSAndy Wingo   if (TableNumber)
963a5a3659dSAndy Wingo     Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
964a5a3659dSAndy Wingo   encodeULEB128(Flags, W->OS);
965a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
966a5a3659dSAndy Wingo     encodeULEB128(TableNumber, W->OS); // the table number
9679e15f359SSam Clegg 
9689e15f359SSam Clegg   // init expr for starting offset
9690ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
9700ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
9710ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9729e15f359SSam Clegg 
973a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
974a5a3659dSAndy Wingo     // We only write active function table initializers, for which the elem kind
975a5a3659dSAndy Wingo     // is specified to be written as 0x00 and interpreted to mean "funcref".
976a5a3659dSAndy Wingo     const uint8_t ElemKind = 0;
977a5a3659dSAndy Wingo     W->OS << ElemKind;
978a5a3659dSAndy Wingo   }
979a5a3659dSAndy Wingo 
9800ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9819e15f359SSam Clegg   for (uint32_t Elem : TableElems)
9820ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9839e15f359SSam Clegg 
9849e15f359SSam Clegg   endSection(Section);
9859e15f359SSam Clegg }
9869e15f359SSam Clegg 
987fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
988fef8de66SThomas Lively   if (DataSegments.empty())
989fef8de66SThomas Lively     return;
990fef8de66SThomas Lively 
991fef8de66SThomas Lively   SectionBookkeeping Section;
992fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9930ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
994fef8de66SThomas Lively   endSection(Section);
995fef8de66SThomas Lively }
996fef8de66SThomas Lively 
997e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
998457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
999457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
10009e15f359SSam Clegg   if (Functions.empty())
1001e49584a3SSam Clegg     return 0;
10029e15f359SSam Clegg 
10039e15f359SSam Clegg   SectionBookkeeping Section;
10049e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
10059e15f359SSam Clegg 
10060ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
10079e15f359SSam Clegg 
10089e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
1009fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
10109e15f359SSam Clegg 
10119e15f359SSam Clegg     int64_t Size = 0;
10129e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
10139e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
10149e15f359SSam Clegg 
10150ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
10160ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10170ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
10189e15f359SSam Clegg   }
10199e15f359SSam Clegg 
10209e15f359SSam Clegg   // Apply fixups.
10217ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
10229e15f359SSam Clegg 
10239e15f359SSam Clegg   endSection(Section);
1024e49584a3SSam Clegg   return Section.Index;
10259e15f359SSam Clegg }
10269e15f359SSam Clegg 
1027e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
10286c899ba6SSam Clegg   if (DataSegments.empty())
1029e49584a3SSam Clegg     return 0;
10309e15f359SSam Clegg 
10319e15f359SSam Clegg   SectionBookkeeping Section;
10329e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
10339e15f359SSam Clegg 
10340ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
10357c395943SSam Clegg 
10366c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
10370ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
1038831a143eSAndy Wingo     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
10390ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
1040831a143eSAndy Wingo     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
10410d9b17d0SWouter van Oortmerssen       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
10424d135b04SWouter van Oortmerssen                               : wasm::WASM_OPCODE_I32_CONST);
10430ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
10440ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
10452e150409SThomas Lively     }
10460ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
10470ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10480ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
10497c395943SSam Clegg   }
10509e15f359SSam Clegg 
10519e15f359SSam Clegg   // Apply fixups.
10527ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
10539e15f359SSam Clegg 
10549e15f359SSam Clegg   endSection(Section);
1055e49584a3SSam Clegg   return Section.Index;
10569e15f359SSam Clegg }
10579e15f359SSam Clegg 
10586f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
10596f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
1060f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
10619e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
10629e15f359SSam Clegg   // for descriptions of the reloc sections.
10639e15f359SSam Clegg 
1064f77dc2a8SSam Clegg   if (Relocs.empty())
10659e15f359SSam Clegg     return;
10669e15f359SSam Clegg 
1067f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1068f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1069f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1070f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1071f77dc2a8SSam Clegg   // not the sections order.
1072efd94c56SFangrui Song   llvm::stable_sort(
1073efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1074f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1075f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1076f77dc2a8SSam Clegg       });
1077f77dc2a8SSam Clegg 
10789e15f359SSam Clegg   SectionBookkeeping Section;
10796f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10809e15f359SSam Clegg 
10810ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
10820ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1083f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1084f208f631SHeejin Ahn     uint64_t Offset =
1085f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10866f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10879e15f359SSam Clegg 
10880ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10890ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10900ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10916f08c84aSSam Clegg     if (RelEntry.hasAddend())
10920ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10939e15f359SSam Clegg   }
10949e15f359SSam Clegg 
10959e15f359SSam Clegg   endSection(Section);
10969e15f359SSam Clegg }
10979e15f359SSam Clegg 
10986a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10996a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
11006a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
11016a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
11026a31a0d6SSam Clegg   }
11036a31a0d6SSam Clegg }
11046a31a0d6SSam Clegg 
11059e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
110686b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1107ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1108ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
11099e15f359SSam Clegg   SectionBookkeeping Section;
11102322a937SSam Clegg   startCustomSection(Section, "linking");
11110ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
11129e15f359SSam Clegg 
11136bb5a41fSSam Clegg   SectionBookkeeping SubSection;
11146c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
11156c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
11160ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
11176c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
11180ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
11190ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
11206c899ba6SSam Clegg       switch (Sym.Kind) {
11216c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
11226c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
11231d891d44SHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_TAG:
1124388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
11250ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
112629874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
112729874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
11286c899ba6SSam Clegg           writeString(Sym.Name);
11296c899ba6SSam Clegg         break;
11306c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
11316c899ba6SSam Clegg         writeString(Sym.Name);
11326c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
11330ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
11340ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
11350ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
11366c899ba6SSam Clegg         }
11376c899ba6SSam Clegg         break;
11386a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
11396a31a0d6SSam Clegg         const uint32_t SectionIndex =
11406a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
11410ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
11426a31a0d6SSam Clegg         break;
11436a31a0d6SSam Clegg       }
11446c899ba6SSam Clegg       default:
11456c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
11466c899ba6SSam Clegg       }
1147b7787fd0SSam Clegg     }
1148b7787fd0SSam Clegg     endSection(SubSection);
1149b7787fd0SSam Clegg   }
11509e15f359SSam Clegg 
11516c899ba6SSam Clegg   if (DataSegments.size()) {
115263ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
11530ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
11546c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1155d95ed959SSam Clegg       writeString(Segment.Name);
11560ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
11573b8d2be5SSam Clegg       encodeULEB128(Segment.LinkingFlags, W->OS);
115863ebb813SSam Clegg     }
1159d95ed959SSam Clegg     endSection(SubSection);
1160d95ed959SSam Clegg   }
1161d95ed959SSam Clegg 
1162bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1163bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
11640ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1165bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
11660ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
11670ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1168bafe6902SSam Clegg     }
1169bafe6902SSam Clegg     endSection(SubSection);
1170bafe6902SSam Clegg   }
1171bafe6902SSam Clegg 
1172ea7caceeSSam Clegg   if (Comdats.size()) {
1173ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
11740ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1175ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1176ea7caceeSSam Clegg       writeString(C.first);
11770ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
11780ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1179ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
11800ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
11810ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1182ea7caceeSSam Clegg       }
1183ea7caceeSSam Clegg     }
1184ea7caceeSSam Clegg     endSection(SubSection);
1185ea7caceeSSam Clegg   }
1186ea7caceeSSam Clegg 
11879e15f359SSam Clegg   endSection(Section);
11889e15f359SSam Clegg }
11899e15f359SSam Clegg 
1190cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1191cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11926a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1193cfd44a2eSSam Clegg   SectionBookkeeping Section;
11946a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11952322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11966a31a0d6SSam Clegg 
11970ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11980ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11996a31a0d6SSam Clegg 
12006a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
12016a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
12026a31a0d6SSam Clegg 
1203cfd44a2eSSam Clegg   endSection(Section);
12046a31a0d6SSam Clegg 
12056a31a0d6SSam Clegg   // Apply fixups.
12064d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
12077ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
12086a31a0d6SSam Clegg }
12096a31a0d6SSam Clegg 
12105e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
12115e3d33a7SSam Clegg   assert(Symbol.isFunction());
12125e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
12135e3d33a7SSam Clegg   return TypeIndices[&Symbol];
12145e3d33a7SSam Clegg }
12155e3d33a7SSam Clegg 
12161d891d44SHeejin Ahn uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) {
12171d891d44SHeejin Ahn   assert(Symbol.isTag());
1218da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1219da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1220da419bdbSHeejin Ahn }
1221da419bdbSHeejin Ahn 
122238b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
12235e3d33a7SSam Clegg   assert(Symbol.isFunction());
12245e3d33a7SSam Clegg 
12254c41fb5aSHeejin Ahn   wasm::WasmSignature S;
12267ee758d6SSam Clegg 
12277ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1228da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1229da419bdbSHeejin Ahn     S.Params = Sig->Params;
123077a7a380SDerek Schuff   }
12315e3d33a7SSam Clegg 
1232da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
12335e3d33a7SSam Clegg   if (Pair.second)
1234da419bdbSHeejin Ahn     Signatures.push_back(S);
12355e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
12365e3d33a7SSam Clegg 
1237d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1238d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1239d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
12405e3d33a7SSam Clegg }
12415e3d33a7SSam Clegg 
12421d891d44SHeejin Ahn void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) {
12431d891d44SHeejin Ahn   assert(Symbol.isTag());
1244da419bdbSHeejin Ahn 
1245da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1246da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
12474c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1248da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1249da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1250da419bdbSHeejin Ahn     S.Params = Sig->Params;
1251da419bdbSHeejin Ahn   }
1252da419bdbSHeejin Ahn 
1253da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1254da419bdbSHeejin Ahn   if (Pair.second)
1255da419bdbSHeejin Ahn     Signatures.push_back(S);
1256da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1257da419bdbSHeejin Ahn 
12581d891d44SHeejin Ahn   LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.second
1259da419bdbSHeejin Ahn                     << "\n");
1260da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1261da419bdbSHeejin Ahn }
1262da419bdbSHeejin Ahn 
12634d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
12643ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
12654d57fbd0SSam Clegg     return true;
12664d57fbd0SSam Clegg 
12674d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
12684d57fbd0SSam Clegg     return false;
12694d57fbd0SSam Clegg 
12703ea1c62cSSam Clegg   if (Sym.isTemporary())
12714d57fbd0SSam Clegg     return false;
12724d57fbd0SSam Clegg 
12734d57fbd0SSam Clegg   if (Sym.isSection())
12744d57fbd0SSam Clegg     return false;
12754d57fbd0SSam Clegg 
12762632ba6aSAndy Wingo   if (Sym.omitFromLinkingSection())
12772632ba6aSAndy Wingo     return false;
12782632ba6aSAndy Wingo 
12794d57fbd0SSam Clegg   return true;
12804d57fbd0SSam Clegg }
128130d314aaSSam Clegg 
12820ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
12830ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
128418eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1285f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1286f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1287f950b24aSSam Clegg   // it if there are no loads or stores.
12888defa952SSam Clegg   wasm::WasmImport MemImport;
12891ed3a046SSam Clegg   MemImport.Module = "env";
12901ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1291f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1292fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1293fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1294f950b24aSSam Clegg   Imports.push_back(MemImport);
1295f950b24aSSam Clegg 
1296da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1297586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1298586320c0SNicholas Wilson   // symbols.
129932ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
130032ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
130132ce5ca0SDan Gohman 
130232ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
13039f3fe42eSSam Clegg     // (because wasm always needs a type signature).
13047ee758d6SSam Clegg     if (WS.isFunction()) {
13059c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
13069c7b5808SDominic Chen       if (!BS)
13079c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
13089c7b5808SDominic Chen                            ": absolute addressing not supported!");
13099c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
13107ee758d6SSam Clegg     }
131132ce5ca0SDan Gohman 
13121d891d44SHeejin Ahn     if (WS.isTag())
13131d891d44SHeejin Ahn       registerTagType(WS);
1314da419bdbSHeejin Ahn 
131532ce5ca0SDan Gohman     if (WS.isTemporary())
131632ce5ca0SDan Gohman       continue;
131732ce5ca0SDan Gohman 
131832ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
13196c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
13206c899ba6SSam Clegg       if (WS.isFunction()) {
13218defa952SSam Clegg         wasm::WasmImport Import;
1322f726e445SDan Gohman         Import.Module = WS.getImportModule();
1323f726e445SDan Gohman         Import.Field = WS.getImportName();
132432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
13258defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
13266c899ba6SSam Clegg         Imports.push_back(Import);
1327492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13286c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
13296c899ba6SSam Clegg       } else if (WS.isGlobal()) {
133015f349f7SNicholas Wilson         if (WS.isWeak())
133115f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
133215f349f7SNicholas Wilson 
13336c899ba6SSam Clegg         wasm::WasmImport Import;
1334f726e445SDan Gohman         Import.Field = WS.getImportName();
133532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1336492f7529SSam Clegg         Import.Module = WS.getImportModule();
13376c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
13386c899ba6SSam Clegg         Imports.push_back(Import);
1339492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13406c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
13411d891d44SHeejin Ahn       } else if (WS.isTag()) {
1342da419bdbSHeejin Ahn         if (WS.isWeak())
13431d891d44SHeejin Ahn           report_fatal_error("undefined tag symbol cannot be weak");
1344da419bdbSHeejin Ahn 
1345da419bdbSHeejin Ahn         wasm::WasmImport Import;
1346f726e445SDan Gohman         Import.Module = WS.getImportModule();
1347f726e445SDan Gohman         Import.Field = WS.getImportName();
13481d891d44SHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_TAG;
1349*3ec1760dSHeejin Ahn         Import.SigIndex = getTagType(WS);
1350da419bdbSHeejin Ahn         Imports.push_back(Import);
1351492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13521d891d44SHeejin Ahn         WasmIndices[&WS] = NumTagImports++;
1353feac819eSAndy Wingo       } else if (WS.isTable()) {
1354feac819eSAndy Wingo         if (WS.isWeak())
1355feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1356feac819eSAndy Wingo 
1357feac819eSAndy Wingo         wasm::WasmImport Import;
1358feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1359feac819eSAndy Wingo         Import.Field = WS.getImportName();
1360feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1361c9801db2SAndy Wingo         Import.Table = WS.getTableType();
1362feac819eSAndy Wingo         Imports.push_back(Import);
1363feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1364feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
136532ce5ca0SDan Gohman       }
136632ce5ca0SDan Gohman     }
136732ce5ca0SDan Gohman   }
136832ce5ca0SDan Gohman 
1369492f7529SSam Clegg   // Add imports for GOT globals
1370492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1371492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1372492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1373492f7529SSam Clegg       wasm::WasmImport Import;
1374492f7529SSam Clegg       if (WS.isFunction())
1375492f7529SSam Clegg         Import.Module = "GOT.func";
1376492f7529SSam Clegg       else
1377492f7529SSam Clegg         Import.Module = "GOT.mem";
1378492f7529SSam Clegg       Import.Field = WS.getName();
1379492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1380492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1381492f7529SSam Clegg       Imports.push_back(Import);
1382492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1383492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1384492f7529SSam Clegg     }
1385492f7529SSam Clegg   }
13860ff28fa6SDerek Schuff }
1387492f7529SSam Clegg 
13880ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
13890ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
13900ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
13910ff28fa6SDerek Schuff   W = &MainWriter;
13920ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13930ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13940ff28fa6SDerek Schuff     assert(DwoOS);
13950ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13960ff28fa6SDerek Schuff     W = &DwoWriter;
13970ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13980ff28fa6SDerek Schuff   } else {
13990ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
14000ff28fa6SDerek Schuff   }
14010ff28fa6SDerek Schuff }
14020ff28fa6SDerek Schuff 
14030ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
14040ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
14050ff28fa6SDerek Schuff                                           DwoMode Mode) {
14060ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
14070ff28fa6SDerek Schuff   SectionCount = 0;
14080ff28fa6SDerek Schuff   CustomSections.clear();
14090ff28fa6SDerek Schuff 
14100ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
14110ff28fa6SDerek Schuff 
14120ff28fa6SDerek Schuff   // Collect information from the available symbols.
14130ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
14140ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
14150ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
14160ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
1417*3ec1760dSHeejin Ahn   SmallVector<uint32_t, 2> TagTypes;
14180ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1419388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
14200ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
14210ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
14220ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
14230ff28fa6SDerek Schuff   uint64_t DataSize = 0;
14240ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
14250ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
14260ff28fa6SDerek Schuff   }
142730d314aaSSam Clegg 
14284d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
14294d57fbd0SSam Clegg   // populating DataLocations.
1430759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1431759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
14327d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1433759631c7SSam Clegg 
14340ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
14350ff28fa6SDerek Schuff       continue;
14360ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
14370ff28fa6SDerek Schuff       continue;
14380ff28fa6SDerek Schuff 
14398d396acaSDerek Schuff     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
14408d396acaSDerek Schuff                       << Section.getGroup() << "\n";);
14418d396acaSDerek Schuff 
1442bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
14434d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1444bafe6902SSam Clegg       continue;
1445bafe6902SSam Clegg 
14464d57fbd0SSam Clegg     // Code is handled separately
14474d57fbd0SSam Clegg     if (Section.getKind().isText())
14484d57fbd0SSam Clegg       continue;
14494d57fbd0SSam Clegg 
14504d57fbd0SSam Clegg     if (Section.isWasmData()) {
1451329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1452759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1453759631c7SSam Clegg       DataSegments.emplace_back();
1454759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
14554d57fbd0SSam Clegg       Segment.Name = SectionName;
1456831a143eSAndy Wingo       Segment.InitFlags = Section.getPassive()
1457831a143eSAndy Wingo                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1458831a143eSAndy Wingo                               : 0;
1459759631c7SSam Clegg       Segment.Offset = DataSize;
1460759631c7SSam Clegg       Segment.Section = &Section;
146163ebb813SSam Clegg       addData(Segment.Data, Section);
146256c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
14633b8d2be5SSam Clegg       Segment.LinkingFlags = Section.getSegmentFlags();
1464759631c7SSam Clegg       DataSize += Segment.Data.size();
14656c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1466ea7caceeSSam Clegg 
1467ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1468ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1469329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1470ea7caceeSSam Clegg       }
14714d57fbd0SSam Clegg     } else {
14724d57fbd0SSam Clegg       // Create custom sections
14734d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
14744d57fbd0SSam Clegg 
14754d57fbd0SSam Clegg       StringRef Name = SectionName;
14764d57fbd0SSam Clegg 
14774d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
14784d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
14794d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
14804d57fbd0SSam Clegg 
14814d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1482fb807d4dSSam Clegg       if (Begin) {
148330d314aaSSam Clegg         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
14844d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1485fb807d4dSSam Clegg       }
1486cbda16ebSThomas Lively 
1487f6f4f843SThomas Lively       // Separate out the producers and target features sections
1488cbda16ebSThomas Lively       if (Name == "producers") {
14890eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1490cbda16ebSThomas Lively         continue;
1491cbda16ebSThomas Lively       }
1492f6f4f843SThomas Lively       if (Name == "target_features") {
1493f6f4f843SThomas Lively         TargetFeaturesSection =
14940eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1495f6f4f843SThomas Lively         continue;
1496f6f4f843SThomas Lively       }
1497cbda16ebSThomas Lively 
14980a391060SDerek Schuff       // Custom sections can also belong to COMDAT groups. In this case the
14990a391060SDerek Schuff       // decriptor's "index" field is the section index (in the final object
15000a391060SDerek Schuff       // file), but that is not known until after layout, so it must be fixed up
15010a391060SDerek Schuff       // later
15020a391060SDerek Schuff       if (const MCSymbolWasm *C = Section.getGroup()) {
15030a391060SDerek Schuff         Comdats[C->getName()].emplace_back(
15040a391060SDerek Schuff             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
15050a391060SDerek Schuff                             static_cast<uint32_t>(CustomSections.size())});
15060a391060SDerek Schuff       }
15070a391060SDerek Schuff 
15084d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1509759631c7SSam Clegg     }
15106a31a0d6SSam Clegg   }
15116a31a0d6SSam Clegg 
151230d314aaSSam Clegg   if (Mode != DwoMode::DwoOnly) {
1513586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for defined symbols.
1514d934cb88SDan Gohman     for (const MCSymbol &S : Asm.symbols()) {
1515d934cb88SDan Gohman       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1516d934cb88SDan Gohman       // or used in relocations.
1517d934cb88SDan Gohman       if (S.isTemporary() && S.getName().empty())
1518d934cb88SDan Gohman         continue;
1519b7787fd0SSam Clegg 
1520d934cb88SDan Gohman       const auto &WS = static_cast<const MCSymbolWasm &>(S);
15215e5b2cb1SWouter van Oortmerssen       LLVM_DEBUG(dbgs()
15225e5b2cb1SWouter van Oortmerssen                  << "MCSymbol: "
15235e5b2cb1SWouter van Oortmerssen                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
15245e5b2cb1SWouter van Oortmerssen                  << " '" << S << "'"
1525d34e60caSNicola Zaghen                  << " isDefined=" << S.isDefined() << " isExternal="
1526d34e60caSNicola Zaghen                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1527d34e60caSNicola Zaghen                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1528b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1529b7787fd0SSam Clegg 
15305e3d33a7SSam Clegg       if (WS.isVariable())
15315e3d33a7SSam Clegg         continue;
15326c899ba6SSam Clegg       if (WS.isComdat() && !WS.isDefined())
15336c899ba6SSam Clegg         continue;
1534b7787fd0SSam Clegg 
1535d934cb88SDan Gohman       if (WS.isFunction()) {
15366c899ba6SSam Clegg         unsigned Index;
1537cd65f698SSam Clegg         if (WS.isDefined()) {
1538b7787fd0SSam Clegg           if (WS.getOffset() != 0)
1539b7787fd0SSam Clegg             report_fatal_error(
1540b7787fd0SSam Clegg                 "function sections must contain one function each");
1541b7787fd0SSam Clegg 
154218c56a07SHeejin Ahn           if (WS.getSize() == nullptr)
1543b7787fd0SSam Clegg             report_fatal_error(
1544b7787fd0SSam Clegg                 "function symbols must have a size set with .size");
1545b7787fd0SSam Clegg 
15466c899ba6SSam Clegg           // A definition. Write out the function body.
15479f3fe42eSSam Clegg           Index = NumFunctionImports + Functions.size();
1548d934cb88SDan Gohman           WasmFunction Func;
1549da419bdbSHeejin Ahn           Func.SigIndex = getFunctionType(WS);
1550d934cb88SDan Gohman           Func.Sym = &WS;
155130d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
15526c899ba6SSam Clegg           WasmIndices[&WS] = Index;
1553d934cb88SDan Gohman           Functions.push_back(Func);
15546c899ba6SSam Clegg 
15556c899ba6SSam Clegg           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
15566c899ba6SSam Clegg           if (const MCSymbolWasm *C = Section.getGroup()) {
15576c899ba6SSam Clegg             Comdats[C->getName()].emplace_back(
15586c899ba6SSam Clegg                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
15596c899ba6SSam Clegg           }
1560881d8778SSam Clegg 
1561881d8778SSam Clegg           if (WS.hasExportName()) {
1562881d8778SSam Clegg             wasm::WasmExport Export;
1563881d8778SSam Clegg             Export.Name = WS.getExportName();
1564881d8778SSam Clegg             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1565881d8778SSam Clegg             Export.Index = Index;
1566881d8778SSam Clegg             Exports.push_back(Export);
1567881d8778SSam Clegg           }
1568d934cb88SDan Gohman         } else {
1569d934cb88SDan Gohman           // An import; the index was assigned above.
15706c899ba6SSam Clegg           Index = WasmIndices.find(&WS)->second;
1571d934cb88SDan Gohman         }
1572d934cb88SDan Gohman 
1573d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1574da419bdbSHeejin Ahn 
15756c899ba6SSam Clegg       } else if (WS.isData()) {
1576f3feb6adSWouter van Oortmerssen         if (!isInSymtab(WS))
1577c38e947eSSam Clegg           continue;
1578c38e947eSSam Clegg 
15796c899ba6SSam Clegg         if (!WS.isDefined()) {
1580d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1581d34e60caSNicola Zaghen                             << "\n");
1582fe6414b0SSam Clegg           continue;
15836c899ba6SSam Clegg         }
1584fe6414b0SSam Clegg 
1585d934cb88SDan Gohman         if (!WS.getSize())
1586c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1587c38e947eSSam Clegg                              WS.getName());
1588d934cb88SDan Gohman 
1589d934cb88SDan Gohman         int64_t Size = 0;
1590d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1591d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1592d934cb88SDan Gohman 
1593759631c7SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1594079cba04SSam Clegg         if (!DataSection.isWasmData())
1595079cba04SSam Clegg           report_fatal_error("data symbols must live in a data section: " +
1596079cba04SSam Clegg                              WS.getName());
15977c395943SSam Clegg 
15986c899ba6SSam Clegg         // For each data symbol, export it in the symtab as a reference to the
15996c899ba6SSam Clegg         // corresponding Wasm data segment.
16006c899ba6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16013b29376eSWouter van Oortmerssen             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
16023b29376eSWouter van Oortmerssen             static_cast<uint64_t>(Size)};
160330d314aaSSam Clegg         assert(DataLocations.count(&WS) == 0);
16046c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1605d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1606da419bdbSHeejin Ahn 
1607a165f2d6SSam Clegg       } else if (WS.isGlobal()) {
16086c899ba6SSam Clegg         // A "true" Wasm global (currently just __stack_pointer)
16090a6c4d8dSSam Clegg         if (WS.isDefined()) {
16100a6c4d8dSSam Clegg           wasm::WasmGlobal Global;
16110a6c4d8dSSam Clegg           Global.Type = WS.getGlobalType();
16120a6c4d8dSSam Clegg           Global.Index = NumGlobalImports + Globals.size();
16130a6c4d8dSSam Clegg           switch (Global.Type.Type) {
16140a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I32:
16150a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
16160a6c4d8dSSam Clegg             break;
16170a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I64:
16180a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
16190a6c4d8dSSam Clegg             break;
16200a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F32:
16210a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
16220a6c4d8dSSam Clegg             break;
16230a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F64:
16240a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
16250a6c4d8dSSam Clegg             break;
162679aad89dSSam Clegg           case wasm::WASM_TYPE_EXTERNREF:
162779aad89dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
162879aad89dSSam Clegg             break;
16290a6c4d8dSSam Clegg           default:
16300a6c4d8dSSam Clegg             llvm_unreachable("unexpected type");
16310a6c4d8dSSam Clegg           }
163230d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
16330a6c4d8dSSam Clegg           WasmIndices[&WS] = Global.Index;
16340a6c4d8dSSam Clegg           Globals.push_back(Global);
16350a6c4d8dSSam Clegg         } else {
1636545932beSEric Christopher           // An import; the index was assigned above
1637d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> global index: "
1638d34e60caSNicola Zaghen                             << WasmIndices.find(&WS)->second << "\n");
16390a6c4d8dSSam Clegg         }
1640388fb67bSPaulo Matos       } else if (WS.isTable()) {
1641388fb67bSPaulo Matos         if (WS.isDefined()) {
1642388fb67bSPaulo Matos           wasm::WasmTable Table;
1643388fb67bSPaulo Matos           Table.Index = NumTableImports + Tables.size();
1644c9801db2SAndy Wingo           Table.Type = WS.getTableType();
164530d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1646388fb67bSPaulo Matos           WasmIndices[&WS] = Table.Index;
1647388fb67bSPaulo Matos           Tables.push_back(Table);
1648388fb67bSPaulo Matos         }
164930d314aaSSam Clegg         LLVM_DEBUG(dbgs() << " -> table index: "
165030d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
16511d891d44SHeejin Ahn       } else if (WS.isTag()) {
165228780e59SHeejin Ahn         // C++ exception symbol (__cpp_exception) or longjmp symbol
165328780e59SHeejin Ahn         // (__c_longjmp)
1654da419bdbSHeejin Ahn         unsigned Index;
1655da419bdbSHeejin Ahn         if (WS.isDefined()) {
1656*3ec1760dSHeejin Ahn           Index = NumTagImports + TagTypes.size();
1657*3ec1760dSHeejin Ahn           uint32_t SigIndex = getTagType(WS);
165830d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1659da419bdbSHeejin Ahn           WasmIndices[&WS] = Index;
1660*3ec1760dSHeejin Ahn           TagTypes.push_back(SigIndex);
1661da419bdbSHeejin Ahn         } else {
1662da419bdbSHeejin Ahn           // An import; the index was assigned above.
1663492f7529SSam Clegg           assert(WasmIndices.count(&WS) > 0);
1664da419bdbSHeejin Ahn         }
16651d891d44SHeejin Ahn         LLVM_DEBUG(dbgs() << "  -> tag index: " << WasmIndices.find(&WS)->second
16661d891d44SHeejin Ahn                           << "\n");
1667da419bdbSHeejin Ahn 
1668a165f2d6SSam Clegg       } else {
1669a165f2d6SSam Clegg         assert(WS.isSection());
1670d934cb88SDan Gohman       }
1671d934cb88SDan Gohman     }
1672d934cb88SDan Gohman 
1673586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1674586320c0SNicholas Wilson     // process these in a separate pass because we need to have processed the
1675586320c0SNicholas Wilson     // target of the alias before the alias itself and the symbols are not
1676586320c0SNicholas Wilson     // necessarily ordered in this way.
1677b7787fd0SSam Clegg     for (const MCSymbol &S : Asm.symbols()) {
1678b7787fd0SSam Clegg       if (!S.isVariable())
1679b7787fd0SSam Clegg         continue;
168031a2c809SSam Clegg 
1681cd65f698SSam Clegg       assert(S.isDefined());
1682b7787fd0SSam Clegg 
16839c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
16849c7b5808SDominic Chen       if (!BS)
16859c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
16869c7b5808SDominic Chen                            ": absolute addressing not supported!");
16879c7b5808SDominic Chen       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
16887ee758d6SSam Clegg 
16895e3d33a7SSam Clegg       // Find the target symbol of this weak alias and export that index
1690aff1c4dfSSam Clegg       const auto &WS = static_cast<const MCSymbolWasm &>(S);
169130d314aaSSam Clegg       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
169230d314aaSSam Clegg                         << "'\n");
1693b7787fd0SSam Clegg 
16947ee758d6SSam Clegg       if (Base->isFunction()) {
16957ee758d6SSam Clegg         assert(WasmIndices.count(Base) > 0);
16967ee758d6SSam Clegg         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1697492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
16986c899ba6SSam Clegg         WasmIndices[&WS] = WasmIndex;
1699d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
17007ee758d6SSam Clegg       } else if (Base->isData()) {
17017ee758d6SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
17027ee758d6SSam Clegg         uint64_t Offset = Layout.getSymbolOffset(S);
17037ee758d6SSam Clegg         int64_t Size = 0;
17047ee758d6SSam Clegg         // For data symbol alias we use the size of the base symbol as the
17057ee758d6SSam Clegg         // size of the alias.  When an offset from the base is involved this
17067ee758d6SSam Clegg         // can result in a offset + size goes past the end of the data section
17077ee758d6SSam Clegg         // which out object format doesn't support.  So we must clamp it.
17087ee758d6SSam Clegg         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
17097ee758d6SSam Clegg           report_fatal_error(".size expression must be evaluatable");
17107ee758d6SSam Clegg         const WasmDataSegment &Segment =
17117ee758d6SSam Clegg             DataSegments[DataSection.getSegmentIndex()];
17127ee758d6SSam Clegg         Size =
17137ee758d6SSam Clegg             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
17147ee758d6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
17157ee758d6SSam Clegg             DataSection.getSegmentIndex(),
17167ee758d6SSam Clegg             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
17177ee758d6SSam Clegg             static_cast<uint32_t>(Size)};
17186c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1719d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
17206c899ba6SSam Clegg       } else {
17211d891d44SHeejin Ahn         report_fatal_error("don't yet support global/tag aliases");
17226c899ba6SSam Clegg       }
1723586320c0SNicholas Wilson     }
172430d314aaSSam Clegg   }
172531a2c809SSam Clegg 
1726586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1727586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1728586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
172925d8e68bSSam Clegg     if (!isInSymtab(WS)) {
173018c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1731586320c0SNicholas Wilson       continue;
173225d8e68bSSam Clegg     }
1733d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1734586320c0SNicholas Wilson 
1735586320c0SNicholas Wilson     uint32_t Flags = 0;
1736586320c0SNicholas Wilson     if (WS.isWeak())
1737586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1738586320c0SNicholas Wilson     if (WS.isHidden())
1739586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1740586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1741586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1742586320c0SNicholas Wilson     if (WS.isUndefined())
1743586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1744da84b688SDan Gohman     if (WS.isNoStrip()) {
1745da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1746da84b688SDan Gohman       if (isEmscripten()) {
1747d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1748da84b688SDan Gohman       }
1749da84b688SDan Gohman     }
1750b4f4e370SSam Clegg     if (WS.hasImportName())
175129874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1752881d8778SSam Clegg     if (WS.hasExportName())
1753881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
175444177e5fSSam Clegg     if (WS.isTLS())
175544177e5fSSam Clegg       Flags |= wasm::WASM_SYMBOL_TLS;
1756586320c0SNicholas Wilson 
1757586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1758586320c0SNicholas Wilson     Info.Name = WS.getName();
17595e5b2cb1SWouter van Oortmerssen     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1760586320c0SNicholas Wilson     Info.Flags = Flags;
17614d57fbd0SSam Clegg     if (!WS.isData()) {
17624d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1763586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
17644d57fbd0SSam Clegg     } else if (WS.isDefined()) {
17654d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1766586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
17674d57fbd0SSam Clegg     }
176825d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1769586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1770b7787fd0SSam Clegg   }
1771b7787fd0SSam Clegg 
17726006e091SSam Clegg   {
17736006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1774f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1775f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1776f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1777d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1778cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
177981443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1780cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
17813a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB &&
17823a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
1783f9edbe95SSam Clegg         return;
1784f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
17857ee758d6SSam Clegg       const MCSymbolWasm *Base =
17867ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
17877ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
178818c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
17897ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
17907ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1791f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
17926c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
17937ee758d6SSam Clegg         registerFunctionType(*Base);
17946006e091SSam Clegg       }
17956006e091SSam Clegg     };
1796970d02c4SDan Gohman 
17976006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
17986006e091SSam Clegg       HandleReloc(RelEntry);
17996006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
18006006e091SSam Clegg       HandleReloc(RelEntry);
1801d934cb88SDan Gohman   }
1802d934cb88SDan Gohman 
1803bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1804bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1805bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
18067d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1807bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
18087d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1809bafe6902SSam Clegg       continue;
1810bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1811bafe6902SSam Clegg       continue;
1812b210c64bSSam Clegg 
1813b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1814b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1815bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1816b210c64bSSam Clegg 
1817b210c64bSSam Clegg     auto IT = WS.begin();
1818b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1819b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1820b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1821b210c64bSSam Clegg 
1822b210c64bSSam Clegg     IT = std::next(IT);
1823b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1824bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1825bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1826bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1827bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1828b210c64bSSam Clegg 
1829b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1830bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1831bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1832b210c64bSSam Clegg 
1833bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
18344d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
18357d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
18367d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1837f208f631SHeejin Ahn         report_fatal_error(
1838f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
18397d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1840bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1841bafe6902SSam Clegg     }
1842bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1843bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1844f208f631SHeejin Ahn     for (const uint8_t *
184518c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
184618c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
184718c56a07SHeejin Ahn          P != End; ++P) {
184818c56a07SHeejin Ahn       if (*P != 0)
1849bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1850bafe6902SSam Clegg     }
1851bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1852f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1853f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1854bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
18558fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
18568fffa1dfSSam Clegg       if (!SymRef)
1857bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
18588fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
18598fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
18603ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
18618fffa1dfSSam Clegg       if (!TargetSym.isFunction())
18628fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
186325d8e68bSSam Clegg       InitFuncs.push_back(
18648fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1865bafe6902SSam Clegg     }
1866bafe6902SSam Clegg   }
1867bafe6902SSam Clegg 
186818eafb6cSDan Gohman   // Write out the Wasm header.
186918eafb6cSDan Gohman   writeHeader(Asm);
187018eafb6cSDan Gohman 
18710ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
18720ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1873da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1874f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
18759e15f359SSam Clegg     writeFunctionSection(Functions);
1876d823cc7cSAndy Wingo     writeTableSection(Tables);
1877f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1878*3ec1760dSHeejin Ahn     writeTagSection(TagTypes);
18790a6c4d8dSSam Clegg     writeGlobalSection(Globals);
18809e15f359SSam Clegg     writeExportSection(Exports);
1881a5a3659dSAndy Wingo     const MCSymbol *IndirectFunctionTable =
1882a5a3659dSAndy Wingo         Asm.getContext().lookupSymbol("__indirect_function_table");
1883a5a3659dSAndy Wingo     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1884a5a3659dSAndy Wingo                      TableElems);
1885fef8de66SThomas Lively     writeDataCountSection();
18860ff28fa6SDerek Schuff 
18870ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
18880ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
18890ff28fa6SDerek Schuff   }
18900ff28fa6SDerek Schuff 
18910a391060SDerek Schuff   // The Sections in the COMDAT list have placeholder indices (their index among
18920a391060SDerek Schuff   // custom sections, rather than among all sections). Fix them up here.
18930a391060SDerek Schuff   for (auto &Group : Comdats) {
18940a391060SDerek Schuff     for (auto &Entry : Group.second) {
18950a391060SDerek Schuff       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
18960a391060SDerek Schuff         Entry.Index += SectionCount;
18970ff28fa6SDerek Schuff       }
18980a391060SDerek Schuff     }
18990a391060SDerek Schuff   }
19000a391060SDerek Schuff   for (auto &CustomSection : CustomSections)
19010a391060SDerek Schuff     writeCustomSection(CustomSection, Asm, Layout);
19020ff28fa6SDerek Schuff 
19030ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1904c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
19050ff28fa6SDerek Schuff 
19066f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
19076f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
19080ff28fa6SDerek Schuff   }
19096a31a0d6SSam Clegg   writeCustomRelocSections();
1910cbda16ebSThomas Lively   if (ProducersSection)
1911cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1912f6f4f843SThomas Lively   if (TargetFeaturesSection)
1913f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1914970d02c4SDan Gohman 
1915d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
19160ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
191718eafb6cSDan Gohman }
191818eafb6cSDan Gohman 
191960fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
19201301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
192118eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
19220eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
192318eafb6cSDan Gohman }
19240ff28fa6SDerek Schuff 
19250ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
19260ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
19270ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
19280ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
19290ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
19300ff28fa6SDerek Schuff }
1931