10b57cec5SDimitry Andric //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements Wasm object file writer information.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
150b57cec5SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
160b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
170b57cec5SDimitry Andric #include "llvm/MC/MCAsmBackend.h"
180b57cec5SDimitry Andric #include "llvm/MC/MCAsmLayout.h"
190b57cec5SDimitry Andric #include "llvm/MC/MCAssembler.h"
200b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
210b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
220b57cec5SDimitry Andric #include "llvm/MC/MCFixupKindInfo.h"
230b57cec5SDimitry Andric #include "llvm/MC/MCObjectWriter.h"
240b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
250b57cec5SDimitry Andric #include "llvm/MC/MCSymbolWasm.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCWasmObjectWriter.h"
280b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
290b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
300b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
310b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
320b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h"
330b57cec5SDimitry Andric #include <vector>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric #define DEBUG_TYPE "mc"
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric namespace {
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric // Went we ceate the indirect function table we start at 1, so that there is
420b57cec5SDimitry Andric // and emtpy slot at 0 and therefore calling a null function pointer will trap.
430b57cec5SDimitry Andric static const uint32_t InitialTableOffset = 1;
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric // For patching purposes, we need to remember where each section starts, both
460b57cec5SDimitry Andric // for patching up the section size field, and for patching up references to
470b57cec5SDimitry Andric // locations within the section.
480b57cec5SDimitry Andric struct SectionBookkeeping {
490b57cec5SDimitry Andric   // Where the size of the section is written.
500b57cec5SDimitry Andric   uint64_t SizeOffset;
510b57cec5SDimitry Andric   // Where the section header ends (without custom section name).
520b57cec5SDimitry Andric   uint64_t PayloadOffset;
530b57cec5SDimitry Andric   // Where the contents of the section starts.
540b57cec5SDimitry Andric   uint64_t ContentsOffset;
550b57cec5SDimitry Andric   uint32_t Index;
560b57cec5SDimitry Andric };
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric // The signature of a wasm function or event, in a struct capable of being used
590b57cec5SDimitry Andric // as a DenseMap key.
600b57cec5SDimitry Andric // TODO: Consider using wasm::WasmSignature directly instead.
610b57cec5SDimitry Andric struct WasmSignature {
620b57cec5SDimitry Andric   // Support empty and tombstone instances, needed by DenseMap.
630b57cec5SDimitry Andric   enum { Plain, Empty, Tombstone } State = Plain;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   // The return types of the function.
660b57cec5SDimitry Andric   SmallVector<wasm::ValType, 1> Returns;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   // The parameter types of the function.
690b57cec5SDimitry Andric   SmallVector<wasm::ValType, 4> Params;
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric   bool operator==(const WasmSignature &Other) const {
720b57cec5SDimitry Andric     return State == Other.State && Returns == Other.Returns &&
730b57cec5SDimitry Andric            Params == Other.Params;
740b57cec5SDimitry Andric   }
750b57cec5SDimitry Andric };
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric // Traits for using WasmSignature in a DenseMap.
780b57cec5SDimitry Andric struct WasmSignatureDenseMapInfo {
790b57cec5SDimitry Andric   static WasmSignature getEmptyKey() {
800b57cec5SDimitry Andric     WasmSignature Sig;
810b57cec5SDimitry Andric     Sig.State = WasmSignature::Empty;
820b57cec5SDimitry Andric     return Sig;
830b57cec5SDimitry Andric   }
840b57cec5SDimitry Andric   static WasmSignature getTombstoneKey() {
850b57cec5SDimitry Andric     WasmSignature Sig;
860b57cec5SDimitry Andric     Sig.State = WasmSignature::Tombstone;
870b57cec5SDimitry Andric     return Sig;
880b57cec5SDimitry Andric   }
890b57cec5SDimitry Andric   static unsigned getHashValue(const WasmSignature &Sig) {
900b57cec5SDimitry Andric     uintptr_t Value = Sig.State;
910b57cec5SDimitry Andric     for (wasm::ValType Ret : Sig.Returns)
920b57cec5SDimitry Andric       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
930b57cec5SDimitry Andric     for (wasm::ValType Param : Sig.Params)
940b57cec5SDimitry Andric       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
950b57cec5SDimitry Andric     return Value;
960b57cec5SDimitry Andric   }
970b57cec5SDimitry Andric   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
980b57cec5SDimitry Andric     return LHS == RHS;
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric };
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric // A wasm data segment.  A wasm binary contains only a single data section
1030b57cec5SDimitry Andric // but that can contain many segments, each with their own virtual location
1040b57cec5SDimitry Andric // in memory.  Each MCSection data created by llvm is modeled as its own
1050b57cec5SDimitry Andric // wasm data segment.
1060b57cec5SDimitry Andric struct WasmDataSegment {
1070b57cec5SDimitry Andric   MCSectionWasm *Section;
1080b57cec5SDimitry Andric   StringRef Name;
1090b57cec5SDimitry Andric   uint32_t InitFlags;
1100b57cec5SDimitry Andric   uint32_t Offset;
1110b57cec5SDimitry Andric   uint32_t Alignment;
1120b57cec5SDimitry Andric   uint32_t LinkerFlags;
1130b57cec5SDimitry Andric   SmallVector<char, 4> Data;
1140b57cec5SDimitry Andric };
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric // A wasm function to be written into the function section.
1170b57cec5SDimitry Andric struct WasmFunction {
1180b57cec5SDimitry Andric   uint32_t SigIndex;
1190b57cec5SDimitry Andric   const MCSymbolWasm *Sym;
1200b57cec5SDimitry Andric };
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric // A wasm global to be written into the global section.
1230b57cec5SDimitry Andric struct WasmGlobal {
1240b57cec5SDimitry Andric   wasm::WasmGlobalType Type;
1250b57cec5SDimitry Andric   uint64_t InitialValue;
1260b57cec5SDimitry Andric };
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric // Information about a single item which is part of a COMDAT.  For each data
1290b57cec5SDimitry Andric // segment or function which is in the COMDAT, there is a corresponding
1300b57cec5SDimitry Andric // WasmComdatEntry.
1310b57cec5SDimitry Andric struct WasmComdatEntry {
1320b57cec5SDimitry Andric   unsigned Kind;
1330b57cec5SDimitry Andric   uint32_t Index;
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric // Information about a single relocation.
1370b57cec5SDimitry Andric struct WasmRelocationEntry {
1380b57cec5SDimitry Andric   uint64_t Offset;                   // Where is the relocation.
1390b57cec5SDimitry Andric   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1400b57cec5SDimitry Andric   int64_t Addend;                    // A value to add to the symbol.
1410b57cec5SDimitry Andric   unsigned Type;                     // The type of the relocation.
1420b57cec5SDimitry Andric   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1450b57cec5SDimitry Andric                       int64_t Addend, unsigned Type,
1460b57cec5SDimitry Andric                       const MCSectionWasm *FixupSection)
1470b57cec5SDimitry Andric       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1480b57cec5SDimitry Andric         FixupSection(FixupSection) {}
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   void print(raw_ostream &Out) const {
1530b57cec5SDimitry Andric     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
1540b57cec5SDimitry Andric         << ", Sym=" << *Symbol << ", Addend=" << Addend
1550b57cec5SDimitry Andric         << ", FixupSection=" << FixupSection->getSectionName();
1560b57cec5SDimitry Andric   }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1590b57cec5SDimitry Andric   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1600b57cec5SDimitry Andric #endif
1610b57cec5SDimitry Andric };
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric static const uint32_t InvalidIndex = -1;
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric struct WasmCustomSection {
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   StringRef Name;
1680b57cec5SDimitry Andric   MCSectionWasm *Section;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   uint32_t OutputContentsOffset;
1710b57cec5SDimitry Andric   uint32_t OutputIndex;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1740b57cec5SDimitry Andric       : Name(Name), Section(Section), OutputContentsOffset(0),
1750b57cec5SDimitry Andric         OutputIndex(InvalidIndex) {}
1760b57cec5SDimitry Andric };
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric #if !defined(NDEBUG)
1790b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
1800b57cec5SDimitry Andric   Rel.print(OS);
1810b57cec5SDimitry Andric   return OS;
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric #endif
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
1860b57cec5SDimitry Andric // to allow patching.
1870b57cec5SDimitry Andric static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
1880b57cec5SDimitry Andric                               uint64_t Offset) {
1890b57cec5SDimitry Andric   uint8_t Buffer[5];
1900b57cec5SDimitry Andric   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
1910b57cec5SDimitry Andric   assert(SizeLen == 5);
1920b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, SizeLen, Offset);
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric // Write X as an signed LEB value at offset Offset in Stream, padded
1960b57cec5SDimitry Andric // to allow patching.
1970b57cec5SDimitry Andric static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
1980b57cec5SDimitry Andric                                uint64_t Offset) {
1990b57cec5SDimitry Andric   uint8_t Buffer[5];
2000b57cec5SDimitry Andric   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
2010b57cec5SDimitry Andric   assert(SizeLen == 5);
2020b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, SizeLen, Offset);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric // Write X as a plain integer value at offset Offset in Stream.
2060b57cec5SDimitry Andric static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
2070b57cec5SDimitry Andric   uint8_t Buffer[4];
2080b57cec5SDimitry Andric   support::endian::write32le(Buffer, X);
2090b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric class WasmObjectWriter : public MCObjectWriter {
2130b57cec5SDimitry Andric   support::endian::Writer W;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   /// The target specific Wasm writer instance.
2160b57cec5SDimitry Andric   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   // Relocations for fixing up references in the code section.
2190b57cec5SDimitry Andric   std::vector<WasmRelocationEntry> CodeRelocations;
2200b57cec5SDimitry Andric   uint32_t CodeSectionIndex;
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   // Relocations for fixing up references in the data section.
2230b57cec5SDimitry Andric   std::vector<WasmRelocationEntry> DataRelocations;
2240b57cec5SDimitry Andric   uint32_t DataSectionIndex;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   // Index values to use for fixing up call_indirect type indices.
2270b57cec5SDimitry Andric   // Maps function symbols to the index of the type of the function
2280b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
2290b57cec5SDimitry Andric   // Maps function symbols to the table element index space. Used
2300b57cec5SDimitry Andric   // for TABLE_INDEX relocation types (i.e. address taken functions).
2310b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2320b57cec5SDimitry Andric   // Maps function/global symbols to the function/global/event/section index
2330b57cec5SDimitry Andric   // space.
2340b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2350b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2360b57cec5SDimitry Andric   // Maps data symbols to the Wasm segment and offset/size with the segment.
2370b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   // Stores output data (index, relocations, content offset) for custom
2400b57cec5SDimitry Andric   // section.
2410b57cec5SDimitry Andric   std::vector<WasmCustomSection> CustomSections;
2420b57cec5SDimitry Andric   std::unique_ptr<WasmCustomSection> ProducersSection;
2430b57cec5SDimitry Andric   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2440b57cec5SDimitry Andric   // Relocations for fixing up references in the custom sections.
2450b57cec5SDimitry Andric   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2460b57cec5SDimitry Andric       CustomSectionsRelocations;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   // Map from section to defining function symbol.
2490b57cec5SDimitry Andric   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
2520b57cec5SDimitry Andric   SmallVector<WasmSignature, 4> Signatures;
2530b57cec5SDimitry Andric   SmallVector<WasmDataSegment, 4> DataSegments;
2540b57cec5SDimitry Andric   unsigned NumFunctionImports = 0;
2550b57cec5SDimitry Andric   unsigned NumGlobalImports = 0;
2560b57cec5SDimitry Andric   unsigned NumEventImports = 0;
2570b57cec5SDimitry Andric   uint32_t SectionCount = 0;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   // TargetObjectWriter wrappers.
2600b57cec5SDimitry Andric   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
2618bcb0991SDimitry Andric   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2640b57cec5SDimitry Andric   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
2650b57cec5SDimitry Andric   void endSection(SectionBookkeeping &Section);
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric public:
2680b57cec5SDimitry Andric   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2690b57cec5SDimitry Andric                    raw_pwrite_stream &OS)
2700b57cec5SDimitry Andric       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric private:
2730b57cec5SDimitry Andric   void reset() override {
2740b57cec5SDimitry Andric     CodeRelocations.clear();
2750b57cec5SDimitry Andric     DataRelocations.clear();
2760b57cec5SDimitry Andric     TypeIndices.clear();
2770b57cec5SDimitry Andric     WasmIndices.clear();
2780b57cec5SDimitry Andric     GOTIndices.clear();
2790b57cec5SDimitry Andric     TableIndices.clear();
2800b57cec5SDimitry Andric     DataLocations.clear();
2810b57cec5SDimitry Andric     CustomSections.clear();
2820b57cec5SDimitry Andric     ProducersSection.reset();
2830b57cec5SDimitry Andric     TargetFeaturesSection.reset();
2840b57cec5SDimitry Andric     CustomSectionsRelocations.clear();
2850b57cec5SDimitry Andric     SignatureIndices.clear();
2860b57cec5SDimitry Andric     Signatures.clear();
2870b57cec5SDimitry Andric     DataSegments.clear();
2880b57cec5SDimitry Andric     SectionFunctions.clear();
2890b57cec5SDimitry Andric     NumFunctionImports = 0;
2900b57cec5SDimitry Andric     NumGlobalImports = 0;
2910b57cec5SDimitry Andric     MCObjectWriter::reset();
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   void writeHeader(const MCAssembler &Asm);
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
2970b57cec5SDimitry Andric                         const MCFragment *Fragment, const MCFixup &Fixup,
2980b57cec5SDimitry Andric                         MCValue Target, uint64_t &FixedValue) override;
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   void executePostLayoutBinding(MCAssembler &Asm,
3010b57cec5SDimitry Andric                                 const MCAsmLayout &Layout) override;
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   void writeString(const StringRef Str) {
3060b57cec5SDimitry Andric     encodeULEB128(Str.size(), W.OS);
3070b57cec5SDimitry Andric     W.OS << Str;
3080b57cec5SDimitry Andric   }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3130b57cec5SDimitry Andric   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
3140b57cec5SDimitry Andric                           uint32_t NumElements);
3150b57cec5SDimitry Andric   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3160b57cec5SDimitry Andric   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
3170b57cec5SDimitry Andric   void writeElemSection(ArrayRef<uint32_t> TableElems);
3180b57cec5SDimitry Andric   void writeDataCountSection();
3190b57cec5SDimitry Andric   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
3200b57cec5SDimitry Andric                         ArrayRef<WasmFunction> Functions);
3210b57cec5SDimitry Andric   void writeDataSection();
3220b57cec5SDimitry Andric   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3230b57cec5SDimitry Andric   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3240b57cec5SDimitry Andric                          std::vector<WasmRelocationEntry> &Relocations);
3250b57cec5SDimitry Andric   void writeLinkingMetaDataSection(
3260b57cec5SDimitry Andric       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
3270b57cec5SDimitry Andric       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
3280b57cec5SDimitry Andric       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3290b57cec5SDimitry Andric   void writeCustomSection(WasmCustomSection &CustomSection,
3300b57cec5SDimitry Andric                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3310b57cec5SDimitry Andric   void writeCustomRelocSections();
3320b57cec5SDimitry Andric   void
3330b57cec5SDimitry Andric   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3340b57cec5SDimitry Andric                                  const MCAsmLayout &Layout);
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
3370b57cec5SDimitry Andric   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3380b57cec5SDimitry Andric                         uint64_t ContentsOffset);
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3410b57cec5SDimitry Andric   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3420b57cec5SDimitry Andric   uint32_t getEventType(const MCSymbolWasm &Symbol);
3430b57cec5SDimitry Andric   void registerFunctionType(const MCSymbolWasm &Symbol);
3440b57cec5SDimitry Andric   void registerEventType(const MCSymbolWasm &Symbol);
3450b57cec5SDimitry Andric };
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric } // end anonymous namespace
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric // Write out a section header and a patchable section size field.
3500b57cec5SDimitry Andric void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3510b57cec5SDimitry Andric                                     unsigned SectionId) {
3520b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3530b57cec5SDimitry Andric   W.OS << char(SectionId);
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   Section.SizeOffset = W.OS.tell();
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   // The section size. We don't know the size yet, so reserve enough space
3580b57cec5SDimitry Andric   // for any 32-bit value; we'll patch it later.
3590b57cec5SDimitry Andric   encodeULEB128(0, W.OS, 5);
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // The position where the section starts, for measuring its size.
3620b57cec5SDimitry Andric   Section.ContentsOffset = W.OS.tell();
3630b57cec5SDimitry Andric   Section.PayloadOffset = W.OS.tell();
3640b57cec5SDimitry Andric   Section.Index = SectionCount++;
3650b57cec5SDimitry Andric }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3680b57cec5SDimitry Andric                                           StringRef Name) {
3690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3700b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_CUSTOM);
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   // The position where the section header ends, for measuring its size.
3730b57cec5SDimitry Andric   Section.PayloadOffset = W.OS.tell();
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // Custom sections in wasm also have a string identifier.
3760b57cec5SDimitry Andric   writeString(Name);
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   // The position where the custom section starts.
3790b57cec5SDimitry Andric   Section.ContentsOffset = W.OS.tell();
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric // Now that the section is complete and we know how big it is, patch up the
3830b57cec5SDimitry Andric // section size field at the start of the section.
3840b57cec5SDimitry Andric void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3850b57cec5SDimitry Andric   uint64_t Size = W.OS.tell();
3860b57cec5SDimitry Andric   // /dev/null doesn't support seek/tell and can report offset of 0.
3870b57cec5SDimitry Andric   // Simply skip this patching in that case.
3880b57cec5SDimitry Andric   if (!Size)
3890b57cec5SDimitry Andric     return;
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   Size -= Section.PayloadOffset;
3920b57cec5SDimitry Andric   if (uint32_t(Size) != Size)
3930b57cec5SDimitry Andric     report_fatal_error("section size does not fit in a uint32_t");
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   // Write the final section size to the payload_len field, which follows
3980b57cec5SDimitry Andric   // the section id byte.
3990b57cec5SDimitry Andric   writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
4000b57cec5SDimitry Andric                     Section.SizeOffset);
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric // Emit the Wasm header.
4040b57cec5SDimitry Andric void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4050b57cec5SDimitry Andric   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4060b57cec5SDimitry Andric   W.write<uint32_t>(wasm::WasmVersion);
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
4100b57cec5SDimitry Andric                                                 const MCAsmLayout &Layout) {
4110b57cec5SDimitry Andric   // Build a map of sections to the function that defines them, for use
4120b57cec5SDimitry Andric   // in recordRelocation.
4130b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
4140b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4150b57cec5SDimitry Andric     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4160b57cec5SDimitry Andric       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4170b57cec5SDimitry Andric       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4180b57cec5SDimitry Andric       if (!Pair.second)
4190b57cec5SDimitry Andric         report_fatal_error("section already has a defining function: " +
4200b57cec5SDimitry Andric                            Sec.getSectionName());
4210b57cec5SDimitry Andric     }
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
4260b57cec5SDimitry Andric                                         const MCAsmLayout &Layout,
4270b57cec5SDimitry Andric                                         const MCFragment *Fragment,
4280b57cec5SDimitry Andric                                         const MCFixup &Fixup, MCValue Target,
4290b57cec5SDimitry Andric                                         uint64_t &FixedValue) {
4308bcb0991SDimitry Andric   // The WebAssembly backend should never generate FKF_IsPCRel fixups
4318bcb0991SDimitry Andric   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
4328bcb0991SDimitry Andric            MCFixupKindInfo::FKF_IsPCRel));
4338bcb0991SDimitry Andric 
4340b57cec5SDimitry Andric   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
4350b57cec5SDimitry Andric   uint64_t C = Target.getConstant();
4360b57cec5SDimitry Andric   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
4370b57cec5SDimitry Andric   MCContext &Ctx = Asm.getContext();
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   // The .init_array isn't translated as data, so don't do relocations in it.
4400b57cec5SDimitry Andric   if (FixupSection.getSectionName().startswith(".init_array"))
4410b57cec5SDimitry Andric     return;
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
4448bcb0991SDimitry Andric     // To get here the A - B expression must have failed evaluateAsRelocatable.
4458bcb0991SDimitry Andric     // This means either A or B must be undefined and in WebAssembly we can't
4468bcb0991SDimitry Andric     // support either of those cases.
4478bcb0991SDimitry Andric     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
4480b57cec5SDimitry Andric     Ctx.reportError(
4490b57cec5SDimitry Andric         Fixup.getLoc(),
4500b57cec5SDimitry Andric         Twine("symbol '") + SymB.getName() +
4518bcb0991SDimitry Andric             "': unsupported subtraction expression used in relocation.");
4520b57cec5SDimitry Andric     return;
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // We either rejected the fixup or folded B into C at this point.
4560b57cec5SDimitry Andric   const MCSymbolRefExpr *RefA = Target.getSymA();
4578bcb0991SDimitry Andric   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
4580b57cec5SDimitry Andric 
4598bcb0991SDimitry Andric   if (SymA->isVariable()) {
4600b57cec5SDimitry Andric     const MCExpr *Expr = SymA->getVariableValue();
4610b57cec5SDimitry Andric     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4620b57cec5SDimitry Andric     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4630b57cec5SDimitry Andric       llvm_unreachable("weakref used in reloc not yet implemented");
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   // Put any constant offset in an addend. Offsets can be negative, and
4670b57cec5SDimitry Andric   // LLVM expects wrapping, in contrast to wasm's immediates which can't
4680b57cec5SDimitry Andric   // be negative and don't wrap.
4690b57cec5SDimitry Andric   FixedValue = 0;
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // Absolute offset within a section or a function.
4740b57cec5SDimitry Andric   // Currently only supported for for metadata sections.
4750b57cec5SDimitry Andric   // See: test/MC/WebAssembly/blockaddress.ll
4760b57cec5SDimitry Andric   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
4770b57cec5SDimitry Andric       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4780b57cec5SDimitry Andric     if (!FixupSection.getKind().isMetadata())
4790b57cec5SDimitry Andric       report_fatal_error("relocations for function or section offsets are "
4800b57cec5SDimitry Andric                          "only supported in metadata sections");
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric     const MCSymbol *SectionSymbol = nullptr;
4830b57cec5SDimitry Andric     const MCSection &SecA = SymA->getSection();
4840b57cec5SDimitry Andric     if (SecA.getKind().isText())
4850b57cec5SDimitry Andric       SectionSymbol = SectionFunctions.find(&SecA)->second;
4860b57cec5SDimitry Andric     else
4870b57cec5SDimitry Andric       SectionSymbol = SecA.getBeginSymbol();
4880b57cec5SDimitry Andric     if (!SectionSymbol)
4890b57cec5SDimitry Andric       report_fatal_error("section symbol is required for relocation");
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric     C += Layout.getSymbolOffset(*SymA);
4920b57cec5SDimitry Andric     SymA = cast<MCSymbolWasm>(SectionSymbol);
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
4960b57cec5SDimitry Andric   // against a named symbol.
4970b57cec5SDimitry Andric   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
4980b57cec5SDimitry Andric     if (SymA->getName().empty())
4990b57cec5SDimitry Andric       report_fatal_error("relocations against un-named temporaries are not yet "
5000b57cec5SDimitry Andric                          "supported by wasm");
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric     SymA->setUsedInReloc();
5030b57cec5SDimitry Andric   }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
5060b57cec5SDimitry Andric     SymA->setUsedInGOT();
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
5090b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   if (FixupSection.isWasmData()) {
5120b57cec5SDimitry Andric     DataRelocations.push_back(Rec);
5130b57cec5SDimitry Andric   } else if (FixupSection.getKind().isText()) {
5140b57cec5SDimitry Andric     CodeRelocations.push_back(Rec);
5150b57cec5SDimitry Andric   } else if (FixupSection.getKind().isMetadata()) {
5160b57cec5SDimitry Andric     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5170b57cec5SDimitry Andric   } else {
5180b57cec5SDimitry Andric     llvm_unreachable("unexpected section type");
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric }
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
5230b57cec5SDimitry Andric   const MCSymbolWasm* Ret = &Symbol;
5240b57cec5SDimitry Andric   while (Ret->isVariable()) {
5250b57cec5SDimitry Andric     const MCExpr *Expr = Ret->getVariableValue();
5260b57cec5SDimitry Andric     auto *Inner = cast<MCSymbolRefExpr>(Expr);
5270b57cec5SDimitry Andric     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
5280b57cec5SDimitry Andric   }
5290b57cec5SDimitry Andric   return Ret;
5300b57cec5SDimitry Andric }
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric // Compute a value to write into the code at the location covered
5330b57cec5SDimitry Andric // by RelEntry. This value isn't used by the static linker; it just serves
5340b57cec5SDimitry Andric // to make the object format more readable and more likely to be directly
5350b57cec5SDimitry Andric // useable.
5360b57cec5SDimitry Andric uint32_t
5370b57cec5SDimitry Andric WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
5380b57cec5SDimitry Andric   if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
5390b57cec5SDimitry Andric     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
5400b57cec5SDimitry Andric     return GOTIndices[RelEntry.Symbol];
5410b57cec5SDimitry Andric   }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   switch (RelEntry.Type) {
5440b57cec5SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
5450b57cec5SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_SLEB:
5460b57cec5SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_I32: {
5470b57cec5SDimitry Andric     // Provisional value is table address of the resolved symbol itself
5480b57cec5SDimitry Andric     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
5490b57cec5SDimitry Andric     assert(Sym->isFunction());
5500b57cec5SDimitry Andric     return TableIndices[Sym];
5510b57cec5SDimitry Andric   }
5520b57cec5SDimitry Andric   case wasm::R_WASM_TYPE_INDEX_LEB:
5530b57cec5SDimitry Andric     // Provisional value is same as the index
5540b57cec5SDimitry Andric     return getRelocationIndexValue(RelEntry);
5550b57cec5SDimitry Andric   case wasm::R_WASM_FUNCTION_INDEX_LEB:
5560b57cec5SDimitry Andric   case wasm::R_WASM_GLOBAL_INDEX_LEB:
5570b57cec5SDimitry Andric   case wasm::R_WASM_EVENT_INDEX_LEB:
5580b57cec5SDimitry Andric     // Provisional value is function/global/event Wasm index
5590b57cec5SDimitry Andric     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5600b57cec5SDimitry Andric     return WasmIndices[RelEntry.Symbol];
5610b57cec5SDimitry Andric   case wasm::R_WASM_FUNCTION_OFFSET_I32:
5620b57cec5SDimitry Andric   case wasm::R_WASM_SECTION_OFFSET_I32: {
5630b57cec5SDimitry Andric     const auto &Section =
5640b57cec5SDimitry Andric         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5650b57cec5SDimitry Andric     return Section.getSectionOffset() + RelEntry.Addend;
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_LEB:
5680b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_I32:
5690b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5700b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_SLEB: {
5710b57cec5SDimitry Andric     // Provisional value is address of the global
5720b57cec5SDimitry Andric     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
5730b57cec5SDimitry Andric     // For undefined symbols, use zero
5740b57cec5SDimitry Andric     if (!Sym->isDefined())
5750b57cec5SDimitry Andric       return 0;
5760b57cec5SDimitry Andric     const wasm::WasmDataReference &Ref = DataLocations[Sym];
5770b57cec5SDimitry Andric     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
5780b57cec5SDimitry Andric     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5790b57cec5SDimitry Andric     return Segment.Offset + Ref.Offset + RelEntry.Addend;
5800b57cec5SDimitry Andric   }
5810b57cec5SDimitry Andric   default:
5820b57cec5SDimitry Andric     llvm_unreachable("invalid relocation type");
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric static void addData(SmallVectorImpl<char> &DataBytes,
5870b57cec5SDimitry Andric                     MCSectionWasm &DataSection) {
5880b57cec5SDimitry Andric   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   for (const MCFragment &Frag : DataSection) {
5930b57cec5SDimitry Andric     if (Frag.hasInstructions())
5940b57cec5SDimitry Andric       report_fatal_error("only data supported in data sections");
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
5970b57cec5SDimitry Andric       if (Align->getValueSize() != 1)
5980b57cec5SDimitry Andric         report_fatal_error("only byte values supported for alignment");
5990b57cec5SDimitry Andric       // If nops are requested, use zeros, as this is the data section.
6000b57cec5SDimitry Andric       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
6010b57cec5SDimitry Andric       uint64_t Size =
6020b57cec5SDimitry Andric           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
6030b57cec5SDimitry Andric                              DataBytes.size() + Align->getMaxBytesToEmit());
6040b57cec5SDimitry Andric       DataBytes.resize(Size, Value);
6050b57cec5SDimitry Andric     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
6060b57cec5SDimitry Andric       int64_t NumValues;
6070b57cec5SDimitry Andric       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
6080b57cec5SDimitry Andric         llvm_unreachable("The fill should be an assembler constant");
6090b57cec5SDimitry Andric       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
6100b57cec5SDimitry Andric                        Fill->getValue());
6110b57cec5SDimitry Andric     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
6120b57cec5SDimitry Andric       const SmallVectorImpl<char> &Contents = LEB->getContents();
6130b57cec5SDimitry Andric       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
6140b57cec5SDimitry Andric     } else {
6150b57cec5SDimitry Andric       const auto &DataFrag = cast<MCDataFragment>(Frag);
6160b57cec5SDimitry Andric       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
6170b57cec5SDimitry Andric       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
6180b57cec5SDimitry Andric     }
6190b57cec5SDimitry Andric   }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric uint32_t
6250b57cec5SDimitry Andric WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
6260b57cec5SDimitry Andric   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
6270b57cec5SDimitry Andric     if (!TypeIndices.count(RelEntry.Symbol))
6280b57cec5SDimitry Andric       report_fatal_error("symbol not found in type index space: " +
6290b57cec5SDimitry Andric                          RelEntry.Symbol->getName());
6300b57cec5SDimitry Andric     return TypeIndices[RelEntry.Symbol];
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   return RelEntry.Symbol->getIndex();
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric // Apply the portions of the relocation records that we can handle ourselves
6370b57cec5SDimitry Andric // directly.
6380b57cec5SDimitry Andric void WasmObjectWriter::applyRelocations(
6390b57cec5SDimitry Andric     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
6400b57cec5SDimitry Andric   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
6410b57cec5SDimitry Andric   for (const WasmRelocationEntry &RelEntry : Relocations) {
6420b57cec5SDimitry Andric     uint64_t Offset = ContentsOffset +
6430b57cec5SDimitry Andric                       RelEntry.FixupSection->getSectionOffset() +
6440b57cec5SDimitry Andric                       RelEntry.Offset;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6470b57cec5SDimitry Andric     uint32_t Value = getProvisionalValue(RelEntry);
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric     switch (RelEntry.Type) {
6500b57cec5SDimitry Andric     case wasm::R_WASM_FUNCTION_INDEX_LEB:
6510b57cec5SDimitry Andric     case wasm::R_WASM_TYPE_INDEX_LEB:
6520b57cec5SDimitry Andric     case wasm::R_WASM_GLOBAL_INDEX_LEB:
6530b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_LEB:
6540b57cec5SDimitry Andric     case wasm::R_WASM_EVENT_INDEX_LEB:
6550b57cec5SDimitry Andric       writePatchableLEB(Stream, Value, Offset);
6560b57cec5SDimitry Andric       break;
6570b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_I32:
6580b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_I32:
6590b57cec5SDimitry Andric     case wasm::R_WASM_FUNCTION_OFFSET_I32:
6600b57cec5SDimitry Andric     case wasm::R_WASM_SECTION_OFFSET_I32:
6610b57cec5SDimitry Andric       writeI32(Stream, Value, Offset);
6620b57cec5SDimitry Andric       break;
6630b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_SLEB:
6640b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
6650b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6660b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6670b57cec5SDimitry Andric       writePatchableSLEB(Stream, Value, Offset);
6680b57cec5SDimitry Andric       break;
6690b57cec5SDimitry Andric     default:
6700b57cec5SDimitry Andric       llvm_unreachable("invalid relocation type");
6710b57cec5SDimitry Andric     }
6720b57cec5SDimitry Andric   }
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
6760b57cec5SDimitry Andric   if (Signatures.empty())
6770b57cec5SDimitry Andric     return;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   SectionBookkeeping Section;
6800b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_TYPE);
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   encodeULEB128(Signatures.size(), W.OS);
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   for (const WasmSignature &Sig : Signatures) {
6850b57cec5SDimitry Andric     W.OS << char(wasm::WASM_TYPE_FUNC);
6860b57cec5SDimitry Andric     encodeULEB128(Sig.Params.size(), W.OS);
6870b57cec5SDimitry Andric     for (wasm::ValType Ty : Sig.Params)
6880b57cec5SDimitry Andric       writeValueType(Ty);
6890b57cec5SDimitry Andric     encodeULEB128(Sig.Returns.size(), W.OS);
6900b57cec5SDimitry Andric     for (wasm::ValType Ty : Sig.Returns)
6910b57cec5SDimitry Andric       writeValueType(Ty);
6920b57cec5SDimitry Andric   }
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric   endSection(Section);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
6980b57cec5SDimitry Andric                                           uint32_t DataSize,
6990b57cec5SDimitry Andric                                           uint32_t NumElements) {
7000b57cec5SDimitry Andric   if (Imports.empty())
7010b57cec5SDimitry Andric     return;
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   SectionBookkeeping Section;
7060b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_IMPORT);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   encodeULEB128(Imports.size(), W.OS);
7090b57cec5SDimitry Andric   for (const wasm::WasmImport &Import : Imports) {
7100b57cec5SDimitry Andric     writeString(Import.Module);
7110b57cec5SDimitry Andric     writeString(Import.Field);
7120b57cec5SDimitry Andric     W.OS << char(Import.Kind);
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric     switch (Import.Kind) {
7150b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_FUNCTION:
7160b57cec5SDimitry Andric       encodeULEB128(Import.SigIndex, W.OS);
7170b57cec5SDimitry Andric       break;
7180b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_GLOBAL:
7190b57cec5SDimitry Andric       W.OS << char(Import.Global.Type);
7200b57cec5SDimitry Andric       W.OS << char(Import.Global.Mutable ? 1 : 0);
7210b57cec5SDimitry Andric       break;
7220b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_MEMORY:
7230b57cec5SDimitry Andric       encodeULEB128(0, W.OS);        // flags
7240b57cec5SDimitry Andric       encodeULEB128(NumPages, W.OS); // initial
7250b57cec5SDimitry Andric       break;
7260b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_TABLE:
7270b57cec5SDimitry Andric       W.OS << char(Import.Table.ElemType);
7280b57cec5SDimitry Andric       encodeULEB128(0, W.OS);           // flags
7290b57cec5SDimitry Andric       encodeULEB128(NumElements, W.OS); // initial
7300b57cec5SDimitry Andric       break;
7310b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_EVENT:
7320b57cec5SDimitry Andric       encodeULEB128(Import.Event.Attribute, W.OS);
7330b57cec5SDimitry Andric       encodeULEB128(Import.Event.SigIndex, W.OS);
7340b57cec5SDimitry Andric       break;
7350b57cec5SDimitry Andric     default:
7360b57cec5SDimitry Andric       llvm_unreachable("unsupported import kind");
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   endSection(Section);
7410b57cec5SDimitry Andric }
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7440b57cec5SDimitry Andric   if (Functions.empty())
7450b57cec5SDimitry Andric     return;
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   SectionBookkeeping Section;
7480b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_FUNCTION);
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   encodeULEB128(Functions.size(), W.OS);
7510b57cec5SDimitry Andric   for (const WasmFunction &Func : Functions)
7520b57cec5SDimitry Andric     encodeULEB128(Func.SigIndex, W.OS);
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric   endSection(Section);
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
7580b57cec5SDimitry Andric   if (Events.empty())
7590b57cec5SDimitry Andric     return;
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   SectionBookkeeping Section;
7620b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_EVENT);
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   encodeULEB128(Events.size(), W.OS);
7650b57cec5SDimitry Andric   for (const wasm::WasmEventType &Event : Events) {
7660b57cec5SDimitry Andric     encodeULEB128(Event.Attribute, W.OS);
7670b57cec5SDimitry Andric     encodeULEB128(Event.SigIndex, W.OS);
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   endSection(Section);
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7740b57cec5SDimitry Andric   if (Exports.empty())
7750b57cec5SDimitry Andric     return;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   SectionBookkeeping Section;
7780b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_EXPORT);
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   encodeULEB128(Exports.size(), W.OS);
7810b57cec5SDimitry Andric   for (const wasm::WasmExport &Export : Exports) {
7820b57cec5SDimitry Andric     writeString(Export.Name);
7830b57cec5SDimitry Andric     W.OS << char(Export.Kind);
7840b57cec5SDimitry Andric     encodeULEB128(Export.Index, W.OS);
7850b57cec5SDimitry Andric   }
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric   endSection(Section);
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7910b57cec5SDimitry Andric   if (TableElems.empty())
7920b57cec5SDimitry Andric     return;
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   SectionBookkeeping Section;
7950b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_ELEM);
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   encodeULEB128(1, W.OS); // number of "segments"
7980b57cec5SDimitry Andric   encodeULEB128(0, W.OS); // the table index
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   // init expr for starting offset
8010b57cec5SDimitry Andric   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
8020b57cec5SDimitry Andric   encodeSLEB128(InitialTableOffset, W.OS);
8030b57cec5SDimitry Andric   W.OS << char(wasm::WASM_OPCODE_END);
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   encodeULEB128(TableElems.size(), W.OS);
8060b57cec5SDimitry Andric   for (uint32_t Elem : TableElems)
8070b57cec5SDimitry Andric     encodeULEB128(Elem, W.OS);
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   endSection(Section);
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric void WasmObjectWriter::writeDataCountSection() {
8130b57cec5SDimitry Andric   if (DataSegments.empty())
8140b57cec5SDimitry Andric     return;
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   SectionBookkeeping Section;
8170b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_DATACOUNT);
8180b57cec5SDimitry Andric   encodeULEB128(DataSegments.size(), W.OS);
8190b57cec5SDimitry Andric   endSection(Section);
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
8230b57cec5SDimitry Andric                                         const MCAsmLayout &Layout,
8240b57cec5SDimitry Andric                                         ArrayRef<WasmFunction> Functions) {
8250b57cec5SDimitry Andric   if (Functions.empty())
8260b57cec5SDimitry Andric     return;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   SectionBookkeeping Section;
8290b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_CODE);
8300b57cec5SDimitry Andric   CodeSectionIndex = Section.Index;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   encodeULEB128(Functions.size(), W.OS);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   for (const WasmFunction &Func : Functions) {
8350b57cec5SDimitry Andric     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric     int64_t Size = 0;
8380b57cec5SDimitry Andric     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8390b57cec5SDimitry Andric       report_fatal_error(".size expression must be evaluatable");
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     encodeULEB128(Size, W.OS);
8420b57cec5SDimitry Andric     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
8430b57cec5SDimitry Andric     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // Apply fixups.
8470b57cec5SDimitry Andric   applyRelocations(CodeRelocations, Section.ContentsOffset);
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   endSection(Section);
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric void WasmObjectWriter::writeDataSection() {
8530b57cec5SDimitry Andric   if (DataSegments.empty())
8540b57cec5SDimitry Andric     return;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   SectionBookkeeping Section;
8570b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_DATA);
8580b57cec5SDimitry Andric   DataSectionIndex = Section.Index;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   encodeULEB128(DataSegments.size(), W.OS); // count
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   for (const WasmDataSegment &Segment : DataSegments) {
8630b57cec5SDimitry Andric     encodeULEB128(Segment.InitFlags, W.OS); // flags
8640b57cec5SDimitry Andric     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
8650b57cec5SDimitry Andric       encodeULEB128(0, W.OS); // memory index
8660b57cec5SDimitry Andric     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
8670b57cec5SDimitry Andric       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
8680b57cec5SDimitry Andric       encodeSLEB128(Segment.Offset, W.OS); // offset
8690b57cec5SDimitry Andric       W.OS << char(wasm::WASM_OPCODE_END);
8700b57cec5SDimitry Andric     }
8710b57cec5SDimitry Andric     encodeULEB128(Segment.Data.size(), W.OS); // size
8720b57cec5SDimitry Andric     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
8730b57cec5SDimitry Andric     W.OS << Segment.Data; // data
8740b57cec5SDimitry Andric   }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Apply fixups.
8770b57cec5SDimitry Andric   applyRelocations(DataRelocations, Section.ContentsOffset);
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   endSection(Section);
8800b57cec5SDimitry Andric }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric void WasmObjectWriter::writeRelocSection(
8830b57cec5SDimitry Andric     uint32_t SectionIndex, StringRef Name,
8840b57cec5SDimitry Andric     std::vector<WasmRelocationEntry> &Relocs) {
8850b57cec5SDimitry Andric   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8860b57cec5SDimitry Andric   // for descriptions of the reloc sections.
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   if (Relocs.empty())
8890b57cec5SDimitry Andric     return;
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   // First, ensure the relocations are sorted in offset order.  In general they
8920b57cec5SDimitry Andric   // should already be sorted since `recordRelocation` is called in offset
8930b57cec5SDimitry Andric   // order, but for the code section we combine many MC sections into single
8940b57cec5SDimitry Andric   // wasm section, and this order is determined by the order of Asm.Symbols()
8950b57cec5SDimitry Andric   // not the sections order.
8960b57cec5SDimitry Andric   llvm::stable_sort(
8970b57cec5SDimitry Andric       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
8980b57cec5SDimitry Andric         return (A.Offset + A.FixupSection->getSectionOffset()) <
8990b57cec5SDimitry Andric                (B.Offset + B.FixupSection->getSectionOffset());
9000b57cec5SDimitry Andric       });
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric   SectionBookkeeping Section;
9030b57cec5SDimitry Andric   startCustomSection(Section, std::string("reloc.") + Name.str());
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   encodeULEB128(SectionIndex, W.OS);
9060b57cec5SDimitry Andric   encodeULEB128(Relocs.size(), W.OS);
9070b57cec5SDimitry Andric   for (const WasmRelocationEntry &RelEntry : Relocs) {
9080b57cec5SDimitry Andric     uint64_t Offset =
9090b57cec5SDimitry Andric         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9100b57cec5SDimitry Andric     uint32_t Index = getRelocationIndexValue(RelEntry);
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric     W.OS << char(RelEntry.Type);
9130b57cec5SDimitry Andric     encodeULEB128(Offset, W.OS);
9140b57cec5SDimitry Andric     encodeULEB128(Index, W.OS);
9150b57cec5SDimitry Andric     if (RelEntry.hasAddend())
9160b57cec5SDimitry Andric       encodeSLEB128(RelEntry.Addend, W.OS);
9170b57cec5SDimitry Andric   }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric   endSection(Section);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric void WasmObjectWriter::writeCustomRelocSections() {
9230b57cec5SDimitry Andric   for (const auto &Sec : CustomSections) {
9240b57cec5SDimitry Andric     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9250b57cec5SDimitry Andric     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9260b57cec5SDimitry Andric   }
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric void WasmObjectWriter::writeLinkingMetaDataSection(
9300b57cec5SDimitry Andric     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
9310b57cec5SDimitry Andric     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
9320b57cec5SDimitry Andric     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9330b57cec5SDimitry Andric   SectionBookkeeping Section;
9340b57cec5SDimitry Andric   startCustomSection(Section, "linking");
9350b57cec5SDimitry Andric   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   SectionBookkeeping SubSection;
9380b57cec5SDimitry Andric   if (SymbolInfos.size() != 0) {
9390b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9400b57cec5SDimitry Andric     encodeULEB128(SymbolInfos.size(), W.OS);
9410b57cec5SDimitry Andric     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9420b57cec5SDimitry Andric       encodeULEB128(Sym.Kind, W.OS);
9430b57cec5SDimitry Andric       encodeULEB128(Sym.Flags, W.OS);
9440b57cec5SDimitry Andric       switch (Sym.Kind) {
9450b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9460b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9470b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_EVENT:
9480b57cec5SDimitry Andric         encodeULEB128(Sym.ElementIndex, W.OS);
9490b57cec5SDimitry Andric         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
9500b57cec5SDimitry Andric             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
9510b57cec5SDimitry Andric           writeString(Sym.Name);
9520b57cec5SDimitry Andric         break;
9530b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_DATA:
9540b57cec5SDimitry Andric         writeString(Sym.Name);
9550b57cec5SDimitry Andric         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9560b57cec5SDimitry Andric           encodeULEB128(Sym.DataRef.Segment, W.OS);
9570b57cec5SDimitry Andric           encodeULEB128(Sym.DataRef.Offset, W.OS);
9580b57cec5SDimitry Andric           encodeULEB128(Sym.DataRef.Size, W.OS);
9590b57cec5SDimitry Andric         }
9600b57cec5SDimitry Andric         break;
9610b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9620b57cec5SDimitry Andric         const uint32_t SectionIndex =
9630b57cec5SDimitry Andric             CustomSections[Sym.ElementIndex].OutputIndex;
9640b57cec5SDimitry Andric         encodeULEB128(SectionIndex, W.OS);
9650b57cec5SDimitry Andric         break;
9660b57cec5SDimitry Andric       }
9670b57cec5SDimitry Andric       default:
9680b57cec5SDimitry Andric         llvm_unreachable("unexpected kind");
9690b57cec5SDimitry Andric       }
9700b57cec5SDimitry Andric     }
9710b57cec5SDimitry Andric     endSection(SubSection);
9720b57cec5SDimitry Andric   }
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   if (DataSegments.size()) {
9750b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9760b57cec5SDimitry Andric     encodeULEB128(DataSegments.size(), W.OS);
9770b57cec5SDimitry Andric     for (const WasmDataSegment &Segment : DataSegments) {
9780b57cec5SDimitry Andric       writeString(Segment.Name);
9790b57cec5SDimitry Andric       encodeULEB128(Segment.Alignment, W.OS);
9800b57cec5SDimitry Andric       encodeULEB128(Segment.LinkerFlags, W.OS);
9810b57cec5SDimitry Andric     }
9820b57cec5SDimitry Andric     endSection(SubSection);
9830b57cec5SDimitry Andric   }
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   if (!InitFuncs.empty()) {
9860b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_INIT_FUNCS);
9870b57cec5SDimitry Andric     encodeULEB128(InitFuncs.size(), W.OS);
9880b57cec5SDimitry Andric     for (auto &StartFunc : InitFuncs) {
9890b57cec5SDimitry Andric       encodeULEB128(StartFunc.first, W.OS);  // priority
9900b57cec5SDimitry Andric       encodeULEB128(StartFunc.second, W.OS); // function index
9910b57cec5SDimitry Andric     }
9920b57cec5SDimitry Andric     endSection(SubSection);
9930b57cec5SDimitry Andric   }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   if (Comdats.size()) {
9960b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_COMDAT_INFO);
9970b57cec5SDimitry Andric     encodeULEB128(Comdats.size(), W.OS);
9980b57cec5SDimitry Andric     for (const auto &C : Comdats) {
9990b57cec5SDimitry Andric       writeString(C.first);
10000b57cec5SDimitry Andric       encodeULEB128(0, W.OS); // flags for future use
10010b57cec5SDimitry Andric       encodeULEB128(C.second.size(), W.OS);
10020b57cec5SDimitry Andric       for (const WasmComdatEntry &Entry : C.second) {
10030b57cec5SDimitry Andric         encodeULEB128(Entry.Kind, W.OS);
10040b57cec5SDimitry Andric         encodeULEB128(Entry.Index, W.OS);
10050b57cec5SDimitry Andric       }
10060b57cec5SDimitry Andric     }
10070b57cec5SDimitry Andric     endSection(SubSection);
10080b57cec5SDimitry Andric   }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   endSection(Section);
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
10140b57cec5SDimitry Andric                                           const MCAssembler &Asm,
10150b57cec5SDimitry Andric                                           const MCAsmLayout &Layout) {
10160b57cec5SDimitry Andric   SectionBookkeeping Section;
10170b57cec5SDimitry Andric   auto *Sec = CustomSection.Section;
10180b57cec5SDimitry Andric   startCustomSection(Section, CustomSection.Name);
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
10210b57cec5SDimitry Andric   Asm.writeSectionData(W.OS, Sec, Layout);
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10240b57cec5SDimitry Andric   CustomSection.OutputIndex = Section.Index;
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric   endSection(Section);
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // Apply fixups.
10290b57cec5SDimitry Andric   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10300b57cec5SDimitry Andric   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10340b57cec5SDimitry Andric   assert(Symbol.isFunction());
10350b57cec5SDimitry Andric   assert(TypeIndices.count(&Symbol));
10360b57cec5SDimitry Andric   return TypeIndices[&Symbol];
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
10400b57cec5SDimitry Andric   assert(Symbol.isEvent());
10410b57cec5SDimitry Andric   assert(TypeIndices.count(&Symbol));
10420b57cec5SDimitry Andric   return TypeIndices[&Symbol];
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10460b57cec5SDimitry Andric   assert(Symbol.isFunction());
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric   WasmSignature S;
10490b57cec5SDimitry Andric   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
10500b57cec5SDimitry Andric   if (auto *Sig = ResolvedSym->getSignature()) {
10510b57cec5SDimitry Andric     S.Returns = Sig->Returns;
10520b57cec5SDimitry Andric     S.Params = Sig->Params;
10530b57cec5SDimitry Andric   }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10560b57cec5SDimitry Andric   if (Pair.second)
10570b57cec5SDimitry Andric     Signatures.push_back(S);
10580b57cec5SDimitry Andric   TypeIndices[&Symbol] = Pair.first->second;
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
10610b57cec5SDimitry Andric                     << " new:" << Pair.second << "\n");
10620b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
10660b57cec5SDimitry Andric   assert(Symbol.isEvent());
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric   // TODO Currently we don't generate imported exceptions, but if we do, we
10690b57cec5SDimitry Andric   // should have a way of infering types of imported exceptions.
10700b57cec5SDimitry Andric   WasmSignature S;
10710b57cec5SDimitry Andric   if (auto *Sig = Symbol.getSignature()) {
10720b57cec5SDimitry Andric     S.Returns = Sig->Returns;
10730b57cec5SDimitry Andric     S.Params = Sig->Params;
10740b57cec5SDimitry Andric   }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10770b57cec5SDimitry Andric   if (Pair.second)
10780b57cec5SDimitry Andric     Signatures.push_back(S);
10790b57cec5SDimitry Andric   TypeIndices[&Symbol] = Pair.first->second;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
10820b57cec5SDimitry Andric                     << "\n");
10830b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10840b57cec5SDimitry Andric }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric static bool isInSymtab(const MCSymbolWasm &Sym) {
10870b57cec5SDimitry Andric   if (Sym.isUsedInReloc())
10880b57cec5SDimitry Andric     return true;
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric   if (Sym.isComdat() && !Sym.isDefined())
10910b57cec5SDimitry Andric     return false;
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   if (Sym.isTemporary() && Sym.getName().empty())
10940b57cec5SDimitry Andric     return false;
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
10970b57cec5SDimitry Andric     return false;
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   if (Sym.isSection())
11000b57cec5SDimitry Andric     return false;
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric   return true;
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
11060b57cec5SDimitry Andric                                        const MCAsmLayout &Layout) {
11070b57cec5SDimitry Andric   uint64_t StartOffset = W.OS.tell();
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Collect information from the available symbols.
11120b57cec5SDimitry Andric   SmallVector<WasmFunction, 4> Functions;
11130b57cec5SDimitry Andric   SmallVector<uint32_t, 4> TableElems;
11140b57cec5SDimitry Andric   SmallVector<wasm::WasmImport, 4> Imports;
11150b57cec5SDimitry Andric   SmallVector<wasm::WasmExport, 4> Exports;
11160b57cec5SDimitry Andric   SmallVector<wasm::WasmEventType, 1> Events;
11170b57cec5SDimitry Andric   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
11180b57cec5SDimitry Andric   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
11190b57cec5SDimitry Andric   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11200b57cec5SDimitry Andric   uint32_t DataSize = 0;
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric   // For now, always emit the memory import, since loads and stores are not
11230b57cec5SDimitry Andric   // valid without it. In the future, we could perhaps be more clever and omit
11240b57cec5SDimitry Andric   // it if there are no loads or stores.
11250b57cec5SDimitry Andric   wasm::WasmImport MemImport;
11260b57cec5SDimitry Andric   MemImport.Module = "env";
11270b57cec5SDimitry Andric   MemImport.Field = "__linear_memory";
11280b57cec5SDimitry Andric   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
11290b57cec5SDimitry Andric   Imports.push_back(MemImport);
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric   // For now, always emit the table section, since indirect calls are not
11320b57cec5SDimitry Andric   // valid without it. In the future, we could perhaps be more clever and omit
11330b57cec5SDimitry Andric   // it if there are no indirect calls.
11340b57cec5SDimitry Andric   wasm::WasmImport TableImport;
11350b57cec5SDimitry Andric   TableImport.Module = "env";
11360b57cec5SDimitry Andric   TableImport.Field = "__indirect_function_table";
11370b57cec5SDimitry Andric   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11380b57cec5SDimitry Andric   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
11390b57cec5SDimitry Andric   Imports.push_back(TableImport);
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric   // Populate SignatureIndices, and Imports and WasmIndices for undefined
11420b57cec5SDimitry Andric   // symbols.  This must be done before populating WasmIndices for defined
11430b57cec5SDimitry Andric   // symbols.
11440b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
11450b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     // Register types for all functions, including those with private linkage
11480b57cec5SDimitry Andric     // (because wasm always needs a type signature).
11490b57cec5SDimitry Andric     if (WS.isFunction())
11500b57cec5SDimitry Andric       registerFunctionType(WS);
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric     if (WS.isEvent())
11530b57cec5SDimitry Andric       registerEventType(WS);
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric     if (WS.isTemporary())
11560b57cec5SDimitry Andric       continue;
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric     // If the symbol is not defined in this translation unit, import it.
11590b57cec5SDimitry Andric     if (!WS.isDefined() && !WS.isComdat()) {
11600b57cec5SDimitry Andric       if (WS.isFunction()) {
11610b57cec5SDimitry Andric         wasm::WasmImport Import;
11620b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
11630b57cec5SDimitry Andric         Import.Field = WS.getImportName();
11640b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11650b57cec5SDimitry Andric         Import.SigIndex = getFunctionType(WS);
11660b57cec5SDimitry Andric         Imports.push_back(Import);
11670b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
11680b57cec5SDimitry Andric         WasmIndices[&WS] = NumFunctionImports++;
11690b57cec5SDimitry Andric       } else if (WS.isGlobal()) {
11700b57cec5SDimitry Andric         if (WS.isWeak())
11710b57cec5SDimitry Andric           report_fatal_error("undefined global symbol cannot be weak");
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric         wasm::WasmImport Import;
11740b57cec5SDimitry Andric         Import.Field = WS.getImportName();
11750b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11760b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
11770b57cec5SDimitry Andric         Import.Global = WS.getGlobalType();
11780b57cec5SDimitry Andric         Imports.push_back(Import);
11790b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
11800b57cec5SDimitry Andric         WasmIndices[&WS] = NumGlobalImports++;
11810b57cec5SDimitry Andric       } else if (WS.isEvent()) {
11820b57cec5SDimitry Andric         if (WS.isWeak())
11830b57cec5SDimitry Andric           report_fatal_error("undefined event symbol cannot be weak");
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric         wasm::WasmImport Import;
11860b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
11870b57cec5SDimitry Andric         Import.Field = WS.getImportName();
11880b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
11890b57cec5SDimitry Andric         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
11900b57cec5SDimitry Andric         Import.Event.SigIndex = getEventType(WS);
11910b57cec5SDimitry Andric         Imports.push_back(Import);
11920b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
11930b57cec5SDimitry Andric         WasmIndices[&WS] = NumEventImports++;
11940b57cec5SDimitry Andric       }
11950b57cec5SDimitry Andric     }
11960b57cec5SDimitry Andric   }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   // Add imports for GOT globals
11990b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
12000b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
12010b57cec5SDimitry Andric     if (WS.isUsedInGOT()) {
12020b57cec5SDimitry Andric       wasm::WasmImport Import;
12030b57cec5SDimitry Andric       if (WS.isFunction())
12040b57cec5SDimitry Andric         Import.Module = "GOT.func";
12050b57cec5SDimitry Andric       else
12060b57cec5SDimitry Andric         Import.Module = "GOT.mem";
12070b57cec5SDimitry Andric       Import.Field = WS.getName();
12080b57cec5SDimitry Andric       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
12090b57cec5SDimitry Andric       Import.Global = {wasm::WASM_TYPE_I32, true};
12100b57cec5SDimitry Andric       Imports.push_back(Import);
12110b57cec5SDimitry Andric       assert(GOTIndices.count(&WS) == 0);
12120b57cec5SDimitry Andric       GOTIndices[&WS] = NumGlobalImports++;
12130b57cec5SDimitry Andric     }
12140b57cec5SDimitry Andric   }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric   // Populate DataSegments and CustomSections, which must be done before
12170b57cec5SDimitry Andric   // populating DataLocations.
12180b57cec5SDimitry Andric   for (MCSection &Sec : Asm) {
12190b57cec5SDimitry Andric     auto &Section = static_cast<MCSectionWasm &>(Sec);
12200b57cec5SDimitry Andric     StringRef SectionName = Section.getSectionName();
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     // .init_array sections are handled specially elsewhere.
12230b57cec5SDimitry Andric     if (SectionName.startswith(".init_array"))
12240b57cec5SDimitry Andric       continue;
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric     // Code is handled separately
12270b57cec5SDimitry Andric     if (Section.getKind().isText())
12280b57cec5SDimitry Andric       continue;
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric     if (Section.isWasmData()) {
12310b57cec5SDimitry Andric       uint32_t SegmentIndex = DataSegments.size();
12320b57cec5SDimitry Andric       DataSize = alignTo(DataSize, Section.getAlignment());
12330b57cec5SDimitry Andric       DataSegments.emplace_back();
12340b57cec5SDimitry Andric       WasmDataSegment &Segment = DataSegments.back();
12350b57cec5SDimitry Andric       Segment.Name = SectionName;
12360b57cec5SDimitry Andric       Segment.InitFlags =
12370b57cec5SDimitry Andric           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
12380b57cec5SDimitry Andric       Segment.Offset = DataSize;
12390b57cec5SDimitry Andric       Segment.Section = &Section;
12400b57cec5SDimitry Andric       addData(Segment.Data, Section);
12410b57cec5SDimitry Andric       Segment.Alignment = Log2_32(Section.getAlignment());
12420b57cec5SDimitry Andric       Segment.LinkerFlags = 0;
12430b57cec5SDimitry Andric       DataSize += Segment.Data.size();
12440b57cec5SDimitry Andric       Section.setSegmentIndex(SegmentIndex);
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric       if (const MCSymbolWasm *C = Section.getGroup()) {
12470b57cec5SDimitry Andric         Comdats[C->getName()].emplace_back(
12480b57cec5SDimitry Andric             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
12490b57cec5SDimitry Andric       }
12500b57cec5SDimitry Andric     } else {
12510b57cec5SDimitry Andric       // Create custom sections
12520b57cec5SDimitry Andric       assert(Sec.getKind().isMetadata());
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric       StringRef Name = SectionName;
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric       // For user-defined custom sections, strip the prefix
12570b57cec5SDimitry Andric       if (Name.startswith(".custom_section."))
12580b57cec5SDimitry Andric         Name = Name.substr(strlen(".custom_section."));
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric       MCSymbol *Begin = Sec.getBeginSymbol();
12610b57cec5SDimitry Andric       if (Begin) {
12620b57cec5SDimitry Andric         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
12630b57cec5SDimitry Andric         if (SectionName != Begin->getName())
12640b57cec5SDimitry Andric           report_fatal_error("section name and begin symbol should match: " +
12650b57cec5SDimitry Andric                              Twine(SectionName));
12660b57cec5SDimitry Andric       }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric       // Separate out the producers and target features sections
12690b57cec5SDimitry Andric       if (Name == "producers") {
12708bcb0991SDimitry Andric         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
12710b57cec5SDimitry Andric         continue;
12720b57cec5SDimitry Andric       }
12730b57cec5SDimitry Andric       if (Name == "target_features") {
12740b57cec5SDimitry Andric         TargetFeaturesSection =
12758bcb0991SDimitry Andric             std::make_unique<WasmCustomSection>(Name, &Section);
12760b57cec5SDimitry Andric         continue;
12770b57cec5SDimitry Andric       }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric       CustomSections.emplace_back(Name, &Section);
12800b57cec5SDimitry Andric     }
12810b57cec5SDimitry Andric   }
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric   // Populate WasmIndices and DataLocations for defined symbols.
12840b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
12850b57cec5SDimitry Andric     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
12860b57cec5SDimitry Andric     // or used in relocations.
12870b57cec5SDimitry Andric     if (S.isTemporary() && S.getName().empty())
12880b57cec5SDimitry Andric       continue;
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
12910b57cec5SDimitry Andric     LLVM_DEBUG(
12920b57cec5SDimitry Andric         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
12930b57cec5SDimitry Andric                << " isDefined=" << S.isDefined() << " isExternal="
12940b57cec5SDimitry Andric                << S.isExternal() << " isTemporary=" << S.isTemporary()
12950b57cec5SDimitry Andric                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
12960b57cec5SDimitry Andric                << " isVariable=" << WS.isVariable() << "\n");
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric     if (WS.isVariable())
12990b57cec5SDimitry Andric       continue;
13000b57cec5SDimitry Andric     if (WS.isComdat() && !WS.isDefined())
13010b57cec5SDimitry Andric       continue;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric     if (WS.isFunction()) {
13040b57cec5SDimitry Andric       unsigned Index;
13050b57cec5SDimitry Andric       if (WS.isDefined()) {
13060b57cec5SDimitry Andric         if (WS.getOffset() != 0)
13070b57cec5SDimitry Andric           report_fatal_error(
13080b57cec5SDimitry Andric               "function sections must contain one function each");
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric         if (WS.getSize() == nullptr)
13110b57cec5SDimitry Andric           report_fatal_error(
13120b57cec5SDimitry Andric               "function symbols must have a size set with .size");
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric         // A definition. Write out the function body.
13150b57cec5SDimitry Andric         Index = NumFunctionImports + Functions.size();
13160b57cec5SDimitry Andric         WasmFunction Func;
13170b57cec5SDimitry Andric         Func.SigIndex = getFunctionType(WS);
13180b57cec5SDimitry Andric         Func.Sym = &WS;
13190b57cec5SDimitry Andric         WasmIndices[&WS] = Index;
13200b57cec5SDimitry Andric         Functions.push_back(Func);
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13230b57cec5SDimitry Andric         if (const MCSymbolWasm *C = Section.getGroup()) {
13240b57cec5SDimitry Andric           Comdats[C->getName()].emplace_back(
13250b57cec5SDimitry Andric               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13260b57cec5SDimitry Andric         }
1327480093f4SDimitry Andric 
1328480093f4SDimitry Andric         if (WS.hasExportName()) {
1329480093f4SDimitry Andric           wasm::WasmExport Export;
1330480093f4SDimitry Andric           Export.Name = WS.getExportName();
1331480093f4SDimitry Andric           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1332480093f4SDimitry Andric           Export.Index = Index;
1333480093f4SDimitry Andric           Exports.push_back(Export);
1334480093f4SDimitry Andric         }
13350b57cec5SDimitry Andric       } else {
13360b57cec5SDimitry Andric         // An import; the index was assigned above.
13370b57cec5SDimitry Andric         Index = WasmIndices.find(&WS)->second;
13380b57cec5SDimitry Andric       }
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric     } else if (WS.isData()) {
13430b57cec5SDimitry Andric       if (!isInSymtab(WS))
13440b57cec5SDimitry Andric         continue;
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric       if (!WS.isDefined()) {
13470b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
13480b57cec5SDimitry Andric                           << "\n");
13490b57cec5SDimitry Andric         continue;
13500b57cec5SDimitry Andric       }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric       if (!WS.getSize())
13530b57cec5SDimitry Andric         report_fatal_error("data symbols must have a size set with .size: " +
13540b57cec5SDimitry Andric                            WS.getName());
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric       int64_t Size = 0;
13570b57cec5SDimitry Andric       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
13580b57cec5SDimitry Andric         report_fatal_error(".size expression must be evaluatable");
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
13618bcb0991SDimitry Andric       if (!DataSection.isWasmData())
13628bcb0991SDimitry Andric         report_fatal_error("data symbols must live in a data section: " +
13638bcb0991SDimitry Andric                            WS.getName());
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric       // For each data symbol, export it in the symtab as a reference to the
13660b57cec5SDimitry Andric       // corresponding Wasm data segment.
13670b57cec5SDimitry Andric       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13680b57cec5SDimitry Andric           DataSection.getSegmentIndex(),
13690b57cec5SDimitry Andric           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13700b57cec5SDimitry Andric           static_cast<uint32_t>(Size)};
13710b57cec5SDimitry Andric       DataLocations[&WS] = Ref;
13720b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric     } else if (WS.isGlobal()) {
13750b57cec5SDimitry Andric       // A "true" Wasm global (currently just __stack_pointer)
13760b57cec5SDimitry Andric       if (WS.isDefined())
13770b57cec5SDimitry Andric         report_fatal_error("don't yet support defined globals");
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric       // An import; the index was assigned above
13800b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> global index: "
13810b57cec5SDimitry Andric                         << WasmIndices.find(&WS)->second << "\n");
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric     } else if (WS.isEvent()) {
13840b57cec5SDimitry Andric       // C++ exception symbol (__cpp_exception)
13850b57cec5SDimitry Andric       unsigned Index;
13860b57cec5SDimitry Andric       if (WS.isDefined()) {
13870b57cec5SDimitry Andric         Index = NumEventImports + Events.size();
13880b57cec5SDimitry Andric         wasm::WasmEventType Event;
13890b57cec5SDimitry Andric         Event.SigIndex = getEventType(WS);
13900b57cec5SDimitry Andric         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
13910b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
13920b57cec5SDimitry Andric         WasmIndices[&WS] = Index;
13930b57cec5SDimitry Andric         Events.push_back(Event);
13940b57cec5SDimitry Andric       } else {
13950b57cec5SDimitry Andric         // An import; the index was assigned above.
13960b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) > 0);
13970b57cec5SDimitry Andric       }
13980b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
13990b57cec5SDimitry Andric                         << "\n");
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric     } else {
14020b57cec5SDimitry Andric       assert(WS.isSection());
14030b57cec5SDimitry Andric     }
14040b57cec5SDimitry Andric   }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
14070b57cec5SDimitry Andric   // process these in a separate pass because we need to have processed the
14080b57cec5SDimitry Andric   // target of the alias before the alias itself and the symbols are not
14090b57cec5SDimitry Andric   // necessarily ordered in this way.
14100b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
14110b57cec5SDimitry Andric     if (!S.isVariable())
14120b57cec5SDimitry Andric       continue;
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric     assert(S.isDefined());
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric     // Find the target symbol of this weak alias and export that index
14170b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
14180b57cec5SDimitry Andric     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
14190b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
14200b57cec5SDimitry Andric                       << "'\n");
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric     if (ResolvedSym->isFunction()) {
14230b57cec5SDimitry Andric       assert(WasmIndices.count(ResolvedSym) > 0);
14240b57cec5SDimitry Andric       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
14250b57cec5SDimitry Andric       assert(WasmIndices.count(&WS) == 0);
14260b57cec5SDimitry Andric       WasmIndices[&WS] = WasmIndex;
14270b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
14280b57cec5SDimitry Andric     } else if (ResolvedSym->isData()) {
14290b57cec5SDimitry Andric       assert(DataLocations.count(ResolvedSym) > 0);
14300b57cec5SDimitry Andric       const wasm::WasmDataReference &Ref =
14310b57cec5SDimitry Andric           DataLocations.find(ResolvedSym)->second;
14320b57cec5SDimitry Andric       DataLocations[&WS] = Ref;
14330b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
14340b57cec5SDimitry Andric     } else {
14350b57cec5SDimitry Andric       report_fatal_error("don't yet support global/event aliases");
14360b57cec5SDimitry Andric     }
14370b57cec5SDimitry Andric   }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   // Finally, populate the symbol table itself, in its "natural" order.
14400b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
14410b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
14420b57cec5SDimitry Andric     if (!isInSymtab(WS)) {
14430b57cec5SDimitry Andric       WS.setIndex(InvalidIndex);
14440b57cec5SDimitry Andric       continue;
14450b57cec5SDimitry Andric     }
14460b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric     uint32_t Flags = 0;
14490b57cec5SDimitry Andric     if (WS.isWeak())
14500b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
14510b57cec5SDimitry Andric     if (WS.isHidden())
14520b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
14530b57cec5SDimitry Andric     if (!WS.isExternal() && WS.isDefined())
14540b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
14550b57cec5SDimitry Andric     if (WS.isUndefined())
14560b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
14578bcb0991SDimitry Andric     if (WS.isNoStrip()) {
14588bcb0991SDimitry Andric       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
14598bcb0991SDimitry Andric       if (isEmscripten()) {
14600b57cec5SDimitry Andric         Flags |= wasm::WASM_SYMBOL_EXPORTED;
14618bcb0991SDimitry Andric       }
14628bcb0991SDimitry Andric     }
1463480093f4SDimitry Andric     if (WS.hasImportName())
14640b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1465480093f4SDimitry Andric     if (WS.hasExportName())
1466480093f4SDimitry Andric       Flags |= wasm::WASM_SYMBOL_EXPORTED;
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric     wasm::WasmSymbolInfo Info;
14690b57cec5SDimitry Andric     Info.Name = WS.getName();
14700b57cec5SDimitry Andric     Info.Kind = WS.getType();
14710b57cec5SDimitry Andric     Info.Flags = Flags;
14720b57cec5SDimitry Andric     if (!WS.isData()) {
14730b57cec5SDimitry Andric       assert(WasmIndices.count(&WS) > 0);
14740b57cec5SDimitry Andric       Info.ElementIndex = WasmIndices.find(&WS)->second;
14750b57cec5SDimitry Andric     } else if (WS.isDefined()) {
14760b57cec5SDimitry Andric       assert(DataLocations.count(&WS) > 0);
14770b57cec5SDimitry Andric       Info.DataRef = DataLocations.find(&WS)->second;
14780b57cec5SDimitry Andric     }
14790b57cec5SDimitry Andric     WS.setIndex(SymbolInfos.size());
14800b57cec5SDimitry Andric     SymbolInfos.emplace_back(Info);
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   {
14840b57cec5SDimitry Andric     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
14850b57cec5SDimitry Andric       // Functions referenced by a relocation need to put in the table.  This is
14860b57cec5SDimitry Andric       // purely to make the object file's provisional values readable, and is
14870b57cec5SDimitry Andric       // ignored by the linker, which re-calculates the relocations itself.
14880b57cec5SDimitry Andric       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
14890b57cec5SDimitry Andric           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
14900b57cec5SDimitry Andric         return;
14910b57cec5SDimitry Andric       assert(Rel.Symbol->isFunction());
14920b57cec5SDimitry Andric       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
14930b57cec5SDimitry Andric       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
14940b57cec5SDimitry Andric       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
14950b57cec5SDimitry Andric       if (TableIndices.try_emplace(&WS, TableIndex).second) {
14960b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
14970b57cec5SDimitry Andric                           << " to table: " << TableIndex << "\n");
14980b57cec5SDimitry Andric         TableElems.push_back(FunctionIndex);
14990b57cec5SDimitry Andric         registerFunctionType(WS);
15000b57cec5SDimitry Andric       }
15010b57cec5SDimitry Andric     };
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
15040b57cec5SDimitry Andric       HandleReloc(RelEntry);
15050b57cec5SDimitry Andric     for (const WasmRelocationEntry &RelEntry : DataRelocations)
15060b57cec5SDimitry Andric       HandleReloc(RelEntry);
15070b57cec5SDimitry Andric   }
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // Translate .init_array section contents into start functions.
15100b57cec5SDimitry Andric   for (const MCSection &S : Asm) {
15110b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSectionWasm &>(S);
15120b57cec5SDimitry Andric     if (WS.getSectionName().startswith(".fini_array"))
15130b57cec5SDimitry Andric       report_fatal_error(".fini_array sections are unsupported");
15140b57cec5SDimitry Andric     if (!WS.getSectionName().startswith(".init_array"))
15150b57cec5SDimitry Andric       continue;
15160b57cec5SDimitry Andric     if (WS.getFragmentList().empty())
15170b57cec5SDimitry Andric       continue;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric     // init_array is expected to contain a single non-empty data fragment
15200b57cec5SDimitry Andric     if (WS.getFragmentList().size() != 3)
15210b57cec5SDimitry Andric       report_fatal_error("only one .init_array section fragment supported");
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric     auto IT = WS.begin();
15240b57cec5SDimitry Andric     const MCFragment &EmptyFrag = *IT;
15250b57cec5SDimitry Andric     if (EmptyFrag.getKind() != MCFragment::FT_Data)
15260b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned");
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric     IT = std::next(IT);
15290b57cec5SDimitry Andric     const MCFragment &AlignFrag = *IT;
15300b57cec5SDimitry Andric     if (AlignFrag.getKind() != MCFragment::FT_Align)
15310b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned");
15320b57cec5SDimitry Andric     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
15330b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned for pointers");
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     const MCFragment &Frag = *std::next(IT);
15360b57cec5SDimitry Andric     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
15370b57cec5SDimitry Andric       report_fatal_error("only data supported in .init_array section");
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric     uint16_t Priority = UINT16_MAX;
15400b57cec5SDimitry Andric     unsigned PrefixLength = strlen(".init_array");
15410b57cec5SDimitry Andric     if (WS.getSectionName().size() > PrefixLength) {
15420b57cec5SDimitry Andric       if (WS.getSectionName()[PrefixLength] != '.')
15430b57cec5SDimitry Andric         report_fatal_error(
15440b57cec5SDimitry Andric             ".init_array section priority should start with '.'");
15450b57cec5SDimitry Andric       if (WS.getSectionName()
15460b57cec5SDimitry Andric               .substr(PrefixLength + 1)
15470b57cec5SDimitry Andric               .getAsInteger(10, Priority))
15480b57cec5SDimitry Andric         report_fatal_error("invalid .init_array section priority");
15490b57cec5SDimitry Andric     }
15500b57cec5SDimitry Andric     const auto &DataFrag = cast<MCDataFragment>(Frag);
15510b57cec5SDimitry Andric     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
15520b57cec5SDimitry Andric     for (const uint8_t *
15530b57cec5SDimitry Andric              P = (const uint8_t *)Contents.data(),
15540b57cec5SDimitry Andric             *End = (const uint8_t *)Contents.data() + Contents.size();
15550b57cec5SDimitry Andric          P != End; ++P) {
15560b57cec5SDimitry Andric       if (*P != 0)
15570b57cec5SDimitry Andric         report_fatal_error("non-symbolic data in .init_array section");
15580b57cec5SDimitry Andric     }
15590b57cec5SDimitry Andric     for (const MCFixup &Fixup : DataFrag.getFixups()) {
15600b57cec5SDimitry Andric       assert(Fixup.getKind() ==
15610b57cec5SDimitry Andric              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
15620b57cec5SDimitry Andric       const MCExpr *Expr = Fixup.getValue();
15630b57cec5SDimitry Andric       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
15640b57cec5SDimitry Andric       if (!SymRef)
15650b57cec5SDimitry Andric         report_fatal_error("fixups in .init_array should be symbol references");
15660b57cec5SDimitry Andric       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
15670b57cec5SDimitry Andric       if (TargetSym.getIndex() == InvalidIndex)
15680b57cec5SDimitry Andric         report_fatal_error("symbols in .init_array should exist in symbtab");
15690b57cec5SDimitry Andric       if (!TargetSym.isFunction())
15700b57cec5SDimitry Andric         report_fatal_error("symbols in .init_array should be for functions");
15710b57cec5SDimitry Andric       InitFuncs.push_back(
15720b57cec5SDimitry Andric           std::make_pair(Priority, TargetSym.getIndex()));
15730b57cec5SDimitry Andric     }
15740b57cec5SDimitry Andric   }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric   // Write out the Wasm header.
15770b57cec5SDimitry Andric   writeHeader(Asm);
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   writeTypeSection(Signatures);
15800b57cec5SDimitry Andric   writeImportSection(Imports, DataSize, TableElems.size());
15810b57cec5SDimitry Andric   writeFunctionSection(Functions);
15820b57cec5SDimitry Andric   // Skip the "table" section; we import the table instead.
15830b57cec5SDimitry Andric   // Skip the "memory" section; we import the memory instead.
15840b57cec5SDimitry Andric   writeEventSection(Events);
15850b57cec5SDimitry Andric   writeExportSection(Exports);
15860b57cec5SDimitry Andric   writeElemSection(TableElems);
15870b57cec5SDimitry Andric   writeDataCountSection();
15880b57cec5SDimitry Andric   writeCodeSection(Asm, Layout, Functions);
15890b57cec5SDimitry Andric   writeDataSection();
15900b57cec5SDimitry Andric   for (auto &CustomSection : CustomSections)
15910b57cec5SDimitry Andric     writeCustomSection(CustomSection, Asm, Layout);
15920b57cec5SDimitry Andric   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15930b57cec5SDimitry Andric   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15940b57cec5SDimitry Andric   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15950b57cec5SDimitry Andric   writeCustomRelocSections();
15960b57cec5SDimitry Andric   if (ProducersSection)
15970b57cec5SDimitry Andric     writeCustomSection(*ProducersSection, Asm, Layout);
15980b57cec5SDimitry Andric   if (TargetFeaturesSection)
15990b57cec5SDimitry Andric     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   // TODO: Translate the .comment section to the output.
16020b57cec5SDimitry Andric   return W.OS.tell() - StartOffset;
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric std::unique_ptr<MCObjectWriter>
16060b57cec5SDimitry Andric llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
16070b57cec5SDimitry Andric                              raw_pwrite_stream &OS) {
16088bcb0991SDimitry Andric   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
16090b57cec5SDimitry Andric }
1610