118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
31d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4318c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
516a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
526a31a0d6SSam Clegg   uint64_t PayloadOffset;
536a31a0d6SSam Clegg   // Where the contents of the section starts.
54d934cb88SDan Gohman   uint64_t ContentsOffset;
556f08c84aSSam Clegg   uint32_t Index;
56d934cb88SDan Gohman };
57d934cb88SDan Gohman 
58da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
59da419bdbSHeejin Ahn // as a DenseMap key.
60da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
61da419bdbSHeejin Ahn struct WasmSignature {
629e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6318c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
649e15f359SSam Clegg 
659e15f359SSam Clegg   // The return types of the function.
669e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
679e15f359SSam Clegg 
689e15f359SSam Clegg   // The parameter types of the function.
699e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
709e15f359SSam Clegg 
71da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
729e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
739e15f359SSam Clegg            Params == Other.Params;
749e15f359SSam Clegg   }
759e15f359SSam Clegg };
769e15f359SSam Clegg 
77da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
78da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
79da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
80da419bdbSHeejin Ahn     WasmSignature Sig;
81da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
82da419bdbSHeejin Ahn     return Sig;
839e15f359SSam Clegg   }
84da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
85da419bdbSHeejin Ahn     WasmSignature Sig;
86da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
87da419bdbSHeejin Ahn     return Sig;
889e15f359SSam Clegg   }
89da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
90da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
91da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
924808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
93da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
944808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
959e15f359SSam Clegg     return Value;
969e15f359SSam Clegg   }
97da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
989e15f359SSam Clegg     return LHS == RHS;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg };
1019e15f359SSam Clegg 
1027c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1037c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1047c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1057c395943SSam Clegg // wasm data segment.
1067c395943SSam Clegg struct WasmDataSegment {
1077c395943SSam Clegg   MCSectionWasm *Section;
108d95ed959SSam Clegg   StringRef Name;
1092e150409SThomas Lively   uint32_t InitFlags;
1107c395943SSam Clegg   uint32_t Offset;
11163ebb813SSam Clegg   uint32_t Alignment;
1122e150409SThomas Lively   uint32_t LinkerFlags;
1137c395943SSam Clegg   SmallVector<char, 4> Data;
1147c395943SSam Clegg };
1157c395943SSam Clegg 
1169e15f359SSam Clegg // A wasm function to be written into the function section.
1179e15f359SSam Clegg struct WasmFunction {
118da419bdbSHeejin Ahn   uint32_t SigIndex;
1199e15f359SSam Clegg   const MCSymbolWasm *Sym;
1209e15f359SSam Clegg };
1219e15f359SSam Clegg 
1229e15f359SSam Clegg // A wasm global to be written into the global section.
1239e15f359SSam Clegg struct WasmGlobal {
1246e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1259e15f359SSam Clegg   uint64_t InitialValue;
1269e15f359SSam Clegg };
1279e15f359SSam Clegg 
128ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
129ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
130ea7caceeSSam Clegg // WasmComdatEntry.
131ea7caceeSSam Clegg struct WasmComdatEntry {
132ea7caceeSSam Clegg   unsigned Kind;
133ea7caceeSSam Clegg   uint32_t Index;
134ea7caceeSSam Clegg };
135ea7caceeSSam Clegg 
1366dc65e91SSam Clegg // Information about a single relocation.
1376dc65e91SSam Clegg struct WasmRelocationEntry {
1386dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1396dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1406dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1416dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
142fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1436dc65e91SSam Clegg 
1446dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1456dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
146fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1476dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1486dc65e91SSam Clegg         FixupSection(FixupSection) {}
1496dc65e91SSam Clegg 
150acd7d2b0SSam Clegg   bool hasAddend() const {
151acd7d2b0SSam Clegg     switch (Type) {
152d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
153d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
1542a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
155d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
156d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
157d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
158acd7d2b0SSam Clegg       return true;
159acd7d2b0SSam Clegg     default:
160acd7d2b0SSam Clegg       return false;
161acd7d2b0SSam Clegg     }
162acd7d2b0SSam Clegg   }
163acd7d2b0SSam Clegg 
1646dc65e91SSam Clegg   void print(raw_ostream &Out) const {
165f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
166f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
167759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1686dc65e91SSam Clegg   }
169b7787fd0SSam Clegg 
170615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
171b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
172b7787fd0SSam Clegg #endif
1736dc65e91SSam Clegg };
1746dc65e91SSam Clegg 
17518c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
17625d8e68bSSam Clegg 
177cfd44a2eSSam Clegg struct WasmCustomSection {
178cfd44a2eSSam Clegg 
1796a31a0d6SSam Clegg   StringRef Name;
1806a31a0d6SSam Clegg   MCSectionWasm *Section;
1816a31a0d6SSam Clegg 
1826a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1836a31a0d6SSam Clegg   uint32_t OutputIndex;
1846a31a0d6SSam Clegg 
1856a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1866a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
18718c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
188cfd44a2eSSam Clegg };
189cfd44a2eSSam Clegg 
1901fb8daa6SSam Clegg #if !defined(NDEBUG)
1917f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
192b7787fd0SSam Clegg   Rel.print(OS);
193b7787fd0SSam Clegg   return OS;
194b7787fd0SSam Clegg }
1951fb8daa6SSam Clegg #endif
196b7787fd0SSam Clegg 
19719e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
19819e8befaSSam Clegg // to allow patching.
19918c56a07SHeejin Ahn static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
20019e8befaSSam Clegg                               uint64_t Offset) {
20119e8befaSSam Clegg   uint8_t Buffer[5];
20219e8befaSSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
20319e8befaSSam Clegg   assert(SizeLen == 5);
20419e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20519e8befaSSam Clegg }
20619e8befaSSam Clegg 
20719e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
20819e8befaSSam Clegg // to allow patching.
20918c56a07SHeejin Ahn static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
21019e8befaSSam Clegg                                uint64_t Offset) {
21119e8befaSSam Clegg   uint8_t Buffer[5];
21219e8befaSSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
21319e8befaSSam Clegg   assert(SizeLen == 5);
21419e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
21519e8befaSSam Clegg }
21619e8befaSSam Clegg 
21719e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
21818c56a07SHeejin Ahn static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
21919e8befaSSam Clegg   uint8_t Buffer[4];
22019e8befaSSam Clegg   support::endian::write32le(Buffer, X);
22119e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
22219e8befaSSam Clegg }
22319e8befaSSam Clegg 
22418eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
225f17b149dSPeter Collingbourne   support::endian::Writer W;
226f17b149dSPeter Collingbourne 
22718eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22818eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22918eafb6cSDan Gohman 
230d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
231d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2326f08c84aSSam Clegg   uint32_t CodeSectionIndex;
233d934cb88SDan Gohman 
234d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
235d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2366f08c84aSSam Clegg   uint32_t DataSectionIndex;
237d934cb88SDan Gohman 
238d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
239acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
240acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
241d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
242d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
243f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
244da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
245da419bdbSHeejin Ahn   // space.
2466c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
247492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2486c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2496c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2506a31a0d6SSam Clegg 
2516a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2526a31a0d6SSam Clegg   // section.
2536a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
254cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
255f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2566a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2576a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2586a31a0d6SSam Clegg       CustomSectionsRelocations;
259acd7d2b0SSam Clegg 
260c0d41195SSam Clegg   // Map from section to defining function symbol.
2616ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2626ccb59b3SSam Clegg 
263da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
264da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2656c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2669f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2677c395943SSam Clegg   unsigned NumGlobalImports = 0;
268da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2697e1c3345SChandler Carruth   uint32_t SectionCount = 0;
270d934cb88SDan Gohman 
27118eafb6cSDan Gohman   // TargetObjectWriter wrappers.
27218eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
27318eafb6cSDan Gohman 
2742322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2752322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
276d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
277d934cb88SDan Gohman 
27818eafb6cSDan Gohman public:
2791301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2801301a878SLang Hames                    raw_pwrite_stream &OS)
28159a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
28218eafb6cSDan Gohman 
2830917c9e4SDan Gohman private:
284acd7d2b0SSam Clegg   void reset() override {
285acd7d2b0SSam Clegg     CodeRelocations.clear();
286acd7d2b0SSam Clegg     DataRelocations.clear();
287acd7d2b0SSam Clegg     TypeIndices.clear();
2886c899ba6SSam Clegg     WasmIndices.clear();
289492f7529SSam Clegg     GOTIndices.clear();
290f9edbe95SSam Clegg     TableIndices.clear();
2916c899ba6SSam Clegg     DataLocations.clear();
292cbda16ebSThomas Lively     CustomSections.clear();
293cbda16ebSThomas Lively     ProducersSection.reset();
294f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2956a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
296da419bdbSHeejin Ahn     SignatureIndices.clear();
297da419bdbSHeejin Ahn     Signatures.clear();
2986c899ba6SSam Clegg     DataSegments.clear();
2996ccb59b3SSam Clegg     SectionFunctions.clear();
3009f3fe42eSSam Clegg     NumFunctionImports = 0;
3017c395943SSam Clegg     NumGlobalImports = 0;
302105bdc25SSam Clegg     MCObjectWriter::reset();
303acd7d2b0SSam Clegg   }
304acd7d2b0SSam Clegg 
30518eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30618eafb6cSDan Gohman 
30718eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30818eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
309ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
31018eafb6cSDan Gohman 
31118eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
31218eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
31318eafb6cSDan Gohman 
314438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3159e15f359SSam Clegg 
316b7787fd0SSam Clegg   void writeString(const StringRef Str) {
317f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
318f17b149dSPeter Collingbourne     W.OS << Str;
319b7787fd0SSam Clegg   }
320b7787fd0SSam Clegg 
321f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3229e15f359SSam Clegg 
323da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3248defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
325f950b24aSSam Clegg                           uint32_t NumElements);
326457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3278defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
328457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
329fef8de66SThomas Lively   void writeDataCountSection();
3309e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
331457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3326c899ba6SSam Clegg   void writeDataSection();
333da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3346f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
335f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
33631a2c809SSam Clegg   void writeLinkingMetaDataSection(
33786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
338ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
339ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
340cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
341cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3426a31a0d6SSam Clegg   void writeCustomRelocSections();
3436a31a0d6SSam Clegg   void
3446a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3456a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
346acd7d2b0SSam Clegg 
3477c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
348acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
349acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
350acd7d2b0SSam Clegg 
351acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3525e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
353da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
35438b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
35538b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
35618eafb6cSDan Gohman };
3579e15f359SSam Clegg 
35818eafb6cSDan Gohman } // end anonymous namespace
35918eafb6cSDan Gohman 
360d934cb88SDan Gohman // Write out a section header and a patchable section size field.
361d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3622322a937SSam Clegg                                     unsigned SectionId) {
363d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
364f17b149dSPeter Collingbourne   W.OS << char(SectionId);
365d934cb88SDan Gohman 
366f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
367d934cb88SDan Gohman 
368d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
369d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
37019e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
371d934cb88SDan Gohman 
372d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
373f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
374f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3756f08c84aSSam Clegg   Section.Index = SectionCount++;
376d934cb88SDan Gohman }
3772322a937SSam Clegg 
3782322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3792322a937SSam Clegg                                           StringRef Name) {
380d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3812322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3826a31a0d6SSam Clegg 
3836a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
384f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3856a31a0d6SSam Clegg 
3862322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3872322a937SSam Clegg   writeString(Name);
3886a31a0d6SSam Clegg 
3896a31a0d6SSam Clegg   // The position where the custom section starts.
390f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
391d934cb88SDan Gohman }
392d934cb88SDan Gohman 
393d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
394d934cb88SDan Gohman // section size field at the start of the section.
395d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
396c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
397c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
398c0affde8SSam Clegg   // Simply skip this patching in that case.
399c0affde8SSam Clegg   if (!Size)
400c0affde8SSam Clegg     return;
401c0affde8SSam Clegg 
402c0affde8SSam Clegg   Size -= Section.PayloadOffset;
403d934cb88SDan Gohman   if (uint32_t(Size) != Size)
404d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
405d934cb88SDan Gohman 
406d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
407d934cb88SDan Gohman 
408d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
409d934cb88SDan Gohman   // the section id byte.
41018c56a07SHeejin Ahn   writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
411f17b149dSPeter Collingbourne                     Section.SizeOffset);
412d934cb88SDan Gohman }
413d934cb88SDan Gohman 
41418eafb6cSDan Gohman // Emit the Wasm header.
41518eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
416f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
417f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
41818eafb6cSDan Gohman }
41918eafb6cSDan Gohman 
42018eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
42118eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4226ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4236ccb59b3SSam Clegg   // in recordRelocation.
4246ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4256ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4266ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4276ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4286ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4296ccb59b3SSam Clegg       if (!Pair.second)
4306ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4316ccb59b3SSam Clegg                            Sec.getSectionName());
4326ccb59b3SSam Clegg     }
4336ccb59b3SSam Clegg   }
43418eafb6cSDan Gohman }
43518eafb6cSDan Gohman 
43618eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
43718eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
43818eafb6cSDan Gohman                                         const MCFragment *Fragment,
43918eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
440ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
441ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
442ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
443ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
444fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
445d934cb88SDan Gohman   uint64_t C = Target.getConstant();
446d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
447d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
448d934cb88SDan Gohman 
449bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
450bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
451bafe6902SSam Clegg     return;
452bafe6902SSam Clegg 
453d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
454d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
455d934cb88SDan Gohman            "Should not have constructed this");
456d934cb88SDan Gohman 
457d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
458d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
459d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
460d934cb88SDan Gohman 
461d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
462d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
463d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
464d934cb88SDan Gohman     if (IsPCRel) {
465d934cb88SDan Gohman       Ctx.reportError(
466d934cb88SDan Gohman           Fixup.getLoc(),
467d934cb88SDan Gohman           "No relocation available to represent this relative expression");
468d934cb88SDan Gohman       return;
469d934cb88SDan Gohman     }
470d934cb88SDan Gohman 
471d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
472d934cb88SDan Gohman 
473d934cb88SDan Gohman     if (SymB.isUndefined()) {
474d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
475d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
476d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
477d934cb88SDan Gohman       return;
478d934cb88SDan Gohman     }
479d934cb88SDan Gohman 
480d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
481d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
482d934cb88SDan Gohman     if (&SecB != &FixupSection) {
483d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
484d934cb88SDan Gohman                       "Cannot represent a difference across sections");
485d934cb88SDan Gohman       return;
486d934cb88SDan Gohman     }
487d934cb88SDan Gohman 
488d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
489d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
490d934cb88SDan Gohman     IsPCRel = true;
491d934cb88SDan Gohman     C -= K;
492d934cb88SDan Gohman   }
493d934cb88SDan Gohman 
494d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
495d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
496d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
497d934cb88SDan Gohman 
498d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
499d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
5006ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
5016ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5026ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
503d934cb88SDan Gohman   }
504d934cb88SDan Gohman 
505d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
506d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
507d934cb88SDan Gohman   // be negative and don't wrap.
508d934cb88SDan Gohman   FixedValue = 0;
509d934cb88SDan Gohman 
510a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
511ae03c1e7SSam Clegg   assert(!IsPCRel);
5129d24fb7fSSam Clegg   assert(SymA);
5139d24fb7fSSam Clegg 
5144d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5154d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5164d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
517d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
518d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
5194d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5204d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5214d57fbd0SSam Clegg                          "only supported in metadata sections");
5224d57fbd0SSam Clegg 
5234d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5244d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5254d57fbd0SSam Clegg     if (SecA.getKind().isText())
5266ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
5274d57fbd0SSam Clegg     else
5284d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5294d57fbd0SSam Clegg     if (!SectionSymbol)
5304d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5314d57fbd0SSam Clegg 
5324d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5334d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5344d57fbd0SSam Clegg   }
5354d57fbd0SSam Clegg 
536d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5374d57fbd0SSam Clegg   // against a named symbol.
538d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5394d57fbd0SSam Clegg     if (SymA->getName().empty())
5404d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5414d57fbd0SSam Clegg                          "supported by wasm");
5424d57fbd0SSam Clegg 
5434d57fbd0SSam Clegg     SymA->setUsedInReloc();
5444d57fbd0SSam Clegg   }
545ae03c1e7SSam Clegg 
546492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
547492f7529SSam Clegg     SymA->setUsedInGOT();
548492f7529SSam Clegg 
549d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
550d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
551d934cb88SDan Gohman 
5526a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
553d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5546a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
55512fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5566a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5576a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5586a31a0d6SSam Clegg   } else {
55912fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
560d934cb88SDan Gohman   }
5616a31a0d6SSam Clegg }
562d934cb88SDan Gohman 
56318c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
564ffba00bdSSam Clegg   const MCSymbolWasm* Ret = &Symbol;
565ffba00bdSSam Clegg   while (Ret->isVariable()) {
566ffba00bdSSam Clegg     const MCExpr *Expr = Ret->getVariableValue();
567aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
568ffba00bdSSam Clegg     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
569aff1c4dfSSam Clegg   }
570ffba00bdSSam Clegg   return Ret;
571aff1c4dfSSam Clegg }
572aff1c4dfSSam Clegg 
573d934cb88SDan Gohman // Compute a value to write into the code at the location covered
57460ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57560ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57660ec3034SSam Clegg // useable.
5777c395943SSam Clegg uint32_t
5787c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
579492f7529SSam Clegg   if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
580492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
581492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
582492f7529SSam Clegg   }
583492f7529SSam Clegg 
58460ec3034SSam Clegg   switch (RelEntry.Type) {
5852a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
586d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
587d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_I32: {
588f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
58918c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
590f9edbe95SSam Clegg     assert(Sym->isFunction());
591f9edbe95SSam Clegg     return TableIndices[Sym];
592f9edbe95SSam Clegg   }
593d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5946c899ba6SSam Clegg     // Provisional value is same as the index
59560ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
596d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
597d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
598d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
599da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
600492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6016c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
602d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
603d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
6046a31a0d6SSam Clegg     const auto &Section =
6056a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6066a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6076a31a0d6SSam Clegg   }
608d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
609d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I32:
6102a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
611d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_SLEB: {
612f9edbe95SSam Clegg     // Provisional value is address of the global
61318c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
614270ed1b3SSam Clegg     // For undefined symbols, use zero
615cd65f698SSam Clegg     if (!Sym->isDefined())
616270ed1b3SSam Clegg       return 0;
6176c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6186c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
619d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6206c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
62160ec3034SSam Clegg   }
62260ec3034SSam Clegg   default:
62360ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
62460ec3034SSam Clegg   }
625d934cb88SDan Gohman }
626d934cb88SDan Gohman 
627759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62863ebb813SSam Clegg                     MCSectionWasm &DataSection) {
629d34e60caSNicola Zaghen   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
630759631c7SSam Clegg 
63163ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63263ebb813SSam Clegg 
633759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
634759631c7SSam Clegg     if (Frag.hasInstructions())
635759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
636759631c7SSam Clegg 
637759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
638759631c7SSam Clegg       if (Align->getValueSize() != 1)
639759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
640759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
641759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
642f208f631SHeejin Ahn       uint64_t Size =
643f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
644f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
645759631c7SSam Clegg       DataBytes.resize(Size, Value);
646759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
647588fad4dSNirav Dave       int64_t NumValues;
648588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
649d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
650588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
651588fad4dSNirav Dave                        Fill->getValue());
65224faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
65324faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
65424faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
655759631c7SSam Clegg     } else {
656759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
657759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
658759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
659759631c7SSam Clegg     }
660759631c7SSam Clegg   }
661759631c7SSam Clegg 
662d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
663759631c7SSam Clegg }
664759631c7SSam Clegg 
66560ec3034SSam Clegg uint32_t
66660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
667d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
668b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
669b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
670b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
671acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
672acd7d2b0SSam Clegg   }
67360ec3034SSam Clegg 
67425d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
675acd7d2b0SSam Clegg }
676acd7d2b0SSam Clegg 
677d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
678d934cb88SDan Gohman // directly.
679acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
680acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
681f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
682d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
683d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
684d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
685d934cb88SDan Gohman                       RelEntry.Offset;
686d934cb88SDan Gohman 
687d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68860ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68960ec3034SSam Clegg 
690acd7d2b0SSam Clegg     switch (RelEntry.Type) {
691d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
692d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
693d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
694d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
695d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
69618c56a07SHeejin Ahn       writePatchableLEB(Stream, Value, Offset);
697d934cb88SDan Gohman       break;
698d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
699d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
700d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
701d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
70218c56a07SHeejin Ahn       writeI32(Stream, Value, Offset);
703d934cb88SDan Gohman       break;
704d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7052a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
706d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7072a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
70818c56a07SHeejin Ahn       writePatchableSLEB(Stream, Value, Offset);
70960ec3034SSam Clegg       break;
710d934cb88SDan Gohman     default:
7119d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
712d934cb88SDan Gohman     }
713d934cb88SDan Gohman   }
71418eafb6cSDan Gohman }
71518eafb6cSDan Gohman 
716da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
717da419bdbSHeejin Ahn   if (Signatures.empty())
7189e15f359SSam Clegg     return;
7199e15f359SSam Clegg 
7209e15f359SSam Clegg   SectionBookkeeping Section;
7219e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7229e15f359SSam Clegg 
723da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
7249e15f359SSam Clegg 
725da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
726f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
727da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
728da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7299e15f359SSam Clegg       writeValueType(Ty);
730da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
731da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7329e15f359SSam Clegg       writeValueType(Ty);
7339e15f359SSam Clegg   }
7349e15f359SSam Clegg 
7359e15f359SSam Clegg   endSection(Section);
7369e15f359SSam Clegg }
7379e15f359SSam Clegg 
7388defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
739f950b24aSSam Clegg                                           uint32_t DataSize,
740f950b24aSSam Clegg                                           uint32_t NumElements) {
7419e15f359SSam Clegg   if (Imports.empty())
7429e15f359SSam Clegg     return;
7439e15f359SSam Clegg 
744f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
745f950b24aSSam Clegg 
7469e15f359SSam Clegg   SectionBookkeeping Section;
7479e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7489e15f359SSam Clegg 
749f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7508defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7518defa952SSam Clegg     writeString(Import.Module);
7528defa952SSam Clegg     writeString(Import.Field);
753f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7549e15f359SSam Clegg 
7559e15f359SSam Clegg     switch (Import.Kind) {
7569e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
757f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7589e15f359SSam Clegg       break;
7599e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
760f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
761f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7629e15f359SSam Clegg       break;
763f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
764f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
765f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
766f950b24aSSam Clegg       break;
767f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
768f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
769f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
770f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
771f950b24aSSam Clegg       break;
772da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
773da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
774da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
775da419bdbSHeejin Ahn       break;
7769e15f359SSam Clegg     default:
7779e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7789e15f359SSam Clegg     }
7799e15f359SSam Clegg   }
7809e15f359SSam Clegg 
7819e15f359SSam Clegg   endSection(Section);
7829e15f359SSam Clegg }
7839e15f359SSam Clegg 
784457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7859e15f359SSam Clegg   if (Functions.empty())
7869e15f359SSam Clegg     return;
7879e15f359SSam Clegg 
7889e15f359SSam Clegg   SectionBookkeeping Section;
7899e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7909e15f359SSam Clegg 
791f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7929e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
793da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7949e15f359SSam Clegg 
7959e15f359SSam Clegg   endSection(Section);
7969e15f359SSam Clegg }
7979e15f359SSam Clegg 
798da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
799da419bdbSHeejin Ahn   if (Events.empty())
800da419bdbSHeejin Ahn     return;
801da419bdbSHeejin Ahn 
802da419bdbSHeejin Ahn   SectionBookkeeping Section;
803da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
804da419bdbSHeejin Ahn 
805da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
806da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
807da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
808da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
809da419bdbSHeejin Ahn   }
810da419bdbSHeejin Ahn 
811da419bdbSHeejin Ahn   endSection(Section);
812da419bdbSHeejin Ahn }
813da419bdbSHeejin Ahn 
8148defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8159e15f359SSam Clegg   if (Exports.empty())
8169e15f359SSam Clegg     return;
8179e15f359SSam Clegg 
8189e15f359SSam Clegg   SectionBookkeeping Section;
8199e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8209e15f359SSam Clegg 
821f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
8228defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8238defa952SSam Clegg     writeString(Export.Name);
824f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
825f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
8269e15f359SSam Clegg   }
8279e15f359SSam Clegg 
8289e15f359SSam Clegg   endSection(Section);
8299e15f359SSam Clegg }
8309e15f359SSam Clegg 
831457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8329e15f359SSam Clegg   if (TableElems.empty())
8339e15f359SSam Clegg     return;
8349e15f359SSam Clegg 
8359e15f359SSam Clegg   SectionBookkeeping Section;
8369e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8379e15f359SSam Clegg 
838f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
839f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8409e15f359SSam Clegg 
8419e15f359SSam Clegg   // init expr for starting offset
842f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
84318c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
844f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8459e15f359SSam Clegg 
846f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8479e15f359SSam Clegg   for (uint32_t Elem : TableElems)
848f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8499e15f359SSam Clegg 
8509e15f359SSam Clegg   endSection(Section);
8519e15f359SSam Clegg }
8529e15f359SSam Clegg 
853fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
854fef8de66SThomas Lively   if (DataSegments.empty())
855fef8de66SThomas Lively     return;
856fef8de66SThomas Lively 
857fef8de66SThomas Lively   SectionBookkeeping Section;
858fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
859fef8de66SThomas Lively   encodeULEB128(DataSegments.size(), W.OS);
860fef8de66SThomas Lively   endSection(Section);
861fef8de66SThomas Lively }
862fef8de66SThomas Lively 
863457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
864457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
865457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8669e15f359SSam Clegg   if (Functions.empty())
8679e15f359SSam Clegg     return;
8689e15f359SSam Clegg 
8699e15f359SSam Clegg   SectionBookkeeping Section;
8709e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8716f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8729e15f359SSam Clegg 
873f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
8749e15f359SSam Clegg 
8759e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
876fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8779e15f359SSam Clegg 
8789e15f359SSam Clegg     int64_t Size = 0;
8799e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8809e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8819e15f359SSam Clegg 
882f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
883f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
884f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8859e15f359SSam Clegg   }
8869e15f359SSam Clegg 
8879e15f359SSam Clegg   // Apply fixups.
888acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   endSection(Section);
8919e15f359SSam Clegg }
8929e15f359SSam Clegg 
8936c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8946c899ba6SSam Clegg   if (DataSegments.empty())
8957c395943SSam Clegg     return;
8969e15f359SSam Clegg 
8979e15f359SSam Clegg   SectionBookkeeping Section;
8989e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8996f08c84aSSam Clegg   DataSectionIndex = Section.Index;
9009e15f359SSam Clegg 
901f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
9027c395943SSam Clegg 
9036c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9042e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
9052e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
906f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
9072e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
908f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
909f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
910f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
9112e150409SThomas Lively     }
912f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
913f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
914f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
9157c395943SSam Clegg   }
9169e15f359SSam Clegg 
9179e15f359SSam Clegg   // Apply fixups.
9187c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
9199e15f359SSam Clegg 
9209e15f359SSam Clegg   endSection(Section);
9219e15f359SSam Clegg }
9229e15f359SSam Clegg 
9236f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9246f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
925f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9269e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9279e15f359SSam Clegg   // for descriptions of the reloc sections.
9289e15f359SSam Clegg 
929f77dc2a8SSam Clegg   if (Relocs.empty())
9309e15f359SSam Clegg     return;
9319e15f359SSam Clegg 
932f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
933f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
934f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
935f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
936f77dc2a8SSam Clegg   // not the sections order.
937*efd94c56SFangrui Song   llvm::stable_sort(
938*efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
939f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
940f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
941f77dc2a8SSam Clegg       });
942f77dc2a8SSam Clegg 
9439e15f359SSam Clegg   SectionBookkeeping Section;
9446f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9459e15f359SSam Clegg 
946f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
947f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
948f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
949f208f631SHeejin Ahn     uint64_t Offset =
950f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9516f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9529e15f359SSam Clegg 
953f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
954f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
955f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9566f08c84aSSam Clegg     if (RelEntry.hasAddend())
957f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9589e15f359SSam Clegg   }
9599e15f359SSam Clegg 
9609e15f359SSam Clegg   endSection(Section);
9619e15f359SSam Clegg }
9629e15f359SSam Clegg 
9636a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9646a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9656a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9666a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9676a31a0d6SSam Clegg   }
9686a31a0d6SSam Clegg }
9696a31a0d6SSam Clegg 
9709e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
97186b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
972ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
973ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9749e15f359SSam Clegg   SectionBookkeeping Section;
9752322a937SSam Clegg   startCustomSection(Section, "linking");
976f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9779e15f359SSam Clegg 
9786bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9796c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9806c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
981f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
9826c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
983f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
984f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
9856c899ba6SSam Clegg       switch (Sym.Kind) {
9866c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9876c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
988da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
989f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
99029874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
99129874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
9926c899ba6SSam Clegg           writeString(Sym.Name);
9936c899ba6SSam Clegg         break;
9946c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9956c899ba6SSam Clegg         writeString(Sym.Name);
9966c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
997f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
998f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
999f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
10006c899ba6SSam Clegg         }
10016c899ba6SSam Clegg         break;
10026a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10036a31a0d6SSam Clegg         const uint32_t SectionIndex =
10046a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
1005f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
10066a31a0d6SSam Clegg         break;
10076a31a0d6SSam Clegg       }
10086c899ba6SSam Clegg       default:
10096c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10106c899ba6SSam Clegg       }
1011b7787fd0SSam Clegg     }
1012b7787fd0SSam Clegg     endSection(SubSection);
1013b7787fd0SSam Clegg   }
10149e15f359SSam Clegg 
10156c899ba6SSam Clegg   if (DataSegments.size()) {
101663ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1017f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
10186c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1019d95ed959SSam Clegg       writeString(Segment.Name);
1020f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
10212e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
102263ebb813SSam Clegg     }
1023d95ed959SSam Clegg     endSection(SubSection);
1024d95ed959SSam Clegg   }
1025d95ed959SSam Clegg 
1026bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1027bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1028f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
1029bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1030f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
1031f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
1032bafe6902SSam Clegg     }
1033bafe6902SSam Clegg     endSection(SubSection);
1034bafe6902SSam Clegg   }
1035bafe6902SSam Clegg 
1036ea7caceeSSam Clegg   if (Comdats.size()) {
1037ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1038f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1039ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1040ea7caceeSSam Clegg       writeString(C.first);
1041f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1042f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1043ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1044f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1045f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1046ea7caceeSSam Clegg       }
1047ea7caceeSSam Clegg     }
1048ea7caceeSSam Clegg     endSection(SubSection);
1049ea7caceeSSam Clegg   }
1050ea7caceeSSam Clegg 
10519e15f359SSam Clegg   endSection(Section);
10529e15f359SSam Clegg }
10539e15f359SSam Clegg 
1054cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1055cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10566a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1057cfd44a2eSSam Clegg   SectionBookkeeping Section;
10586a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10592322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10606a31a0d6SSam Clegg 
1061f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1062f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
10636a31a0d6SSam Clegg 
10646a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10656a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
10666a31a0d6SSam Clegg 
1067cfd44a2eSSam Clegg   endSection(Section);
10686a31a0d6SSam Clegg 
10696a31a0d6SSam Clegg   // Apply fixups.
10704d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10714d57fbd0SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10726a31a0d6SSam Clegg }
10736a31a0d6SSam Clegg 
10745e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10755e3d33a7SSam Clegg   assert(Symbol.isFunction());
10765e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10775e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10785e3d33a7SSam Clegg }
10795e3d33a7SSam Clegg 
1080da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1081da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1082da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1083da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1084da419bdbSHeejin Ahn }
1085da419bdbSHeejin Ahn 
108638b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10875e3d33a7SSam Clegg   assert(Symbol.isFunction());
10885e3d33a7SSam Clegg 
1089da419bdbSHeejin Ahn   WasmSignature S;
109018c56a07SHeejin Ahn   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
109177a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
1092da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1093da419bdbSHeejin Ahn     S.Params = Sig->Params;
109477a7a380SDerek Schuff   }
10955e3d33a7SSam Clegg 
1096da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10975e3d33a7SSam Clegg   if (Pair.second)
1098da419bdbSHeejin Ahn     Signatures.push_back(S);
10995e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11005e3d33a7SSam Clegg 
1101d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1102d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1103d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11045e3d33a7SSam Clegg }
11055e3d33a7SSam Clegg 
110638b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1107da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1108da419bdbSHeejin Ahn 
1109da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1110da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1111da419bdbSHeejin Ahn   WasmSignature S;
1112da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1113da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1114da419bdbSHeejin Ahn     S.Params = Sig->Params;
1115da419bdbSHeejin Ahn   }
1116da419bdbSHeejin Ahn 
1117da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1118da419bdbSHeejin Ahn   if (Pair.second)
1119da419bdbSHeejin Ahn     Signatures.push_back(S);
1120da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1121da419bdbSHeejin Ahn 
1122da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1123da419bdbSHeejin Ahn                     << "\n");
1124da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1125da419bdbSHeejin Ahn }
1126da419bdbSHeejin Ahn 
11274d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11284d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
11294d57fbd0SSam Clegg     return true;
11304d57fbd0SSam Clegg 
11314d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11324d57fbd0SSam Clegg     return false;
11334d57fbd0SSam Clegg 
11344d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
11354d57fbd0SSam Clegg     return false;
11364d57fbd0SSam Clegg 
11374d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
11384d57fbd0SSam Clegg     return false;
11394d57fbd0SSam Clegg 
11404d57fbd0SSam Clegg   if (Sym.isSection())
11414d57fbd0SSam Clegg     return false;
11424d57fbd0SSam Clegg 
11434d57fbd0SSam Clegg   return true;
11444d57fbd0SSam Clegg }
11454d57fbd0SSam Clegg 
1146438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
114718eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1148438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1149438390faSPeter Collingbourne 
1150d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1151d934cb88SDan Gohman 
1152d934cb88SDan Gohman   // Collect information from the available symbols.
1153d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1154d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11558defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11568defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1157da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11586c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1159bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1160ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11617c395943SSam Clegg   uint32_t DataSize = 0;
1162d934cb88SDan Gohman 
1163f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1164f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1165f950b24aSSam Clegg   // it if there are no loads or stores.
11668defa952SSam Clegg   wasm::WasmImport MemImport;
11671ed3a046SSam Clegg   MemImport.Module = "env";
11681ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1169f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1170f950b24aSSam Clegg   Imports.push_back(MemImport);
1171f950b24aSSam Clegg 
1172f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1173f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1174f950b24aSSam Clegg   // it if there are no indirect calls.
11758defa952SSam Clegg   wasm::WasmImport TableImport;
11761ed3a046SSam Clegg   TableImport.Module = "env";
11771ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1178f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11796a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1180f950b24aSSam Clegg   Imports.push_back(TableImport);
1181f950b24aSSam Clegg 
1182da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1183586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1184586320c0SNicholas Wilson   // symbols.
118532ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
118632ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
118732ce5ca0SDan Gohman 
118832ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11899f3fe42eSSam Clegg     // (because wasm always needs a type signature).
119032ce5ca0SDan Gohman     if (WS.isFunction())
119132ce5ca0SDan Gohman       registerFunctionType(WS);
119232ce5ca0SDan Gohman 
1193da419bdbSHeejin Ahn     if (WS.isEvent())
1194da419bdbSHeejin Ahn       registerEventType(WS);
1195da419bdbSHeejin Ahn 
119632ce5ca0SDan Gohman     if (WS.isTemporary())
119732ce5ca0SDan Gohman       continue;
119832ce5ca0SDan Gohman 
119932ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12006c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12016c899ba6SSam Clegg       if (WS.isFunction()) {
12028defa952SSam Clegg         wasm::WasmImport Import;
1203f726e445SDan Gohman         Import.Module = WS.getImportModule();
1204f726e445SDan Gohman         Import.Field = WS.getImportName();
120532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12068defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12076c899ba6SSam Clegg         Imports.push_back(Import);
1208492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12096c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12106c899ba6SSam Clegg       } else if (WS.isGlobal()) {
121115f349f7SNicholas Wilson         if (WS.isWeak())
121215f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
121315f349f7SNicholas Wilson 
12146c899ba6SSam Clegg         wasm::WasmImport Import;
1215f726e445SDan Gohman         Import.Field = WS.getImportName();
121632ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1217492f7529SSam Clegg         Import.Module = WS.getImportModule();
12186c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12196c899ba6SSam Clegg         Imports.push_back(Import);
1220492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12216c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1222da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1223da419bdbSHeejin Ahn         if (WS.isWeak())
1224da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1225da419bdbSHeejin Ahn 
1226da419bdbSHeejin Ahn         wasm::WasmImport Import;
1227f726e445SDan Gohman         Import.Module = WS.getImportModule();
1228f726e445SDan Gohman         Import.Field = WS.getImportName();
1229da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1230da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1231da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1232da419bdbSHeejin Ahn         Imports.push_back(Import);
1233492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1234da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
123532ce5ca0SDan Gohman       }
123632ce5ca0SDan Gohman     }
123732ce5ca0SDan Gohman   }
123832ce5ca0SDan Gohman 
1239492f7529SSam Clegg   // Add imports for GOT globals
1240492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1241492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1242492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1243492f7529SSam Clegg       wasm::WasmImport Import;
1244492f7529SSam Clegg       if (WS.isFunction())
1245492f7529SSam Clegg         Import.Module = "GOT.func";
1246492f7529SSam Clegg       else
1247492f7529SSam Clegg         Import.Module = "GOT.mem";
1248492f7529SSam Clegg       Import.Field = WS.getName();
1249492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1250492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1251492f7529SSam Clegg       Imports.push_back(Import);
1252492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1253492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1254492f7529SSam Clegg     }
1255492f7529SSam Clegg   }
1256492f7529SSam Clegg 
12574d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12584d57fbd0SSam Clegg   // populating DataLocations.
1259759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1260759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
12614d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1262759631c7SSam Clegg 
1263bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
12644d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1265bafe6902SSam Clegg       continue;
1266bafe6902SSam Clegg 
12674d57fbd0SSam Clegg     // Code is handled separately
12684d57fbd0SSam Clegg     if (Section.getKind().isText())
12694d57fbd0SSam Clegg       continue;
12704d57fbd0SSam Clegg 
12714d57fbd0SSam Clegg     if (Section.isWasmData()) {
1272329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1273759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1274759631c7SSam Clegg       DataSegments.emplace_back();
1275759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
12764d57fbd0SSam Clegg       Segment.Name = SectionName;
12779b49f36aSSimon Pilgrim       Segment.InitFlags =
12789b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1279759631c7SSam Clegg       Segment.Offset = DataSize;
1280759631c7SSam Clegg       Segment.Section = &Section;
128163ebb813SSam Clegg       addData(Segment.Data, Section);
128256c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
12832e150409SThomas Lively       Segment.LinkerFlags = 0;
1284759631c7SSam Clegg       DataSize += Segment.Data.size();
12856c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1286ea7caceeSSam Clegg 
1287ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1288ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1289329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1290ea7caceeSSam Clegg       }
12914d57fbd0SSam Clegg     } else {
12924d57fbd0SSam Clegg       // Create custom sections
12934d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
12944d57fbd0SSam Clegg 
12954d57fbd0SSam Clegg       StringRef Name = SectionName;
12964d57fbd0SSam Clegg 
12974d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12984d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12994d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13004d57fbd0SSam Clegg 
13014d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1302fb807d4dSSam Clegg       if (Begin) {
13034d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1304b210c64bSSam Clegg         if (SectionName != Begin->getName())
1305fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1306b210c64bSSam Clegg                              Twine(SectionName));
1307fb807d4dSSam Clegg       }
1308cbda16ebSThomas Lively 
1309f6f4f843SThomas Lively       // Separate out the producers and target features sections
1310cbda16ebSThomas Lively       if (Name == "producers") {
1311cbda16ebSThomas Lively         ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1312cbda16ebSThomas Lively         continue;
1313cbda16ebSThomas Lively       }
1314f6f4f843SThomas Lively       if (Name == "target_features") {
1315f6f4f843SThomas Lively         TargetFeaturesSection =
1316f6f4f843SThomas Lively             llvm::make_unique<WasmCustomSection>(Name, &Section);
1317f6f4f843SThomas Lively         continue;
1318f6f4f843SThomas Lively       }
1319cbda16ebSThomas Lively 
13204d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1321759631c7SSam Clegg     }
13226a31a0d6SSam Clegg   }
13236a31a0d6SSam Clegg 
1324586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1325d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1326d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1327d934cb88SDan Gohman     // or used in relocations.
1328d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1329d934cb88SDan Gohman       continue;
1330b7787fd0SSam Clegg 
1331d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1332d34e60caSNicola Zaghen     LLVM_DEBUG(
1333d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1334d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1335d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1336d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1337b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1338b7787fd0SSam Clegg 
13395e3d33a7SSam Clegg     if (WS.isVariable())
13405e3d33a7SSam Clegg       continue;
13416c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13426c899ba6SSam Clegg       continue;
1343b7787fd0SSam Clegg 
1344d934cb88SDan Gohman     if (WS.isFunction()) {
13456c899ba6SSam Clegg       unsigned Index;
1346cd65f698SSam Clegg       if (WS.isDefined()) {
1347b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1348b7787fd0SSam Clegg           report_fatal_error(
1349b7787fd0SSam Clegg               "function sections must contain one function each");
1350b7787fd0SSam Clegg 
135118c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1352b7787fd0SSam Clegg           report_fatal_error(
1353b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1354b7787fd0SSam Clegg 
13556c899ba6SSam Clegg         // A definition. Write out the function body.
13569f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1357d934cb88SDan Gohman         WasmFunction Func;
1358da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1359d934cb88SDan Gohman         Func.Sym = &WS;
13606c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1361d934cb88SDan Gohman         Functions.push_back(Func);
13626c899ba6SSam Clegg 
13636c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13646c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
13656c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
13666c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13676c899ba6SSam Clegg         }
1368d934cb88SDan Gohman       } else {
1369d934cb88SDan Gohman         // An import; the index was assigned above.
13706c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1371d934cb88SDan Gohman       }
1372d934cb88SDan Gohman 
1373d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1374da419bdbSHeejin Ahn 
13756c899ba6SSam Clegg     } else if (WS.isData()) {
1376f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1377c38e947eSSam Clegg         continue;
1378c38e947eSSam Clegg 
13796c899ba6SSam Clegg       if (!WS.isDefined()) {
1380d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1381d34e60caSNicola Zaghen                           << "\n");
1382fe6414b0SSam Clegg         continue;
13836c899ba6SSam Clegg       }
1384fe6414b0SSam Clegg 
1385d934cb88SDan Gohman       if (!WS.getSize())
1386c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1387c38e947eSSam Clegg                            WS.getName());
1388d934cb88SDan Gohman 
1389d934cb88SDan Gohman       int64_t Size = 0;
1390d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1391d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1392d934cb88SDan Gohman 
1393759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1394ea7caceeSSam Clegg       assert(DataSection.isWasmData());
13957c395943SSam Clegg 
13966c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13976c899ba6SSam Clegg       // corresponding Wasm data segment.
13986c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13996c899ba6SSam Clegg           DataSection.getSegmentIndex(),
14006c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
14016c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
14026c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1403d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1404da419bdbSHeejin Ahn 
1405a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14066c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1407545932beSEric Christopher       if (WS.isDefined())
14086c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
14096c899ba6SSam Clegg 
1410545932beSEric Christopher       // An import; the index was assigned above
1411d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1412d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1413da419bdbSHeejin Ahn 
1414da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1415da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1416da419bdbSHeejin Ahn       unsigned Index;
1417da419bdbSHeejin Ahn       if (WS.isDefined()) {
1418da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1419da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1420da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1421da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1422492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1423da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1424da419bdbSHeejin Ahn         Events.push_back(Event);
1425da419bdbSHeejin Ahn       } else {
1426da419bdbSHeejin Ahn         // An import; the index was assigned above.
1427492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1428da419bdbSHeejin Ahn         Index = WasmIndices.find(&WS)->second;
1429da419bdbSHeejin Ahn       }
1430da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1431da419bdbSHeejin Ahn                         << "\n");
1432da419bdbSHeejin Ahn 
1433a165f2d6SSam Clegg     } else {
1434a165f2d6SSam Clegg       assert(WS.isSection());
1435d934cb88SDan Gohman     }
1436d934cb88SDan Gohman   }
1437d934cb88SDan Gohman 
1438586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1439586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1440586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1441586320c0SNicholas Wilson   // necessarily ordered in this way.
1442b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1443b7787fd0SSam Clegg     if (!S.isVariable())
1444b7787fd0SSam Clegg       continue;
144531a2c809SSam Clegg 
1446cd65f698SSam Clegg     assert(S.isDefined());
1447b7787fd0SSam Clegg 
14485e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1449aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
145018c56a07SHeejin Ahn     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1451d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1452d34e60caSNicola Zaghen                       << "'\n");
1453b7787fd0SSam Clegg 
1454ffba00bdSSam Clegg     if (ResolvedSym->isFunction()) {
14556c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
14566c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1457492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
14586c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1459d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1460ffba00bdSSam Clegg     } else if (ResolvedSym->isData()) {
14616c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
14626c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
14636c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
14646c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1465d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
14666c899ba6SSam Clegg     } else {
1467da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
14686c899ba6SSam Clegg     }
1469586320c0SNicholas Wilson   }
147031a2c809SSam Clegg 
1471586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1472586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1473586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
147425d8e68bSSam Clegg     if (!isInSymtab(WS)) {
147518c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1476586320c0SNicholas Wilson       continue;
147725d8e68bSSam Clegg     }
1478d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1479586320c0SNicholas Wilson 
1480586320c0SNicholas Wilson     uint32_t Flags = 0;
1481586320c0SNicholas Wilson     if (WS.isWeak())
1482586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1483586320c0SNicholas Wilson     if (WS.isHidden())
1484586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1485586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1486586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1487586320c0SNicholas Wilson     if (WS.isUndefined())
1488586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1489d6ef8da3SSam Clegg     if (WS.isExported())
1490d6ef8da3SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
149129874ceaSDan Gohman     if (WS.getName() != WS.getImportName())
149229874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1493586320c0SNicholas Wilson 
1494586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1495586320c0SNicholas Wilson     Info.Name = WS.getName();
1496586320c0SNicholas Wilson     Info.Kind = WS.getType();
1497586320c0SNicholas Wilson     Info.Flags = Flags;
14984d57fbd0SSam Clegg     if (!WS.isData()) {
14994d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1500586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
15014d57fbd0SSam Clegg     } else if (WS.isDefined()) {
15024d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1503586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
15044d57fbd0SSam Clegg     }
150525d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1506586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1507b7787fd0SSam Clegg   }
1508b7787fd0SSam Clegg 
15096006e091SSam Clegg   {
15106006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1511f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1512f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1513f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1514d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1515d1152a26SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
1516f9edbe95SSam Clegg         return;
1517f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
151818c56a07SHeejin Ahn       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
15196c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
152018c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1521f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1522d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1523f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
15246c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
15256006e091SSam Clegg         registerFunctionType(WS);
15266006e091SSam Clegg       }
15276006e091SSam Clegg     };
1528970d02c4SDan Gohman 
15296006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
15306006e091SSam Clegg       HandleReloc(RelEntry);
15316006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
15326006e091SSam Clegg       HandleReloc(RelEntry);
1533d934cb88SDan Gohman   }
1534d934cb88SDan Gohman 
1535bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1536bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1537bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1538bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1539bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1540bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1541bafe6902SSam Clegg       continue;
1542bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1543bafe6902SSam Clegg       continue;
1544b210c64bSSam Clegg 
1545b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1546b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1547bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1548b210c64bSSam Clegg 
1549b210c64bSSam Clegg     auto IT = WS.begin();
1550b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1551b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1552b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1553b210c64bSSam Clegg 
1554b210c64bSSam Clegg     IT = std::next(IT);
1555b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1556bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1557bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1558bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1559bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1560b210c64bSSam Clegg 
1561b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1562bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1563bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1564b210c64bSSam Clegg 
1565bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
15664d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
15674d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
15684d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1569f208f631SHeejin Ahn         report_fatal_error(
1570f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
15714d57fbd0SSam Clegg       if (WS.getSectionName()
15724d57fbd0SSam Clegg               .substr(PrefixLength + 1)
15734d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1574bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1575bafe6902SSam Clegg     }
1576bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1577bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1578f208f631SHeejin Ahn     for (const uint8_t *
157918c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
158018c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
158118c56a07SHeejin Ahn          P != End; ++P) {
158218c56a07SHeejin Ahn       if (*P != 0)
1583bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1584bafe6902SSam Clegg     }
1585bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1586f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1587f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1588bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
15898fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
15908fffa1dfSSam Clegg       if (!SymRef)
1591bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
15928fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
15938fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
159425d8e68bSSam Clegg         report_fatal_error("symbols in .init_array should exist in symbtab");
15958fffa1dfSSam Clegg       if (!TargetSym.isFunction())
15968fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
159725d8e68bSSam Clegg       InitFuncs.push_back(
15988fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1599bafe6902SSam Clegg     }
1600bafe6902SSam Clegg   }
1601bafe6902SSam Clegg 
160218eafb6cSDan Gohman   // Write out the Wasm header.
160318eafb6cSDan Gohman   writeHeader(Asm);
160418eafb6cSDan Gohman 
1605da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1606f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
16079e15f359SSam Clegg   writeFunctionSection(Functions);
1608f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1609f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1610da419bdbSHeejin Ahn   writeEventSection(Events);
16119e15f359SSam Clegg   writeExportSection(Exports);
16129e15f359SSam Clegg   writeElemSection(TableElems);
1613fef8de66SThomas Lively   writeDataCountSection();
1614acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
16156c899ba6SSam Clegg   writeDataSection();
1616cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1617cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1618c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
16196f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
16206f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
16216a31a0d6SSam Clegg   writeCustomRelocSections();
1622cbda16ebSThomas Lively   if (ProducersSection)
1623cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1624f6f4f843SThomas Lively   if (TargetFeaturesSection)
1625f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1626970d02c4SDan Gohman 
1627d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1628438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
162918eafb6cSDan Gohman }
163018eafb6cSDan Gohman 
163160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
16321301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
163318eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
16340917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
163518eafb6cSDan Gohman }
1636