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;
702e150409SThomas Lively   uint32_t LinkerFlags;
717c395943SSam Clegg   SmallVector<char, 4> Data;
727c395943SSam Clegg };
737c395943SSam Clegg 
749e15f359SSam Clegg // A wasm function to be written into the function section.
759e15f359SSam Clegg struct WasmFunction {
76da419bdbSHeejin Ahn   uint32_t SigIndex;
779e15f359SSam Clegg   const MCSymbolWasm *Sym;
789e15f359SSam Clegg };
799e15f359SSam Clegg 
809e15f359SSam Clegg // A wasm global to be written into the global section.
819e15f359SSam Clegg struct WasmGlobal {
826e7f1826SSam Clegg   wasm::WasmGlobalType Type;
839e15f359SSam Clegg   uint64_t InitialValue;
849e15f359SSam Clegg };
859e15f359SSam Clegg 
86ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
87ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
88ea7caceeSSam Clegg // WasmComdatEntry.
89ea7caceeSSam Clegg struct WasmComdatEntry {
90ea7caceeSSam Clegg   unsigned Kind;
91ea7caceeSSam Clegg   uint32_t Index;
92ea7caceeSSam Clegg };
93ea7caceeSSam Clegg 
946dc65e91SSam Clegg // Information about a single relocation.
956dc65e91SSam Clegg struct WasmRelocationEntry {
966dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
976dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
986dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
996dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
100fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1016dc65e91SSam Clegg 
1026dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1036dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
104fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1056dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1066dc65e91SSam Clegg         FixupSection(FixupSection) {}
1076dc65e91SSam Clegg 
108cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109acd7d2b0SSam Clegg 
1106dc65e91SSam Clegg   void print(raw_ostream &Out) const {
111f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1137d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1146dc65e91SSam Clegg   }
115b7787fd0SSam Clegg 
116615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118b7787fd0SSam Clegg #endif
1196dc65e91SSam Clegg };
1206dc65e91SSam Clegg 
12118c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12225d8e68bSSam Clegg 
123cfd44a2eSSam Clegg struct WasmCustomSection {
124cfd44a2eSSam Clegg 
1256a31a0d6SSam Clegg   StringRef Name;
1266a31a0d6SSam Clegg   MCSectionWasm *Section;
1276a31a0d6SSam Clegg 
1286a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1296a31a0d6SSam Clegg   uint32_t OutputIndex;
1306a31a0d6SSam Clegg 
1316a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1326a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
13318c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
134cfd44a2eSSam Clegg };
135cfd44a2eSSam Clegg 
1361fb8daa6SSam Clegg #if !defined(NDEBUG)
1377f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138b7787fd0SSam Clegg   Rel.print(OS);
139b7787fd0SSam Clegg   return OS;
140b7787fd0SSam Clegg }
1411fb8daa6SSam Clegg #endif
142b7787fd0SSam Clegg 
14319e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
14419e8befaSSam Clegg // to allow patching.
1453b29376eSWouter van Oortmerssen template <int W>
1463b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1473b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1483b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1493b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15119e8befaSSam Clegg }
15219e8befaSSam Clegg 
15319e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
15419e8befaSSam Clegg // to allow patching.
1553b29376eSWouter van Oortmerssen template <int W>
1563b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
1573b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1583b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
1593b29376eSWouter van Oortmerssen   assert(SizeLen == W);
16019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
16119e8befaSSam Clegg }
16219e8befaSSam Clegg 
16319e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
1640a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
16519e8befaSSam Clegg   uint8_t Buffer[4];
16619e8befaSSam Clegg   support::endian::write32le(Buffer, X);
16719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
16819e8befaSSam Clegg }
16919e8befaSSam Clegg 
1703b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1713b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
1723b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
1733b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1743b29376eSWouter van Oortmerssen }
1753b29376eSWouter van Oortmerssen 
1760ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1770ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1780ff28fa6SDerek Schuff }
1790ff28fa6SDerek Schuff 
18018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
1810ff28fa6SDerek Schuff   support::endian::Writer *W;
182f17b149dSPeter Collingbourne 
18318eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18418eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18518eafb6cSDan Gohman 
186d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
187d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
188d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
189d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
190d934cb88SDan Gohman 
191d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
192acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
193acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
195d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
196f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197388fb67bSPaulo Matos   // Maps function/global/table symbols to the
198388fb67bSPaulo Matos   // function/global/table/event/section index space.
1996c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
200492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2016c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2026c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2036a31a0d6SSam Clegg 
2046a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2056a31a0d6SSam Clegg   // section.
2066a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
207cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
208f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2096a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2106a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2116a31a0d6SSam Clegg       CustomSectionsRelocations;
212acd7d2b0SSam Clegg 
213c0d41195SSam Clegg   // Map from section to defining function symbol.
2146ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2156ccb59b3SSam Clegg 
2164c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2174c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2186c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2199f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2207c395943SSam Clegg   unsigned NumGlobalImports = 0;
221feac819eSAndy Wingo   unsigned NumTableImports = 0;
222da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2237e1c3345SChandler Carruth   uint32_t SectionCount = 0;
224d934cb88SDan Gohman 
2250ff28fa6SDerek Schuff   enum class DwoMode {
2260ff28fa6SDerek Schuff     AllSections,
2270ff28fa6SDerek Schuff     NonDwoOnly,
2280ff28fa6SDerek Schuff     DwoOnly,
2290ff28fa6SDerek Schuff   };
2300ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2310ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2320ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2330ff28fa6SDerek Schuff 
2340ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
23518eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
236da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
23718eafb6cSDan Gohman 
2382322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2392322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
240d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
241d934cb88SDan Gohman 
24218eafb6cSDan Gohman public:
2431301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2440ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2450ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2460ff28fa6SDerek Schuff 
2470ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2480ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2490ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2500ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
25118eafb6cSDan Gohman 
2520917c9e4SDan Gohman private:
253acd7d2b0SSam Clegg   void reset() override {
254acd7d2b0SSam Clegg     CodeRelocations.clear();
255acd7d2b0SSam Clegg     DataRelocations.clear();
256acd7d2b0SSam Clegg     TypeIndices.clear();
2576c899ba6SSam Clegg     WasmIndices.clear();
258492f7529SSam Clegg     GOTIndices.clear();
259f9edbe95SSam Clegg     TableIndices.clear();
2606c899ba6SSam Clegg     DataLocations.clear();
261cbda16ebSThomas Lively     CustomSections.clear();
262cbda16ebSThomas Lively     ProducersSection.reset();
263f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2646a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
265da419bdbSHeejin Ahn     SignatureIndices.clear();
266da419bdbSHeejin Ahn     Signatures.clear();
2676c899ba6SSam Clegg     DataSegments.clear();
2686ccb59b3SSam Clegg     SectionFunctions.clear();
2699f3fe42eSSam Clegg     NumFunctionImports = 0;
2707c395943SSam Clegg     NumGlobalImports = 0;
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);
314457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
315fef8de66SThomas Lively   void writeDataCountSection();
316e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
317457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
318e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
319da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3200a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
321388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3226f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
323f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32431a2c809SSam Clegg   void writeLinkingMetaDataSection(
32586b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
326ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
327ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
328cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
329cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3306a31a0d6SSam Clegg   void writeCustomRelocSections();
331acd7d2b0SSam Clegg 
3327ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3337ee758d6SSam Clegg                                const MCAsmLayout &Layout);
334acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3357ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
336acd7d2b0SSam Clegg 
337acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3385e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
339da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34038b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34138b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34218eafb6cSDan Gohman };
3439e15f359SSam Clegg 
34418eafb6cSDan Gohman } // end anonymous namespace
34518eafb6cSDan Gohman 
346d934cb88SDan Gohman // Write out a section header and a patchable section size field.
347d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3482322a937SSam Clegg                                     unsigned SectionId) {
349d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3500ff28fa6SDerek Schuff   W->OS << char(SectionId);
351d934cb88SDan Gohman 
3520ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
353d934cb88SDan Gohman 
354d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
355d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3560ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
357d934cb88SDan Gohman 
358d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3590ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3600ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3616f08c84aSSam Clegg   Section.Index = SectionCount++;
362d934cb88SDan Gohman }
3632322a937SSam Clegg 
3642322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3652322a937SSam Clegg                                           StringRef Name) {
366d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3672322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3686a31a0d6SSam Clegg 
3696a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3700ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3716a31a0d6SSam Clegg 
3722322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3732322a937SSam Clegg   writeString(Name);
3746a31a0d6SSam Clegg 
3756a31a0d6SSam Clegg   // The position where the custom section starts.
3760ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
377d934cb88SDan Gohman }
378d934cb88SDan Gohman 
379d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
380d934cb88SDan Gohman // section size field at the start of the section.
381d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3820ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
383c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
384c0affde8SSam Clegg   // Simply skip this patching in that case.
385c0affde8SSam Clegg   if (!Size)
386c0affde8SSam Clegg     return;
387c0affde8SSam Clegg 
388c0affde8SSam Clegg   Size -= Section.PayloadOffset;
389d934cb88SDan Gohman   if (uint32_t(Size) != Size)
390d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
391d934cb88SDan Gohman 
392d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
393d934cb88SDan Gohman 
394d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
395d934cb88SDan Gohman   // the section id byte.
3960ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
397f17b149dSPeter Collingbourne                        Section.SizeOffset);
398d934cb88SDan Gohman }
399d934cb88SDan Gohman 
40018eafb6cSDan Gohman // Emit the Wasm header.
40118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4020ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4030ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40418eafb6cSDan Gohman }
40518eafb6cSDan Gohman 
40618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
40718eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
408*7dc98adbSAndy Wingo   // As a stopgap measure until call_indirect instructions start explicitly
409*7dc98adbSAndy Wingo   // referencing the indirect function table via TABLE_NUMBER relocs, ensure
410*7dc98adbSAndy Wingo   // that the indirect function table import makes it to the output if anything
411*7dc98adbSAndy Wingo   // in the compilation unit has caused it to be present.
412*7dc98adbSAndy Wingo   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table"))
41396ef4f30SSam Clegg     Asm.registerSymbol(*Sym);
41496ef4f30SSam Clegg 
4156ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4166ccb59b3SSam Clegg   // in recordRelocation.
4176ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4186ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4196ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4206ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4216ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4226ccb59b3SSam Clegg       if (!Pair.second)
4236ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4247d1ff446SFangrui Song                            Sec.getName());
4256ccb59b3SSam Clegg     }
4266ccb59b3SSam Clegg   }
42718eafb6cSDan Gohman }
42818eafb6cSDan Gohman 
42918eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
43018eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
43118eafb6cSDan Gohman                                         const MCFragment *Fragment,
43218eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
433ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
434ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
435e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
436ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
437ecc5e808SSam Clegg 
438fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
439d934cb88SDan Gohman   uint64_t C = Target.getConstant();
440d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
441d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
442d934cb88SDan Gohman 
443d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
444ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
445ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
446ecc5e808SSam Clegg     // support either of those cases.
447ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
448d934cb88SDan Gohman     Ctx.reportError(
449d934cb88SDan Gohman         Fixup.getLoc(),
450d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
451ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
452d934cb88SDan Gohman     return;
453d934cb88SDan Gohman   }
454d934cb88SDan Gohman 
455d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
456d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
457ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
458d934cb88SDan Gohman 
4593ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4607d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4613ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4623ea1c62cSSam Clegg     return;
4633ea1c62cSSam Clegg   }
4643ea1c62cSSam Clegg 
465ecc5e808SSam Clegg   if (SymA->isVariable()) {
466d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4677ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4686ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4696ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
470d934cb88SDan Gohman   }
471d934cb88SDan Gohman 
472d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
473d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
474d934cb88SDan Gohman   // be negative and don't wrap.
475d934cb88SDan Gohman   FixedValue = 0;
476d934cb88SDan Gohman 
477a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4789d24fb7fSSam Clegg 
4794d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4804d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4814d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
482d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
48316f02431SWouter van Oortmerssen       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
484d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4854d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4864d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4874d57fbd0SSam Clegg                          "only supported in metadata sections");
4884d57fbd0SSam Clegg 
4894d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4904d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4915e5b2cb1SWouter van Oortmerssen     if (SecA.getKind().isText()) {
4925e5b2cb1SWouter van Oortmerssen       auto SecSymIt = SectionFunctions.find(&SecA);
4935e5b2cb1SWouter van Oortmerssen       if (SecSymIt == SectionFunctions.end())
4945e5b2cb1SWouter van Oortmerssen         report_fatal_error("section doesn\'t have defining symbol");
4955e5b2cb1SWouter van Oortmerssen       SectionSymbol = SecSymIt->second;
4965e5b2cb1SWouter van Oortmerssen     } else {
4974d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4985e5b2cb1SWouter van Oortmerssen     }
4994d57fbd0SSam Clegg     if (!SectionSymbol)
5004d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5014d57fbd0SSam Clegg 
5024d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5034d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5044d57fbd0SSam Clegg   }
5054d57fbd0SSam Clegg 
506feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
507feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
508feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
509feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
510feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
511feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
512feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
513feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
514*7dc98adbSAndy Wingo     if (Sym) {
515*7dc98adbSAndy Wingo       if (!Sym->isFunctionTable())
516feac819eSAndy Wingo         Ctx.reportError(
517feac819eSAndy Wingo             Fixup.getLoc(),
518feac819eSAndy Wingo             "symbol '__indirect_function_table' is not a function table");
519feac819eSAndy Wingo     } else {
520*7dc98adbSAndy Wingo       Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(TableName));
521*7dc98adbSAndy Wingo       Sym->setFunctionTable();
522*7dc98adbSAndy Wingo       // The default function table is synthesized by the linker.
523*7dc98adbSAndy Wingo       Sym->setUndefined();
524feac819eSAndy Wingo     }
525*7dc98adbSAndy Wingo     Sym->setUsedInReloc();
526*7dc98adbSAndy Wingo     Asm.registerSymbol(*Sym);
527861dbe1aSAndy Wingo   }
528feac819eSAndy Wingo 
529d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5304d57fbd0SSam Clegg   // against a named symbol.
531d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5324d57fbd0SSam Clegg     if (SymA->getName().empty())
5334d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5344d57fbd0SSam Clegg                          "supported by wasm");
5354d57fbd0SSam Clegg 
5364d57fbd0SSam Clegg     SymA->setUsedInReloc();
5374d57fbd0SSam Clegg   }
538ae03c1e7SSam Clegg 
539492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
540492f7529SSam Clegg     SymA->setUsedInGOT();
541492f7529SSam Clegg 
542d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
543d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
544d934cb88SDan Gohman 
5456a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
546d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5476a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
54812fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5496a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5506a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5516a31a0d6SSam Clegg   } else {
55212fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
553d934cb88SDan Gohman   }
5546a31a0d6SSam Clegg }
555d934cb88SDan Gohman 
556d934cb88SDan Gohman // Compute a value to write into the code at the location covered
55760ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
55860ec3034SSam Clegg // to make the object format more readable and more likely to be directly
55960ec3034SSam Clegg // useable.
5603b29376eSWouter van Oortmerssen uint64_t
5617ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5627ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
56348139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
56448139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
56548139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
566492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
567492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
568492f7529SSam Clegg   }
569492f7529SSam Clegg 
57060ec3034SSam Clegg   switch (RelEntry.Type) {
5712a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
572d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
573cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
574cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
575cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
576f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5777ee758d6SSam Clegg     const MCSymbolWasm *Base =
5787ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5797ee758d6SSam Clegg     assert(Base->isFunction());
58081443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5817ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
58281443ac1SSam Clegg     else
5837ee758d6SSam Clegg       return TableIndices[Base];
584f9edbe95SSam Clegg   }
585d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5866c899ba6SSam Clegg     // Provisional value is same as the index
58760ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
588d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
589d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
59048139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
591d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
59269e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
593da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
594492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5956c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
596d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
59716f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
598d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5996a31a0d6SSam Clegg     const auto &Section =
6006a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6016a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6026a31a0d6SSam Clegg   }
603d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6043b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6053b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6063b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6072a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6083b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6093b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
610a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
611a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
6129c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
613270ed1b3SSam Clegg     // For undefined symbols, use zero
61401a48535SSam Clegg     if (!RelEntry.Symbol->isDefined())
615270ed1b3SSam Clegg       return 0;
61601a48535SSam Clegg     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
61701a48535SSam Clegg     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
618d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
61901a48535SSam Clegg     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
62060ec3034SSam Clegg   }
62160ec3034SSam Clegg   default:
62260ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
62360ec3034SSam Clegg   }
624d934cb88SDan Gohman }
625d934cb88SDan Gohman 
626759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62763ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6287d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
629759631c7SSam Clegg 
63063ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63163ebb813SSam Clegg 
632759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
633759631c7SSam Clegg     if (Frag.hasInstructions())
634759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
635759631c7SSam Clegg 
636759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
637759631c7SSam Clegg       if (Align->getValueSize() != 1)
638759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
639759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
640759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
641f208f631SHeejin Ahn       uint64_t Size =
642f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
643f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
644759631c7SSam Clegg       DataBytes.resize(Size, Value);
645759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
646588fad4dSNirav Dave       int64_t NumValues;
647588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
648d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
649588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
650588fad4dSNirav Dave                        Fill->getValue());
65124faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
65224faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
6531d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
654759631c7SSam Clegg     } else {
655759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
656759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
6571d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
658759631c7SSam Clegg     }
659759631c7SSam Clegg   }
660759631c7SSam Clegg 
661d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
662759631c7SSam Clegg }
663759631c7SSam Clegg 
66460ec3034SSam Clegg uint32_t
66560ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
666d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
667b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
668b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
669b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
670acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
671acd7d2b0SSam Clegg   }
67260ec3034SSam Clegg 
67325d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
674acd7d2b0SSam Clegg }
675acd7d2b0SSam Clegg 
676d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
677d934cb88SDan Gohman // directly.
678acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6797ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6807ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6810ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
682d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
683d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
684d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
685d934cb88SDan Gohman                       RelEntry.Offset;
686d934cb88SDan Gohman 
687d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6887ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
68960ec3034SSam Clegg 
690acd7d2b0SSam Clegg     switch (RelEntry.Type) {
691d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
692d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
693d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
694d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
695d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
69669e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
6973b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6983b29376eSWouter van Oortmerssen       break;
6993b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7003b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
701d934cb88SDan Gohman       break;
702d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
703d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
704d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
705d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
70648139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
7070a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
708d934cb88SDan Gohman       break;
709cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7103b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
71116f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
7123b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7133b29376eSWouter van Oortmerssen       break;
714d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7152a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
716d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7172a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
718a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
7193b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7203b29376eSWouter van Oortmerssen       break;
721cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7223b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7233b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7243b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
72560ec3034SSam Clegg       break;
726d934cb88SDan Gohman     default:
7279d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
728d934cb88SDan Gohman     }
729d934cb88SDan Gohman   }
73018eafb6cSDan Gohman }
73118eafb6cSDan Gohman 
7324c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7334c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
734da419bdbSHeejin Ahn   if (Signatures.empty())
7359e15f359SSam Clegg     return;
7369e15f359SSam Clegg 
7379e15f359SSam Clegg   SectionBookkeeping Section;
7389e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7399e15f359SSam Clegg 
7400ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7419e15f359SSam Clegg 
7424c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7430ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7440ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
745da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7469e15f359SSam Clegg       writeValueType(Ty);
7470ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
748da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7499e15f359SSam Clegg       writeValueType(Ty);
7509e15f359SSam Clegg   }
7519e15f359SSam Clegg 
7529e15f359SSam Clegg   endSection(Section);
7539e15f359SSam Clegg }
7549e15f359SSam Clegg 
7558defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7564d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
757f950b24aSSam Clegg                                           uint32_t NumElements) {
7589e15f359SSam Clegg   if (Imports.empty())
7599e15f359SSam Clegg     return;
7609e15f359SSam Clegg 
7614d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
762f950b24aSSam Clegg 
7639e15f359SSam Clegg   SectionBookkeeping Section;
7649e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7659e15f359SSam Clegg 
7660ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7678defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7688defa952SSam Clegg     writeString(Import.Module);
7698defa952SSam Clegg     writeString(Import.Field);
7700ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7719e15f359SSam Clegg 
7729e15f359SSam Clegg     switch (Import.Kind) {
7739e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7740ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7759e15f359SSam Clegg       break;
7769e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7770ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7780ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7799e15f359SSam Clegg       break;
780f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7810ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7820ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
783f950b24aSSam Clegg       break;
784f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7850ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7860ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7870ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
788f950b24aSSam Clegg       break;
789da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7900ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7910ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
792da419bdbSHeejin Ahn       break;
7939e15f359SSam Clegg     default:
7949e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7959e15f359SSam Clegg     }
7969e15f359SSam Clegg   }
7979e15f359SSam Clegg 
7989e15f359SSam Clegg   endSection(Section);
7999e15f359SSam Clegg }
8009e15f359SSam Clegg 
801457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8029e15f359SSam Clegg   if (Functions.empty())
8039e15f359SSam Clegg     return;
8049e15f359SSam Clegg 
8059e15f359SSam Clegg   SectionBookkeeping Section;
8069e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8079e15f359SSam Clegg 
8080ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8099e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
8100ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8119e15f359SSam Clegg 
8129e15f359SSam Clegg   endSection(Section);
8139e15f359SSam Clegg }
8149e15f359SSam Clegg 
815da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
816da419bdbSHeejin Ahn   if (Events.empty())
817da419bdbSHeejin Ahn     return;
818da419bdbSHeejin Ahn 
819da419bdbSHeejin Ahn   SectionBookkeeping Section;
820da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
821da419bdbSHeejin Ahn 
8220ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
823da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
8240ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
8250ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
826da419bdbSHeejin Ahn   }
827da419bdbSHeejin Ahn 
828da419bdbSHeejin Ahn   endSection(Section);
829da419bdbSHeejin Ahn }
830da419bdbSHeejin Ahn 
8310a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8320a6c4d8dSSam Clegg   if (Globals.empty())
8330a6c4d8dSSam Clegg     return;
8340a6c4d8dSSam Clegg 
8350a6c4d8dSSam Clegg   SectionBookkeeping Section;
8360a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8370a6c4d8dSSam Clegg 
8380ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8390a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8400ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8410ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8420ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8430a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8440a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8450ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8460a6c4d8dSSam Clegg       break;
8470a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8480ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8490a6c4d8dSSam Clegg       break;
8500a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8510a6c4d8dSSam Clegg       writeI32(0);
8520a6c4d8dSSam Clegg       break;
8530a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8540a6c4d8dSSam Clegg       writeI64(0);
8550a6c4d8dSSam Clegg       break;
85679aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
85779aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
85879aad89dSSam Clegg       break;
8590a6c4d8dSSam Clegg     default:
8600a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8610a6c4d8dSSam Clegg     }
8620ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8630a6c4d8dSSam Clegg   }
8640a6c4d8dSSam Clegg 
8650a6c4d8dSSam Clegg   endSection(Section);
8660a6c4d8dSSam Clegg }
8670a6c4d8dSSam Clegg 
868388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
869388fb67bSPaulo Matos   if (Tables.empty())
870388fb67bSPaulo Matos     return;
871388fb67bSPaulo Matos 
872388fb67bSPaulo Matos   SectionBookkeeping Section;
873388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
874388fb67bSPaulo Matos 
875388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
876388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
8771933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
8781933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
8791933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Initial, W->OS);
8801933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
8811933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
882388fb67bSPaulo Matos   }
883388fb67bSPaulo Matos   endSection(Section);
884388fb67bSPaulo Matos }
885388fb67bSPaulo Matos 
8868defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8879e15f359SSam Clegg   if (Exports.empty())
8889e15f359SSam Clegg     return;
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   SectionBookkeeping Section;
8919e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8929e15f359SSam Clegg 
8930ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8948defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8958defa952SSam Clegg     writeString(Export.Name);
8960ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8970ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8989e15f359SSam Clegg   }
8999e15f359SSam Clegg 
9009e15f359SSam Clegg   endSection(Section);
9019e15f359SSam Clegg }
9029e15f359SSam Clegg 
903457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
9049e15f359SSam Clegg   if (TableElems.empty())
9059e15f359SSam Clegg     return;
9069e15f359SSam Clegg 
9079e15f359SSam Clegg   SectionBookkeeping Section;
9089e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
9099e15f359SSam Clegg 
9100ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
9110ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
9129e15f359SSam Clegg 
9139e15f359SSam Clegg   // init expr for starting offset
9140ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
9150ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
9160ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9179e15f359SSam Clegg 
9180ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9199e15f359SSam Clegg   for (uint32_t Elem : TableElems)
9200ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9219e15f359SSam Clegg 
9229e15f359SSam Clegg   endSection(Section);
9239e15f359SSam Clegg }
9249e15f359SSam Clegg 
925fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
926fef8de66SThomas Lively   if (DataSegments.empty())
927fef8de66SThomas Lively     return;
928fef8de66SThomas Lively 
929fef8de66SThomas Lively   SectionBookkeeping Section;
930fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9310ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
932fef8de66SThomas Lively   endSection(Section);
933fef8de66SThomas Lively }
934fef8de66SThomas Lively 
935e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
936457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
937457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9389e15f359SSam Clegg   if (Functions.empty())
939e49584a3SSam Clegg     return 0;
9409e15f359SSam Clegg 
9419e15f359SSam Clegg   SectionBookkeeping Section;
9429e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9439e15f359SSam Clegg 
9440ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9459e15f359SSam Clegg 
9469e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
947fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9489e15f359SSam Clegg 
9499e15f359SSam Clegg     int64_t Size = 0;
9509e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9519e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9529e15f359SSam Clegg 
9530ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9540ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9550ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9569e15f359SSam Clegg   }
9579e15f359SSam Clegg 
9589e15f359SSam Clegg   // Apply fixups.
9597ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9609e15f359SSam Clegg 
9619e15f359SSam Clegg   endSection(Section);
962e49584a3SSam Clegg   return Section.Index;
9639e15f359SSam Clegg }
9649e15f359SSam Clegg 
965e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9666c899ba6SSam Clegg   if (DataSegments.empty())
967e49584a3SSam Clegg     return 0;
9689e15f359SSam Clegg 
9699e15f359SSam Clegg   SectionBookkeeping Section;
9709e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9719e15f359SSam Clegg 
9720ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9737c395943SSam Clegg 
9746c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9750ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
976831a143eSAndy Wingo     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
9770ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
978831a143eSAndy Wingo     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
9790d9b17d0SWouter van Oortmerssen       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
9804d135b04SWouter van Oortmerssen                               : wasm::WASM_OPCODE_I32_CONST);
9810ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9820ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9832e150409SThomas Lively     }
9840ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9850ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9860ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9877c395943SSam Clegg   }
9889e15f359SSam Clegg 
9899e15f359SSam Clegg   // Apply fixups.
9907ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9919e15f359SSam Clegg 
9929e15f359SSam Clegg   endSection(Section);
993e49584a3SSam Clegg   return Section.Index;
9949e15f359SSam Clegg }
9959e15f359SSam Clegg 
9966f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9976f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
998f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9999e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
10009e15f359SSam Clegg   // for descriptions of the reloc sections.
10019e15f359SSam Clegg 
1002f77dc2a8SSam Clegg   if (Relocs.empty())
10039e15f359SSam Clegg     return;
10049e15f359SSam Clegg 
1005f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1006f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1007f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1008f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1009f77dc2a8SSam Clegg   // not the sections order.
1010efd94c56SFangrui Song   llvm::stable_sort(
1011efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1012f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1013f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1014f77dc2a8SSam Clegg       });
1015f77dc2a8SSam Clegg 
10169e15f359SSam Clegg   SectionBookkeeping Section;
10176f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10189e15f359SSam Clegg 
10190ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
10200ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1021f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1022f208f631SHeejin Ahn     uint64_t Offset =
1023f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10246f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10259e15f359SSam Clegg 
10260ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10270ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10280ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10296f08c84aSSam Clegg     if (RelEntry.hasAddend())
10300ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10319e15f359SSam Clegg   }
10329e15f359SSam Clegg 
10339e15f359SSam Clegg   endSection(Section);
10349e15f359SSam Clegg }
10359e15f359SSam Clegg 
10366a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10376a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10386a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10396a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10406a31a0d6SSam Clegg   }
10416a31a0d6SSam Clegg }
10426a31a0d6SSam Clegg 
10439e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
104486b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1045ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1046ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10479e15f359SSam Clegg   SectionBookkeeping Section;
10482322a937SSam Clegg   startCustomSection(Section, "linking");
10490ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10509e15f359SSam Clegg 
10516bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10526c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10536c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10540ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10556c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10560ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10570ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10586c899ba6SSam Clegg       switch (Sym.Kind) {
10596c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10606c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1061da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1062388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10630ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
106429874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
106529874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10666c899ba6SSam Clegg           writeString(Sym.Name);
10676c899ba6SSam Clegg         break;
10686c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10696c899ba6SSam Clegg         writeString(Sym.Name);
10706c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10710ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10720ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10730ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10746c899ba6SSam Clegg         }
10756c899ba6SSam Clegg         break;
10766a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10776a31a0d6SSam Clegg         const uint32_t SectionIndex =
10786a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10790ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10806a31a0d6SSam Clegg         break;
10816a31a0d6SSam Clegg       }
10826c899ba6SSam Clegg       default:
10836c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10846c899ba6SSam Clegg       }
1085b7787fd0SSam Clegg     }
1086b7787fd0SSam Clegg     endSection(SubSection);
1087b7787fd0SSam Clegg   }
10889e15f359SSam Clegg 
10896c899ba6SSam Clegg   if (DataSegments.size()) {
109063ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10910ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10926c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1093d95ed959SSam Clegg       writeString(Segment.Name);
10940ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10950ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
109663ebb813SSam Clegg     }
1097d95ed959SSam Clegg     endSection(SubSection);
1098d95ed959SSam Clegg   }
1099d95ed959SSam Clegg 
1100bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1101bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
11020ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1103bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
11040ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
11050ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1106bafe6902SSam Clegg     }
1107bafe6902SSam Clegg     endSection(SubSection);
1108bafe6902SSam Clegg   }
1109bafe6902SSam Clegg 
1110ea7caceeSSam Clegg   if (Comdats.size()) {
1111ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
11120ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1113ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1114ea7caceeSSam Clegg       writeString(C.first);
11150ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
11160ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1117ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
11180ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
11190ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1120ea7caceeSSam Clegg       }
1121ea7caceeSSam Clegg     }
1122ea7caceeSSam Clegg     endSection(SubSection);
1123ea7caceeSSam Clegg   }
1124ea7caceeSSam Clegg 
11259e15f359SSam Clegg   endSection(Section);
11269e15f359SSam Clegg }
11279e15f359SSam Clegg 
1128cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1129cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11306a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1131cfd44a2eSSam Clegg   SectionBookkeeping Section;
11326a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11332322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11346a31a0d6SSam Clegg 
11350ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11360ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11376a31a0d6SSam Clegg 
11386a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11396a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11406a31a0d6SSam Clegg 
1141cfd44a2eSSam Clegg   endSection(Section);
11426a31a0d6SSam Clegg 
11436a31a0d6SSam Clegg   // Apply fixups.
11444d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11457ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11466a31a0d6SSam Clegg }
11476a31a0d6SSam Clegg 
11485e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11495e3d33a7SSam Clegg   assert(Symbol.isFunction());
11505e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11515e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11525e3d33a7SSam Clegg }
11535e3d33a7SSam Clegg 
1154da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1155da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1156da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1157da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1158da419bdbSHeejin Ahn }
1159da419bdbSHeejin Ahn 
116038b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11615e3d33a7SSam Clegg   assert(Symbol.isFunction());
11625e3d33a7SSam Clegg 
11634c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11647ee758d6SSam Clegg 
11657ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1166da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1167da419bdbSHeejin Ahn     S.Params = Sig->Params;
116877a7a380SDerek Schuff   }
11695e3d33a7SSam Clegg 
1170da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11715e3d33a7SSam Clegg   if (Pair.second)
1172da419bdbSHeejin Ahn     Signatures.push_back(S);
11735e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11745e3d33a7SSam Clegg 
1175d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1176d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1177d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11785e3d33a7SSam Clegg }
11795e3d33a7SSam Clegg 
118038b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1181da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1182da419bdbSHeejin Ahn 
1183da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1184da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11854c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1186da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1187da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1188da419bdbSHeejin Ahn     S.Params = Sig->Params;
1189da419bdbSHeejin Ahn   }
1190da419bdbSHeejin Ahn 
1191da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1192da419bdbSHeejin Ahn   if (Pair.second)
1193da419bdbSHeejin Ahn     Signatures.push_back(S);
1194da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1195da419bdbSHeejin Ahn 
1196da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1197da419bdbSHeejin Ahn                     << "\n");
1198da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1199da419bdbSHeejin Ahn }
1200da419bdbSHeejin Ahn 
12014d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
12023ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
12034d57fbd0SSam Clegg     return true;
12044d57fbd0SSam Clegg 
12054d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
12064d57fbd0SSam Clegg     return false;
12074d57fbd0SSam Clegg 
12083ea1c62cSSam Clegg   if (Sym.isTemporary())
12094d57fbd0SSam Clegg     return false;
12104d57fbd0SSam Clegg 
12114d57fbd0SSam Clegg   if (Sym.isSection())
12124d57fbd0SSam Clegg     return false;
12134d57fbd0SSam Clegg 
12144d57fbd0SSam Clegg   return true;
12154d57fbd0SSam Clegg }
121630d314aaSSam Clegg 
12170ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
12180ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
121918eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1220f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1221f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1222f950b24aSSam Clegg   // it if there are no loads or stores.
12238defa952SSam Clegg   wasm::WasmImport MemImport;
12241ed3a046SSam Clegg   MemImport.Module = "env";
12251ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1226f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1227fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1228fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1229f950b24aSSam Clegg   Imports.push_back(MemImport);
1230f950b24aSSam Clegg 
1231da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1232586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1233586320c0SNicholas Wilson   // symbols.
123432ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
123532ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
123632ce5ca0SDan Gohman 
123732ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12389f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12397ee758d6SSam Clegg     if (WS.isFunction()) {
12409c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12419c7b5808SDominic Chen       if (!BS)
12429c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12439c7b5808SDominic Chen                            ": absolute addressing not supported!");
12449c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12457ee758d6SSam Clegg     }
124632ce5ca0SDan Gohman 
1247da419bdbSHeejin Ahn     if (WS.isEvent())
1248da419bdbSHeejin Ahn       registerEventType(WS);
1249da419bdbSHeejin Ahn 
125032ce5ca0SDan Gohman     if (WS.isTemporary())
125132ce5ca0SDan Gohman       continue;
125232ce5ca0SDan Gohman 
125332ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12546c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12556c899ba6SSam Clegg       if (WS.isFunction()) {
12568defa952SSam Clegg         wasm::WasmImport Import;
1257f726e445SDan Gohman         Import.Module = WS.getImportModule();
1258f726e445SDan Gohman         Import.Field = WS.getImportName();
125932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12608defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12616c899ba6SSam Clegg         Imports.push_back(Import);
1262492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12636c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12646c899ba6SSam Clegg       } else if (WS.isGlobal()) {
126515f349f7SNicholas Wilson         if (WS.isWeak())
126615f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
126715f349f7SNicholas Wilson 
12686c899ba6SSam Clegg         wasm::WasmImport Import;
1269f726e445SDan Gohman         Import.Field = WS.getImportName();
127032ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1271492f7529SSam Clegg         Import.Module = WS.getImportModule();
12726c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12736c899ba6SSam Clegg         Imports.push_back(Import);
1274492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12756c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1276da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1277da419bdbSHeejin Ahn         if (WS.isWeak())
1278da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1279da419bdbSHeejin Ahn 
1280da419bdbSHeejin Ahn         wasm::WasmImport Import;
1281f726e445SDan Gohman         Import.Module = WS.getImportModule();
1282f726e445SDan Gohman         Import.Field = WS.getImportName();
1283da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1284da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1285da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1286da419bdbSHeejin Ahn         Imports.push_back(Import);
1287492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1288da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
1289feac819eSAndy Wingo       } else if (WS.isTable()) {
1290feac819eSAndy Wingo         if (WS.isWeak())
1291feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1292feac819eSAndy Wingo 
1293feac819eSAndy Wingo         wasm::WasmImport Import;
1294feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1295feac819eSAndy Wingo         Import.Field = WS.getImportName();
1296feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1297feac819eSAndy Wingo         wasm::ValType ElemType = WS.getTableType();
1298feac819eSAndy Wingo         Import.Table.ElemType = uint8_t(ElemType);
1299feac819eSAndy Wingo         // FIXME: Extend table type to include limits? For now we don't specify
1300feac819eSAndy Wingo         // a min or max which does not place any restrictions on the size of the
1301feac819eSAndy Wingo         // imported table.
1302feac819eSAndy Wingo         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1303feac819eSAndy Wingo         Imports.push_back(Import);
1304feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1305feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
130632ce5ca0SDan Gohman       }
130732ce5ca0SDan Gohman     }
130832ce5ca0SDan Gohman   }
130932ce5ca0SDan Gohman 
1310492f7529SSam Clegg   // Add imports for GOT globals
1311492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1312492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1313492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1314492f7529SSam Clegg       wasm::WasmImport Import;
1315492f7529SSam Clegg       if (WS.isFunction())
1316492f7529SSam Clegg         Import.Module = "GOT.func";
1317492f7529SSam Clegg       else
1318492f7529SSam Clegg         Import.Module = "GOT.mem";
1319492f7529SSam Clegg       Import.Field = WS.getName();
1320492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1321492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1322492f7529SSam Clegg       Imports.push_back(Import);
1323492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1324492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1325492f7529SSam Clegg     }
1326492f7529SSam Clegg   }
13270ff28fa6SDerek Schuff }
1328492f7529SSam Clegg 
13290ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
13300ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
13310ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
13320ff28fa6SDerek Schuff   W = &MainWriter;
13330ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13340ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13350ff28fa6SDerek Schuff     assert(DwoOS);
13360ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13370ff28fa6SDerek Schuff     W = &DwoWriter;
13380ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13390ff28fa6SDerek Schuff   } else {
13400ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13410ff28fa6SDerek Schuff   }
13420ff28fa6SDerek Schuff }
13430ff28fa6SDerek Schuff 
13440ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13450ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13460ff28fa6SDerek Schuff                                           DwoMode Mode) {
13470ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13480ff28fa6SDerek Schuff   SectionCount = 0;
13490ff28fa6SDerek Schuff   CustomSections.clear();
13500ff28fa6SDerek Schuff 
13510ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13520ff28fa6SDerek Schuff 
13530ff28fa6SDerek Schuff   // Collect information from the available symbols.
13540ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13550ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13560ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13570ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13580ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13590ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1360388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13610ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13620ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13630ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13640ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13650ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13660ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13670ff28fa6SDerek Schuff   }
136830d314aaSSam Clegg 
13694d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13704d57fbd0SSam Clegg   // populating DataLocations.
1371759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1372759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13737d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1374759631c7SSam Clegg 
13750ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13760ff28fa6SDerek Schuff       continue;
13770ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13780ff28fa6SDerek Schuff       continue;
13790ff28fa6SDerek Schuff 
13808d396acaSDerek Schuff     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
13818d396acaSDerek Schuff                       << Section.getGroup() << "\n";);
13828d396acaSDerek Schuff 
1383bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13844d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1385bafe6902SSam Clegg       continue;
1386bafe6902SSam Clegg 
13874d57fbd0SSam Clegg     // Code is handled separately
13884d57fbd0SSam Clegg     if (Section.getKind().isText())
13894d57fbd0SSam Clegg       continue;
13904d57fbd0SSam Clegg 
13914d57fbd0SSam Clegg     if (Section.isWasmData()) {
1392329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1393759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1394759631c7SSam Clegg       DataSegments.emplace_back();
1395759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13964d57fbd0SSam Clegg       Segment.Name = SectionName;
1397831a143eSAndy Wingo       Segment.InitFlags = Section.getPassive()
1398831a143eSAndy Wingo                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1399831a143eSAndy Wingo                               : 0;
1400759631c7SSam Clegg       Segment.Offset = DataSize;
1401759631c7SSam Clegg       Segment.Section = &Section;
140263ebb813SSam Clegg       addData(Segment.Data, Section);
140356c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
14042e150409SThomas Lively       Segment.LinkerFlags = 0;
1405759631c7SSam Clegg       DataSize += Segment.Data.size();
14066c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1407ea7caceeSSam Clegg 
1408ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1409ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1410329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1411ea7caceeSSam Clegg       }
14124d57fbd0SSam Clegg     } else {
14134d57fbd0SSam Clegg       // Create custom sections
14144d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
14154d57fbd0SSam Clegg 
14164d57fbd0SSam Clegg       StringRef Name = SectionName;
14174d57fbd0SSam Clegg 
14184d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
14194d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
14204d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
14214d57fbd0SSam Clegg 
14224d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1423fb807d4dSSam Clegg       if (Begin) {
142430d314aaSSam Clegg         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
14254d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1426fb807d4dSSam Clegg       }
1427cbda16ebSThomas Lively 
1428f6f4f843SThomas Lively       // Separate out the producers and target features sections
1429cbda16ebSThomas Lively       if (Name == "producers") {
14300eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1431cbda16ebSThomas Lively         continue;
1432cbda16ebSThomas Lively       }
1433f6f4f843SThomas Lively       if (Name == "target_features") {
1434f6f4f843SThomas Lively         TargetFeaturesSection =
14350eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1436f6f4f843SThomas Lively         continue;
1437f6f4f843SThomas Lively       }
1438cbda16ebSThomas Lively 
14390a391060SDerek Schuff       // Custom sections can also belong to COMDAT groups. In this case the
14400a391060SDerek Schuff       // decriptor's "index" field is the section index (in the final object
14410a391060SDerek Schuff       // file), but that is not known until after layout, so it must be fixed up
14420a391060SDerek Schuff       // later
14430a391060SDerek Schuff       if (const MCSymbolWasm *C = Section.getGroup()) {
14440a391060SDerek Schuff         Comdats[C->getName()].emplace_back(
14450a391060SDerek Schuff             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
14460a391060SDerek Schuff                             static_cast<uint32_t>(CustomSections.size())});
14470a391060SDerek Schuff       }
14480a391060SDerek Schuff 
14494d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1450759631c7SSam Clegg     }
14516a31a0d6SSam Clegg   }
14526a31a0d6SSam Clegg 
145330d314aaSSam Clegg   if (Mode != DwoMode::DwoOnly) {
1454586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for defined symbols.
1455d934cb88SDan Gohman     for (const MCSymbol &S : Asm.symbols()) {
1456d934cb88SDan Gohman       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1457d934cb88SDan Gohman       // or used in relocations.
1458d934cb88SDan Gohman       if (S.isTemporary() && S.getName().empty())
1459d934cb88SDan Gohman         continue;
1460b7787fd0SSam Clegg 
1461d934cb88SDan Gohman       const auto &WS = static_cast<const MCSymbolWasm &>(S);
14625e5b2cb1SWouter van Oortmerssen       LLVM_DEBUG(dbgs()
14635e5b2cb1SWouter van Oortmerssen                  << "MCSymbol: "
14645e5b2cb1SWouter van Oortmerssen                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
14655e5b2cb1SWouter van Oortmerssen                  << " '" << S << "'"
1466d34e60caSNicola Zaghen                  << " isDefined=" << S.isDefined() << " isExternal="
1467d34e60caSNicola Zaghen                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1468d34e60caSNicola Zaghen                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1469b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1470b7787fd0SSam Clegg 
14715e3d33a7SSam Clegg       if (WS.isVariable())
14725e3d33a7SSam Clegg         continue;
14736c899ba6SSam Clegg       if (WS.isComdat() && !WS.isDefined())
14746c899ba6SSam Clegg         continue;
1475b7787fd0SSam Clegg 
1476d934cb88SDan Gohman       if (WS.isFunction()) {
14776c899ba6SSam Clegg         unsigned Index;
1478cd65f698SSam Clegg         if (WS.isDefined()) {
1479b7787fd0SSam Clegg           if (WS.getOffset() != 0)
1480b7787fd0SSam Clegg             report_fatal_error(
1481b7787fd0SSam Clegg                 "function sections must contain one function each");
1482b7787fd0SSam Clegg 
148318c56a07SHeejin Ahn           if (WS.getSize() == nullptr)
1484b7787fd0SSam Clegg             report_fatal_error(
1485b7787fd0SSam Clegg                 "function symbols must have a size set with .size");
1486b7787fd0SSam Clegg 
14876c899ba6SSam Clegg           // A definition. Write out the function body.
14889f3fe42eSSam Clegg           Index = NumFunctionImports + Functions.size();
1489d934cb88SDan Gohman           WasmFunction Func;
1490da419bdbSHeejin Ahn           Func.SigIndex = getFunctionType(WS);
1491d934cb88SDan Gohman           Func.Sym = &WS;
149230d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
14936c899ba6SSam Clegg           WasmIndices[&WS] = Index;
1494d934cb88SDan Gohman           Functions.push_back(Func);
14956c899ba6SSam Clegg 
14966c899ba6SSam Clegg           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14976c899ba6SSam Clegg           if (const MCSymbolWasm *C = Section.getGroup()) {
14986c899ba6SSam Clegg             Comdats[C->getName()].emplace_back(
14996c899ba6SSam Clegg                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
15006c899ba6SSam Clegg           }
1501881d8778SSam Clegg 
1502881d8778SSam Clegg           if (WS.hasExportName()) {
1503881d8778SSam Clegg             wasm::WasmExport Export;
1504881d8778SSam Clegg             Export.Name = WS.getExportName();
1505881d8778SSam Clegg             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1506881d8778SSam Clegg             Export.Index = Index;
1507881d8778SSam Clegg             Exports.push_back(Export);
1508881d8778SSam Clegg           }
1509d934cb88SDan Gohman         } else {
1510d934cb88SDan Gohman           // An import; the index was assigned above.
15116c899ba6SSam Clegg           Index = WasmIndices.find(&WS)->second;
1512d934cb88SDan Gohman         }
1513d934cb88SDan Gohman 
1514d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1515da419bdbSHeejin Ahn 
15166c899ba6SSam Clegg       } else if (WS.isData()) {
1517f3feb6adSWouter van Oortmerssen         if (!isInSymtab(WS))
1518c38e947eSSam Clegg           continue;
1519c38e947eSSam Clegg 
15206c899ba6SSam Clegg         if (!WS.isDefined()) {
1521d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1522d34e60caSNicola Zaghen                             << "\n");
1523fe6414b0SSam Clegg           continue;
15246c899ba6SSam Clegg         }
1525fe6414b0SSam Clegg 
1526d934cb88SDan Gohman         if (!WS.getSize())
1527c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1528c38e947eSSam Clegg                              WS.getName());
1529d934cb88SDan Gohman 
1530d934cb88SDan Gohman         int64_t Size = 0;
1531d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1532d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1533d934cb88SDan Gohman 
1534759631c7SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1535079cba04SSam Clegg         if (!DataSection.isWasmData())
1536079cba04SSam Clegg           report_fatal_error("data symbols must live in a data section: " +
1537079cba04SSam Clegg                              WS.getName());
15387c395943SSam Clegg 
15396c899ba6SSam Clegg         // For each data symbol, export it in the symtab as a reference to the
15406c899ba6SSam Clegg         // corresponding Wasm data segment.
15416c899ba6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
15423b29376eSWouter van Oortmerssen             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
15433b29376eSWouter van Oortmerssen             static_cast<uint64_t>(Size)};
154430d314aaSSam Clegg         assert(DataLocations.count(&WS) == 0);
15456c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1546d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1547da419bdbSHeejin Ahn 
1548a165f2d6SSam Clegg       } else if (WS.isGlobal()) {
15496c899ba6SSam Clegg         // A "true" Wasm global (currently just __stack_pointer)
15500a6c4d8dSSam Clegg         if (WS.isDefined()) {
15510a6c4d8dSSam Clegg           wasm::WasmGlobal Global;
15520a6c4d8dSSam Clegg           Global.Type = WS.getGlobalType();
15530a6c4d8dSSam Clegg           Global.Index = NumGlobalImports + Globals.size();
15540a6c4d8dSSam Clegg           switch (Global.Type.Type) {
15550a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I32:
15560a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15570a6c4d8dSSam Clegg             break;
15580a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I64:
15590a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15600a6c4d8dSSam Clegg             break;
15610a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F32:
15620a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15630a6c4d8dSSam Clegg             break;
15640a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F64:
15650a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15660a6c4d8dSSam Clegg             break;
156779aad89dSSam Clegg           case wasm::WASM_TYPE_EXTERNREF:
156879aad89dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
156979aad89dSSam Clegg             break;
15700a6c4d8dSSam Clegg           default:
15710a6c4d8dSSam Clegg             llvm_unreachable("unexpected type");
15720a6c4d8dSSam Clegg           }
157330d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
15740a6c4d8dSSam Clegg           WasmIndices[&WS] = Global.Index;
15750a6c4d8dSSam Clegg           Globals.push_back(Global);
15760a6c4d8dSSam Clegg         } else {
1577545932beSEric Christopher           // An import; the index was assigned above
1578d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> global index: "
1579d34e60caSNicola Zaghen                             << WasmIndices.find(&WS)->second << "\n");
15800a6c4d8dSSam Clegg         }
1581388fb67bSPaulo Matos       } else if (WS.isTable()) {
1582388fb67bSPaulo Matos         if (WS.isDefined()) {
1583388fb67bSPaulo Matos           wasm::WasmTable Table;
1584388fb67bSPaulo Matos           Table.Index = NumTableImports + Tables.size();
15851933c9d4SAndy Wingo           Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1586388fb67bSPaulo Matos           // FIXME: Work on custom limits is ongoing
15871933c9d4SAndy Wingo           Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
158830d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1589388fb67bSPaulo Matos           WasmIndices[&WS] = Table.Index;
1590388fb67bSPaulo Matos           Tables.push_back(Table);
1591388fb67bSPaulo Matos         }
159230d314aaSSam Clegg         LLVM_DEBUG(dbgs() << " -> table index: "
159330d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
1594da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1595da419bdbSHeejin Ahn         // C++ exception symbol (__cpp_exception)
1596da419bdbSHeejin Ahn         unsigned Index;
1597da419bdbSHeejin Ahn         if (WS.isDefined()) {
1598da419bdbSHeejin Ahn           Index = NumEventImports + Events.size();
1599da419bdbSHeejin Ahn           wasm::WasmEventType Event;
1600da419bdbSHeejin Ahn           Event.SigIndex = getEventType(WS);
1601da419bdbSHeejin Ahn           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
160230d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1603da419bdbSHeejin Ahn           WasmIndices[&WS] = Index;
1604da419bdbSHeejin Ahn           Events.push_back(Event);
1605da419bdbSHeejin Ahn         } else {
1606da419bdbSHeejin Ahn           // An import; the index was assigned above.
1607492f7529SSam Clegg           assert(WasmIndices.count(&WS) > 0);
1608da419bdbSHeejin Ahn         }
160930d314aaSSam Clegg         LLVM_DEBUG(dbgs() << "  -> event index: "
161030d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
1611da419bdbSHeejin Ahn 
1612a165f2d6SSam Clegg       } else {
1613a165f2d6SSam Clegg         assert(WS.isSection());
1614d934cb88SDan Gohman       }
1615d934cb88SDan Gohman     }
1616d934cb88SDan Gohman 
1617586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1618586320c0SNicholas Wilson     // process these in a separate pass because we need to have processed the
1619586320c0SNicholas Wilson     // target of the alias before the alias itself and the symbols are not
1620586320c0SNicholas Wilson     // necessarily ordered in this way.
1621b7787fd0SSam Clegg     for (const MCSymbol &S : Asm.symbols()) {
1622b7787fd0SSam Clegg       if (!S.isVariable())
1623b7787fd0SSam Clegg         continue;
162431a2c809SSam Clegg 
1625cd65f698SSam Clegg       assert(S.isDefined());
1626b7787fd0SSam Clegg 
16279c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
16289c7b5808SDominic Chen       if (!BS)
16299c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
16309c7b5808SDominic Chen                            ": absolute addressing not supported!");
16319c7b5808SDominic Chen       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
16327ee758d6SSam Clegg 
16335e3d33a7SSam Clegg       // Find the target symbol of this weak alias and export that index
1634aff1c4dfSSam Clegg       const auto &WS = static_cast<const MCSymbolWasm &>(S);
163530d314aaSSam Clegg       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
163630d314aaSSam Clegg                         << "'\n");
1637b7787fd0SSam Clegg 
16387ee758d6SSam Clegg       if (Base->isFunction()) {
16397ee758d6SSam Clegg         assert(WasmIndices.count(Base) > 0);
16407ee758d6SSam Clegg         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1641492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
16426c899ba6SSam Clegg         WasmIndices[&WS] = WasmIndex;
1643d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
16447ee758d6SSam Clegg       } else if (Base->isData()) {
16457ee758d6SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
16467ee758d6SSam Clegg         uint64_t Offset = Layout.getSymbolOffset(S);
16477ee758d6SSam Clegg         int64_t Size = 0;
16487ee758d6SSam Clegg         // For data symbol alias we use the size of the base symbol as the
16497ee758d6SSam Clegg         // size of the alias.  When an offset from the base is involved this
16507ee758d6SSam Clegg         // can result in a offset + size goes past the end of the data section
16517ee758d6SSam Clegg         // which out object format doesn't support.  So we must clamp it.
16527ee758d6SSam Clegg         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
16537ee758d6SSam Clegg           report_fatal_error(".size expression must be evaluatable");
16547ee758d6SSam Clegg         const WasmDataSegment &Segment =
16557ee758d6SSam Clegg             DataSegments[DataSection.getSegmentIndex()];
16567ee758d6SSam Clegg         Size =
16577ee758d6SSam Clegg             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16587ee758d6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16597ee758d6SSam Clegg             DataSection.getSegmentIndex(),
16607ee758d6SSam Clegg             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16617ee758d6SSam Clegg             static_cast<uint32_t>(Size)};
16626c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1663d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16646c899ba6SSam Clegg       } else {
1665da419bdbSHeejin Ahn         report_fatal_error("don't yet support global/event aliases");
16666c899ba6SSam Clegg       }
1667586320c0SNicholas Wilson     }
166830d314aaSSam Clegg   }
166931a2c809SSam Clegg 
1670586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1671586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1672586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
167325d8e68bSSam Clegg     if (!isInSymtab(WS)) {
167418c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1675586320c0SNicholas Wilson       continue;
167625d8e68bSSam Clegg     }
1677*7dc98adbSAndy Wingo     if (WS.isTable() && WS.getName() == "__indirect_function_table") {
1678*7dc98adbSAndy Wingo       // For the moment, don't emit table symbols -- wasm-ld can't handle them.
1679*7dc98adbSAndy Wingo       continue;
1680*7dc98adbSAndy Wingo     }
1681d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1682586320c0SNicholas Wilson 
1683586320c0SNicholas Wilson     uint32_t Flags = 0;
1684586320c0SNicholas Wilson     if (WS.isWeak())
1685586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1686586320c0SNicholas Wilson     if (WS.isHidden())
1687586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1688586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1689586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1690586320c0SNicholas Wilson     if (WS.isUndefined())
1691586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1692da84b688SDan Gohman     if (WS.isNoStrip()) {
1693da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1694da84b688SDan Gohman       if (isEmscripten()) {
1695d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1696da84b688SDan Gohman       }
1697da84b688SDan Gohman     }
1698b4f4e370SSam Clegg     if (WS.hasImportName())
169929874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1700881d8778SSam Clegg     if (WS.hasExportName())
1701881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1702586320c0SNicholas Wilson 
1703586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1704586320c0SNicholas Wilson     Info.Name = WS.getName();
17055e5b2cb1SWouter van Oortmerssen     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1706586320c0SNicholas Wilson     Info.Flags = Flags;
17074d57fbd0SSam Clegg     if (!WS.isData()) {
17084d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1709586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
17104d57fbd0SSam Clegg     } else if (WS.isDefined()) {
17114d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1712586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
17134d57fbd0SSam Clegg     }
171425d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1715586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1716b7787fd0SSam Clegg   }
1717b7787fd0SSam Clegg 
17186006e091SSam Clegg   {
17196006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1720f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1721f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1722f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1723d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1724cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
172581443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1726cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
172781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1728f9edbe95SSam Clegg         return;
1729f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
17307ee758d6SSam Clegg       const MCSymbolWasm *Base =
17317ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
17327ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
173318c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
17347ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
17357ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1736f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
17376c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
17387ee758d6SSam Clegg         registerFunctionType(*Base);
17396006e091SSam Clegg       }
17406006e091SSam Clegg     };
1741970d02c4SDan Gohman 
17426006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
17436006e091SSam Clegg       HandleReloc(RelEntry);
17446006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
17456006e091SSam Clegg       HandleReloc(RelEntry);
1746d934cb88SDan Gohman   }
1747d934cb88SDan Gohman 
1748bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1749bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1750bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
17517d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1752bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
17537d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1754bafe6902SSam Clegg       continue;
1755bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1756bafe6902SSam Clegg       continue;
1757b210c64bSSam Clegg 
1758b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1759b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1760bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1761b210c64bSSam Clegg 
1762b210c64bSSam Clegg     auto IT = WS.begin();
1763b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1764b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1765b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1766b210c64bSSam Clegg 
1767b210c64bSSam Clegg     IT = std::next(IT);
1768b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1769bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1770bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1771bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1772bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1773b210c64bSSam Clegg 
1774b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1775bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1776bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1777b210c64bSSam Clegg 
1778bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17794d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17807d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17817d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1782f208f631SHeejin Ahn         report_fatal_error(
1783f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17847d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1785bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1786bafe6902SSam Clegg     }
1787bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1788bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1789f208f631SHeejin Ahn     for (const uint8_t *
179018c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
179118c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
179218c56a07SHeejin Ahn          P != End; ++P) {
179318c56a07SHeejin Ahn       if (*P != 0)
1794bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1795bafe6902SSam Clegg     }
1796bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1797f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1798f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1799bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
18008fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
18018fffa1dfSSam Clegg       if (!SymRef)
1802bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
18038fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
18048fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
18053ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
18068fffa1dfSSam Clegg       if (!TargetSym.isFunction())
18078fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
180825d8e68bSSam Clegg       InitFuncs.push_back(
18098fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1810bafe6902SSam Clegg     }
1811bafe6902SSam Clegg   }
1812bafe6902SSam Clegg 
181318eafb6cSDan Gohman   // Write out the Wasm header.
181418eafb6cSDan Gohman   writeHeader(Asm);
181518eafb6cSDan Gohman 
18160ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
18170ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1818da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1819f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
18209e15f359SSam Clegg     writeFunctionSection(Functions);
1821d823cc7cSAndy Wingo     writeTableSection(Tables);
1822f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1823da419bdbSHeejin Ahn     writeEventSection(Events);
18240a6c4d8dSSam Clegg     writeGlobalSection(Globals);
18259e15f359SSam Clegg     writeExportSection(Exports);
18269e15f359SSam Clegg     writeElemSection(TableElems);
1827fef8de66SThomas Lively     writeDataCountSection();
18280ff28fa6SDerek Schuff 
18290ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
18300ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
18310ff28fa6SDerek Schuff   }
18320ff28fa6SDerek Schuff 
18330a391060SDerek Schuff   // The Sections in the COMDAT list have placeholder indices (their index among
18340a391060SDerek Schuff   // custom sections, rather than among all sections). Fix them up here.
18350a391060SDerek Schuff   for (auto &Group : Comdats) {
18360a391060SDerek Schuff     for (auto &Entry : Group.second) {
18370a391060SDerek Schuff       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
18380a391060SDerek Schuff         Entry.Index += SectionCount;
18390ff28fa6SDerek Schuff       }
18400a391060SDerek Schuff     }
18410a391060SDerek Schuff   }
18420a391060SDerek Schuff   for (auto &CustomSection : CustomSections)
18430a391060SDerek Schuff     writeCustomSection(CustomSection, Asm, Layout);
18440ff28fa6SDerek Schuff 
18450ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1846c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
18470ff28fa6SDerek Schuff 
18486f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
18496f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
18500ff28fa6SDerek Schuff   }
18516a31a0d6SSam Clegg   writeCustomRelocSections();
1852cbda16ebSThomas Lively   if (ProducersSection)
1853cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1854f6f4f843SThomas Lively   if (TargetFeaturesSection)
1855f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1856970d02c4SDan Gohman 
1857d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
18580ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
185918eafb6cSDan Gohman }
186018eafb6cSDan Gohman 
186160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
18621301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
186318eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
18640eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
186518eafb6cSDan Gohman }
18660ff28fa6SDerek Schuff 
18670ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
18680ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18690ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
18700ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18710ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18720ff28fa6SDerek Schuff }
1873