118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
318eafb6cSDan Gohman //                     The LLVM Compiler Infrastructure
418eafb6cSDan Gohman //
518eafb6cSDan Gohman // This file is distributed under the University of Illinois Open Source
618eafb6cSDan Gohman // License. See LICENSE.TXT for details.
718eafb6cSDan Gohman //
818eafb6cSDan Gohman //===----------------------------------------------------------------------===//
918eafb6cSDan Gohman //
1018eafb6cSDan Gohman // This file implements Wasm object file writer information.
1118eafb6cSDan Gohman //
1218eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1318eafb6cSDan Gohman 
1418eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1518eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
16264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmInfo.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectFileInfo.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2918eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
30d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3118eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
33d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3518eafb6cSDan Gohman #include <vector>
3618eafb6cSDan Gohman 
3718eafb6cSDan Gohman using namespace llvm;
3818eafb6cSDan Gohman 
395e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
4018eafb6cSDan Gohman 
4118eafb6cSDan Gohman namespace {
429e15f359SSam Clegg 
43d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
44d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
45d934cb88SDan Gohman // locations within the section.
46d934cb88SDan Gohman struct SectionBookkeeping {
47d934cb88SDan Gohman   // Where the size of the section is written.
48d934cb88SDan Gohman   uint64_t SizeOffset;
49d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
50d934cb88SDan Gohman   uint64_t ContentsOffset;
51d934cb88SDan Gohman };
52d934cb88SDan Gohman 
539e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
549e15f359SSam Clegg // DenseMap key.
559e15f359SSam Clegg struct WasmFunctionType {
569e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
579e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
589e15f359SSam Clegg 
599e15f359SSam Clegg   // The return types of the function.
609e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
619e15f359SSam Clegg 
629e15f359SSam Clegg   // The parameter types of the function.
639e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
649e15f359SSam Clegg 
659e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
669e15f359SSam Clegg 
679e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
689e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
699e15f359SSam Clegg            Params == Other.Params;
709e15f359SSam Clegg   }
719e15f359SSam Clegg };
729e15f359SSam Clegg 
739e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
749e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
759e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
769e15f359SSam Clegg     WasmFunctionType FuncTy;
779e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
789e15f359SSam Clegg     return FuncTy;
799e15f359SSam Clegg   }
809e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
819e15f359SSam Clegg     WasmFunctionType FuncTy;
829e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
839e15f359SSam Clegg     return FuncTy;
849e15f359SSam Clegg   }
859e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
869e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
879e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
889e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
899e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
909e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
919e15f359SSam Clegg     return Value;
929e15f359SSam Clegg   }
939e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
949e15f359SSam Clegg                       const WasmFunctionType &RHS) {
959e15f359SSam Clegg     return LHS == RHS;
969e15f359SSam Clegg   }
979e15f359SSam Clegg };
989e15f359SSam Clegg 
997c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1007c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1017c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1027c395943SSam Clegg // wasm data segment.
1037c395943SSam Clegg struct WasmDataSegment {
1047c395943SSam Clegg   MCSectionWasm *Section;
1057c395943SSam Clegg   uint32_t Offset;
1067c395943SSam Clegg   SmallVector<char, 4> Data;
1077c395943SSam Clegg };
1087c395943SSam Clegg 
1099e15f359SSam Clegg // A wasm import to be written into the import section.
1109e15f359SSam Clegg struct WasmImport {
1119e15f359SSam Clegg   StringRef ModuleName;
1129e15f359SSam Clegg   StringRef FieldName;
1139e15f359SSam Clegg   unsigned Kind;
1149e15f359SSam Clegg   int32_t Type;
1159e15f359SSam Clegg };
1169e15f359SSam Clegg 
1179e15f359SSam Clegg // A wasm function to be written into the function section.
1189e15f359SSam Clegg struct WasmFunction {
1199e15f359SSam Clegg   int32_t Type;
1209e15f359SSam Clegg   const MCSymbolWasm *Sym;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm export to be written into the export section.
1249e15f359SSam Clegg struct WasmExport {
1259e15f359SSam Clegg   StringRef FieldName;
1269e15f359SSam Clegg   unsigned Kind;
1279e15f359SSam Clegg   uint32_t Index;
1289e15f359SSam Clegg };
1299e15f359SSam Clegg 
1309e15f359SSam Clegg // A wasm global to be written into the global section.
1319e15f359SSam Clegg struct WasmGlobal {
1329e15f359SSam Clegg   wasm::ValType Type;
1339e15f359SSam Clegg   bool IsMutable;
1349e15f359SSam Clegg   bool HasImport;
1359e15f359SSam Clegg   uint64_t InitialValue;
1369e15f359SSam Clegg   uint32_t ImportIndex;
1379e15f359SSam Clegg };
1389e15f359SSam Clegg 
1396dc65e91SSam Clegg // Information about a single relocation.
1406dc65e91SSam Clegg struct WasmRelocationEntry {
1416dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1426dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1436dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1446dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
145fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1466dc65e91SSam Clegg 
1476dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1486dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
149fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1506dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1516dc65e91SSam Clegg         FixupSection(FixupSection) {}
1526dc65e91SSam Clegg 
153acd7d2b0SSam Clegg   bool hasAddend() const {
154acd7d2b0SSam Clegg     switch (Type) {
15513a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
15613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
15713a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_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 {
1659bf73c07SSam Clegg     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
1666dc65e91SSam Clegg         << ", Type=" << Type << ", FixupSection=" << FixupSection;
1676dc65e91SSam Clegg   }
168b7787fd0SSam Clegg 
169b7787fd0SSam Clegg #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
171b7787fd0SSam Clegg #endif
1726dc65e91SSam Clegg };
1736dc65e91SSam Clegg 
1741fb8daa6SSam Clegg #if !defined(NDEBUG)
1757f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
176b7787fd0SSam Clegg   Rel.print(OS);
177b7787fd0SSam Clegg   return OS;
178b7787fd0SSam Clegg }
1791fb8daa6SSam Clegg #endif
180b7787fd0SSam Clegg 
18118eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
18218eafb6cSDan Gohman   /// Helper struct for containing some precomputed information on symbols.
18318eafb6cSDan Gohman   struct WasmSymbolData {
18418eafb6cSDan Gohman     const MCSymbolWasm *Symbol;
18518eafb6cSDan Gohman     StringRef Name;
18618eafb6cSDan Gohman 
18718eafb6cSDan Gohman     // Support lexicographic sorting.
18818eafb6cSDan Gohman     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
18918eafb6cSDan Gohman   };
19018eafb6cSDan Gohman 
19118eafb6cSDan Gohman   /// The target specific Wasm writer instance.
19218eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
19318eafb6cSDan Gohman 
194d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
195d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
196d934cb88SDan Gohman 
197d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
198d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
199d934cb88SDan Gohman 
200d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
201acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
202acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
203d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
204d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
205d99f6078SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
206d99f6078SSam Clegg   // Maps function/global symbols to the function/global index space.
207acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
208acd7d2b0SSam Clegg 
209acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
210acd7d2b0SSam Clegg       FunctionTypeIndices;
2115e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2127c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2137c395943SSam Clegg   unsigned NumGlobalImports = 0;
214d934cb88SDan Gohman 
21518eafb6cSDan Gohman   // TargetObjectWriter wrappers.
21618eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
217ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
218ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
21918eafb6cSDan Gohman   }
22018eafb6cSDan Gohman 
221d934cb88SDan Gohman   void startSection(SectionBookkeeping &Section, unsigned SectionId,
222d934cb88SDan Gohman                     const char *Name = nullptr);
223d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
224d934cb88SDan Gohman 
22518eafb6cSDan Gohman public:
22618eafb6cSDan Gohman   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
22718eafb6cSDan Gohman       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
22818eafb6cSDan Gohman 
229d934cb88SDan Gohman private:
23018eafb6cSDan Gohman   ~WasmObjectWriter() override;
23118eafb6cSDan Gohman 
232acd7d2b0SSam Clegg   void reset() override {
233acd7d2b0SSam Clegg     CodeRelocations.clear();
234acd7d2b0SSam Clegg     DataRelocations.clear();
235acd7d2b0SSam Clegg     TypeIndices.clear();
236acd7d2b0SSam Clegg     SymbolIndices.clear();
237d99f6078SSam Clegg     IndirectSymbolIndices.clear();
238acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2395e3d33a7SSam Clegg     FunctionTypes.clear();
2407c395943SSam Clegg     Globals.clear();
241acd7d2b0SSam Clegg     MCObjectWriter::reset();
2427c395943SSam Clegg     NumGlobalImports = 0;
243acd7d2b0SSam Clegg   }
244acd7d2b0SSam Clegg 
24518eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
24618eafb6cSDan Gohman 
24718eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
24818eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
249ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
25018eafb6cSDan Gohman 
25118eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
25218eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
25318eafb6cSDan Gohman 
25418eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2559e15f359SSam Clegg 
256b7787fd0SSam Clegg   void writeString(const StringRef Str) {
257b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
258b7787fd0SSam Clegg     writeBytes(Str);
259b7787fd0SSam Clegg   }
260b7787fd0SSam Clegg 
2619e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
2629e15f359SSam Clegg     encodeSLEB128(int32_t(Ty), getStream());
2639e15f359SSam Clegg   }
2649e15f359SSam Clegg 
265457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
266457fb0b4SSam Clegg   void writeImportSection(ArrayRef<WasmImport> Imports);
267457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
268d99f6078SSam Clegg   void writeTableSection(uint32_t NumElements);
2697c395943SSam Clegg   void writeMemorySection(uint32_t DataSize);
2707c395943SSam Clegg   void writeGlobalSection();
271457fb0b4SSam Clegg   void writeExportSection(ArrayRef<WasmExport> Exports);
272457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
2739e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
274457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
275457fb0b4SSam Clegg   void writeDataSection(ArrayRef<WasmDataSegment> Segments);
276457fb0b4SSam Clegg   void writeNameSection(ArrayRef<WasmFunction> Functions,
277457fb0b4SSam Clegg                         ArrayRef<WasmImport> Imports,
2789e15f359SSam Clegg                         uint32_t NumFuncImports);
279acd7d2b0SSam Clegg   void writeCodeRelocSection();
2807c395943SSam Clegg   void writeDataRelocSection();
2819e1ade93SSam Clegg   void writeLinkingMetaDataSection(uint32_t DataSize, uint32_t DataAlignment,
2829e1ade93SSam Clegg                                    ArrayRef<StringRef> WeakSymbols,
283b7787fd0SSam Clegg                                    bool HasStackPointer,
2849e15f359SSam Clegg                                    uint32_t StackPointerGlobal);
285acd7d2b0SSam Clegg 
2867c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
287acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
288acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
289acd7d2b0SSam Clegg 
2907c395943SSam Clegg   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
291acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
2925e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
2935e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
29418eafb6cSDan Gohman };
2959e15f359SSam Clegg 
29618eafb6cSDan Gohman } // end anonymous namespace
29718eafb6cSDan Gohman 
29818eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
29918eafb6cSDan Gohman 
300d934cb88SDan Gohman // Write out a section header and a patchable section size field.
301d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
302d934cb88SDan Gohman                                     unsigned SectionId,
303d934cb88SDan Gohman                                     const char *Name) {
304d934cb88SDan Gohman   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
305d934cb88SDan Gohman          "Only custom sections can have names");
306d934cb88SDan Gohman 
307b7787fd0SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
308e2688c43SDerek Schuff   encodeULEB128(SectionId, getStream());
309d934cb88SDan Gohman 
310d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
311d934cb88SDan Gohman 
312d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
313d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
314d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
315d934cb88SDan Gohman 
316d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
317d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
318d934cb88SDan Gohman 
319d934cb88SDan Gohman   // Custom sections in wasm also have a string identifier.
320d934cb88SDan Gohman   if (SectionId == wasm::WASM_SEC_CUSTOM) {
321b7787fd0SSam Clegg     assert(Name);
322b7787fd0SSam Clegg     writeString(StringRef(Name));
323d934cb88SDan Gohman   }
324d934cb88SDan Gohman }
325d934cb88SDan Gohman 
326d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
327d934cb88SDan Gohman // section size field at the start of the section.
328d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
329d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
330d934cb88SDan Gohman   if (uint32_t(Size) != Size)
331d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
332d934cb88SDan Gohman 
333b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
334d934cb88SDan Gohman 
335d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
336d934cb88SDan Gohman   // the section id byte.
337d934cb88SDan Gohman   uint8_t Buffer[16];
338*66a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
339d934cb88SDan Gohman   assert(SizeLen == 5);
340d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
341d934cb88SDan Gohman }
342d934cb88SDan Gohman 
34318eafb6cSDan Gohman // Emit the Wasm header.
34418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3457ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3467ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
34718eafb6cSDan Gohman }
34818eafb6cSDan Gohman 
34918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
35018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
35118eafb6cSDan Gohman }
35218eafb6cSDan Gohman 
35318eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
35418eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
35518eafb6cSDan Gohman                                         const MCFragment *Fragment,
35618eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
357ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
358ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
359ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
360ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
361fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
362d934cb88SDan Gohman   uint64_t C = Target.getConstant();
363d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
364d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
365d934cb88SDan Gohman 
366d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
367d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
368d934cb88SDan Gohman            "Should not have constructed this");
369d934cb88SDan Gohman 
370d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
371d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
372d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
373d934cb88SDan Gohman 
374d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
375d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
376d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
377d934cb88SDan Gohman     if (IsPCRel) {
378d934cb88SDan Gohman       Ctx.reportError(
379d934cb88SDan Gohman           Fixup.getLoc(),
380d934cb88SDan Gohman           "No relocation available to represent this relative expression");
381d934cb88SDan Gohman       return;
382d934cb88SDan Gohman     }
383d934cb88SDan Gohman 
384d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
385d934cb88SDan Gohman 
386d934cb88SDan Gohman     if (SymB.isUndefined()) {
387d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
388d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
389d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
390d934cb88SDan Gohman       return;
391d934cb88SDan Gohman     }
392d934cb88SDan Gohman 
393d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
394d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
395d934cb88SDan Gohman     if (&SecB != &FixupSection) {
396d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
397d934cb88SDan Gohman                       "Cannot represent a difference across sections");
398d934cb88SDan Gohman       return;
399d934cb88SDan Gohman     }
400d934cb88SDan Gohman 
401d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
402d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
403d934cb88SDan Gohman     IsPCRel = true;
404d934cb88SDan Gohman     C -= K;
405d934cb88SDan Gohman   }
406d934cb88SDan Gohman 
407d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
408d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
409d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
410d934cb88SDan Gohman 
411d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
412d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4136ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4146ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4156ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
416d934cb88SDan Gohman   }
417d934cb88SDan Gohman 
418d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
419d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
420d934cb88SDan Gohman   // be negative and don't wrap.
421d934cb88SDan Gohman   FixedValue = 0;
422d934cb88SDan Gohman 
4236ad8f190SSam Clegg   if (SymA)
424d934cb88SDan Gohman     SymA->setUsedInReloc();
425d934cb88SDan Gohman 
426ae03c1e7SSam Clegg   assert(!IsPCRel);
4279d24fb7fSSam Clegg   assert(SymA);
4289d24fb7fSSam Clegg 
429ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
430ae03c1e7SSam Clegg 
431d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
432b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
433d934cb88SDan Gohman 
434d934cb88SDan Gohman   if (FixupSection.hasInstructions())
435d934cb88SDan Gohman     CodeRelocations.push_back(Rec);
436d934cb88SDan Gohman   else
437d934cb88SDan Gohman     DataRelocations.push_back(Rec);
438d934cb88SDan Gohman }
439d934cb88SDan Gohman 
440d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
441d934cb88SDan Gohman // to allow patching.
442d934cb88SDan Gohman static void
443d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
444d934cb88SDan Gohman   uint8_t Buffer[5];
445*66a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
446d934cb88SDan Gohman   assert(SizeLen == 5);
447d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
448d934cb88SDan Gohman }
449d934cb88SDan Gohman 
450d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
451d934cb88SDan Gohman // to allow patching.
452d934cb88SDan Gohman static void
453d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
454d934cb88SDan Gohman   uint8_t Buffer[5];
455*66a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
456d934cb88SDan Gohman   assert(SizeLen == 5);
457d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
458d934cb88SDan Gohman }
459d934cb88SDan Gohman 
460d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
461d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
462d934cb88SDan Gohman   uint8_t Buffer[4];
463d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
464d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
465d934cb88SDan Gohman }
466d934cb88SDan Gohman 
467aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
468aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
469aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
470aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
471aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
472aff1c4dfSSam Clegg   }
473aff1c4dfSSam Clegg   return &Symbol;
474aff1c4dfSSam Clegg }
475aff1c4dfSSam Clegg 
476d934cb88SDan Gohman // Compute a value to write into the code at the location covered
477d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since
478d934cb88SDan Gohman // we have addends; it just serves to make the code more readable
479d934cb88SDan Gohman // and to make standalone wasm modules directly usable.
4807c395943SSam Clegg uint32_t
4817c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
482aff1c4dfSSam Clegg   const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
483d934cb88SDan Gohman 
484d934cb88SDan Gohman   // For undefined symbols, use a hopefully invalid value.
485b7787fd0SSam Clegg   if (!Sym->isDefined(/*SetUsed=*/false))
486d934cb88SDan Gohman     return UINT32_MAX;
487d934cb88SDan Gohman 
4887c395943SSam Clegg   uint32_t GlobalIndex = SymbolIndices[Sym];
4897c395943SSam Clegg   const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
4907c395943SSam Clegg   uint64_t Address = Global.InitialValue + RelEntry.Addend;
491d934cb88SDan Gohman 
492d934cb88SDan Gohman   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
493d934cb88SDan Gohman   uint32_t Value = Address;
494d934cb88SDan Gohman 
495d934cb88SDan Gohman   return Value;
496d934cb88SDan Gohman }
497d934cb88SDan Gohman 
498acd7d2b0SSam Clegg uint32_t WasmObjectWriter::getRelocationIndexValue(
499acd7d2b0SSam Clegg     const WasmRelocationEntry &RelEntry) {
500acd7d2b0SSam Clegg   switch (RelEntry.Type) {
501acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
502acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
503b7787fd0SSam Clegg     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
504b7787fd0SSam Clegg       report_fatal_error("symbol not found table index space: " +
505b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
506d99f6078SSam Clegg     return IndirectSymbolIndices[RelEntry.Symbol];
507d99f6078SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5089d24fb7fSSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
50913a2e899SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
51013a2e899SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
51113a2e899SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
512b7787fd0SSam Clegg     if (!SymbolIndices.count(RelEntry.Symbol))
513b7787fd0SSam Clegg       report_fatal_error("symbol not found function/global index space: " +
514b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
515acd7d2b0SSam Clegg     return SymbolIndices[RelEntry.Symbol];
516acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
517b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
518b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
519b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
520acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
521acd7d2b0SSam Clegg   default:
522acd7d2b0SSam Clegg     llvm_unreachable("invalid relocation type");
523acd7d2b0SSam Clegg   }
524acd7d2b0SSam Clegg }
525acd7d2b0SSam Clegg 
526d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
527d934cb88SDan Gohman // directly.
528acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
529acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
530acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
531d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
532d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
533d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
534d934cb88SDan Gohman                       RelEntry.Offset;
535d934cb88SDan Gohman 
536b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
537acd7d2b0SSam Clegg     switch (RelEntry.Type) {
538acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
539acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5409d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5419d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
542acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
543acd7d2b0SSam Clegg       WritePatchableSLEB(Stream, Index, Offset);
544d934cb88SDan Gohman       break;
545d934cb88SDan Gohman     }
546acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
547acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
548acd7d2b0SSam Clegg       WriteI32(Stream, Index, Offset);
549d934cb88SDan Gohman       break;
550d934cb88SDan Gohman     }
55113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
5527c395943SSam Clegg       uint32_t Value = getProvisionalValue(RelEntry);
553d934cb88SDan Gohman       WritePatchableSLEB(Stream, Value, Offset);
554d934cb88SDan Gohman       break;
555d934cb88SDan Gohman     }
55613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
5577c395943SSam Clegg       uint32_t Value = getProvisionalValue(RelEntry);
558d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
559d934cb88SDan Gohman       break;
560d934cb88SDan Gohman     }
56113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
5627c395943SSam Clegg       uint32_t Value = getProvisionalValue(RelEntry);
563d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
564d934cb88SDan Gohman       break;
565d934cb88SDan Gohman     }
566d934cb88SDan Gohman     default:
5679d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
568d934cb88SDan Gohman     }
569d934cb88SDan Gohman   }
57018eafb6cSDan Gohman }
57118eafb6cSDan Gohman 
572acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will
573970d02c4SDan Gohman // need to handle.
574acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations(
5757c395943SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
576acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
577acd7d2b0SSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
578970d02c4SDan Gohman 
579acd7d2b0SSam Clegg     uint64_t Offset = RelEntry.Offset +
5807c395943SSam Clegg                       RelEntry.FixupSection->getSectionOffset();
581acd7d2b0SSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
582970d02c4SDan Gohman 
583acd7d2b0SSam Clegg     encodeULEB128(RelEntry.Type, Stream);
584970d02c4SDan Gohman     encodeULEB128(Offset, Stream);
585acd7d2b0SSam Clegg     encodeULEB128(Index, Stream);
586acd7d2b0SSam Clegg     if (RelEntry.hasAddend())
587acd7d2b0SSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
588970d02c4SDan Gohman   }
589970d02c4SDan Gohman }
590970d02c4SDan Gohman 
5919e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
592457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
5939e15f359SSam Clegg   if (FunctionTypes.empty())
5949e15f359SSam Clegg     return;
5959e15f359SSam Clegg 
5969e15f359SSam Clegg   SectionBookkeeping Section;
5979e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
5989e15f359SSam Clegg 
5999e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
6009e15f359SSam Clegg 
6019e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
6029e15f359SSam Clegg     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
6039e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
6049e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
6059e15f359SSam Clegg       writeValueType(Ty);
6069e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
6079e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
6089e15f359SSam Clegg       writeValueType(Ty);
6099e15f359SSam Clegg   }
6109e15f359SSam Clegg 
6119e15f359SSam Clegg   endSection(Section);
6129e15f359SSam Clegg }
6139e15f359SSam Clegg 
614457fb0b4SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
6159e15f359SSam Clegg   if (Imports.empty())
6169e15f359SSam Clegg     return;
6179e15f359SSam Clegg 
6189e15f359SSam Clegg   SectionBookkeeping Section;
6199e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
6209e15f359SSam Clegg 
6219e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
6229e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
623b7787fd0SSam Clegg     writeString(Import.ModuleName);
624b7787fd0SSam Clegg     writeString(Import.FieldName);
6259e15f359SSam Clegg 
6269e15f359SSam Clegg     encodeULEB128(Import.Kind, getStream());
6279e15f359SSam Clegg 
6289e15f359SSam Clegg     switch (Import.Kind) {
6299e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
6309e15f359SSam Clegg       encodeULEB128(Import.Type, getStream());
6319e15f359SSam Clegg       break;
6329e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
6339e15f359SSam Clegg       encodeSLEB128(int32_t(Import.Type), getStream());
6349e15f359SSam Clegg       encodeULEB128(0, getStream()); // mutability
6359e15f359SSam Clegg       break;
6369e15f359SSam Clegg     default:
6379e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
6389e15f359SSam Clegg     }
6399e15f359SSam Clegg   }
6409e15f359SSam Clegg 
6419e15f359SSam Clegg   endSection(Section);
6429e15f359SSam Clegg }
6439e15f359SSam Clegg 
644457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
6459e15f359SSam Clegg   if (Functions.empty())
6469e15f359SSam Clegg     return;
6479e15f359SSam Clegg 
6489e15f359SSam Clegg   SectionBookkeeping Section;
6499e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
6509e15f359SSam Clegg 
6519e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
6529e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
6539e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
6549e15f359SSam Clegg 
6559e15f359SSam Clegg   endSection(Section);
6569e15f359SSam Clegg }
6579e15f359SSam Clegg 
658d99f6078SSam Clegg void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
6599e15f359SSam Clegg   // For now, always emit the table section, since indirect calls are not
6609e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6619e15f359SSam Clegg   // it if there are no indirect calls.
662d99f6078SSam Clegg 
6639e15f359SSam Clegg   SectionBookkeeping Section;
6649e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TABLE);
6659e15f359SSam Clegg 
666d99f6078SSam Clegg   encodeULEB128(1, getStream());                       // The number of tables.
667d99f6078SSam Clegg                                                        // Fixed to 1 for now.
668d99f6078SSam Clegg   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
6699e15f359SSam Clegg   encodeULEB128(0, getStream());                       // flags
670d99f6078SSam Clegg   encodeULEB128(NumElements, getStream());             // initial
6719e15f359SSam Clegg 
6729e15f359SSam Clegg   endSection(Section);
6739e15f359SSam Clegg }
6749e15f359SSam Clegg 
6757c395943SSam Clegg void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
6769e15f359SSam Clegg   // For now, always emit the memory section, since loads and stores are not
6779e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6789e15f359SSam Clegg   // it if there are no loads or stores.
6799e15f359SSam Clegg   SectionBookkeeping Section;
6807c395943SSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
6819e15f359SSam Clegg 
6829e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_MEMORY);
6839e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of memory spaces
6849e15f359SSam Clegg 
6859e15f359SSam Clegg   encodeULEB128(0, getStream()); // flags
6869e15f359SSam Clegg   encodeULEB128(NumPages, getStream()); // initial
6879e15f359SSam Clegg 
6889e15f359SSam Clegg   endSection(Section);
6899e15f359SSam Clegg }
6909e15f359SSam Clegg 
6917c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
6929e15f359SSam Clegg   if (Globals.empty())
6939e15f359SSam Clegg     return;
6949e15f359SSam Clegg 
6959e15f359SSam Clegg   SectionBookkeeping Section;
6969e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
6979e15f359SSam Clegg 
6989e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
6999e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7009e15f359SSam Clegg     writeValueType(Global.Type);
7019e15f359SSam Clegg     write8(Global.IsMutable);
7029e15f359SSam Clegg 
7039e15f359SSam Clegg     if (Global.HasImport) {
7049e15f359SSam Clegg       assert(Global.InitialValue == 0);
7059e15f359SSam Clegg       write8(wasm::WASM_OPCODE_GET_GLOBAL);
7069e15f359SSam Clegg       encodeULEB128(Global.ImportIndex, getStream());
7079e15f359SSam Clegg     } else {
7089e15f359SSam Clegg       assert(Global.ImportIndex == 0);
7099e15f359SSam Clegg       write8(wasm::WASM_OPCODE_I32_CONST);
7109e15f359SSam Clegg       encodeSLEB128(Global.InitialValue, getStream()); // offset
7119e15f359SSam Clegg     }
7129e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7139e15f359SSam Clegg   }
7149e15f359SSam Clegg 
7159e15f359SSam Clegg   endSection(Section);
7169e15f359SSam Clegg }
7179e15f359SSam Clegg 
718457fb0b4SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
7199e15f359SSam Clegg   if (Exports.empty())
7209e15f359SSam Clegg     return;
7219e15f359SSam Clegg 
7229e15f359SSam Clegg   SectionBookkeeping Section;
7239e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7249e15f359SSam Clegg 
7259e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
7269e15f359SSam Clegg   for (const WasmExport &Export : Exports) {
727b7787fd0SSam Clegg     writeString(Export.FieldName);
7289e15f359SSam Clegg     encodeSLEB128(Export.Kind, getStream());
7299e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7309e15f359SSam Clegg   }
7319e15f359SSam Clegg 
7329e15f359SSam Clegg   endSection(Section);
7339e15f359SSam Clegg }
7349e15f359SSam Clegg 
735457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7369e15f359SSam Clegg   if (TableElems.empty())
7379e15f359SSam Clegg     return;
7389e15f359SSam Clegg 
7399e15f359SSam Clegg   SectionBookkeeping Section;
7409e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7419e15f359SSam Clegg 
7429e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7439e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7449e15f359SSam Clegg 
7459e15f359SSam Clegg   // init expr for starting offset
7469e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
7479e15f359SSam Clegg   encodeSLEB128(0, getStream());
7489e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7499e15f359SSam Clegg 
7509e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7519e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7529e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7539e15f359SSam Clegg 
7549e15f359SSam Clegg   endSection(Section);
7559e15f359SSam Clegg }
7569e15f359SSam Clegg 
757457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
758457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
759457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
7609e15f359SSam Clegg   if (Functions.empty())
7619e15f359SSam Clegg     return;
7629e15f359SSam Clegg 
7639e15f359SSam Clegg   SectionBookkeeping Section;
7649e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
7659e15f359SSam Clegg 
7669e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7679e15f359SSam Clegg 
7689e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
769fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
7709e15f359SSam Clegg 
7719e15f359SSam Clegg     int64_t Size = 0;
7729e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
7739e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
7749e15f359SSam Clegg 
7759e15f359SSam Clegg     encodeULEB128(Size, getStream());
7769e15f359SSam Clegg 
777fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
7789e15f359SSam Clegg 
7799e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
7809e15f359SSam Clegg   }
7819e15f359SSam Clegg 
7829e15f359SSam Clegg   // Apply fixups.
783acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
7849e15f359SSam Clegg 
7859e15f359SSam Clegg   endSection(Section);
7869e15f359SSam Clegg }
7879e15f359SSam Clegg 
788457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
7897c395943SSam Clegg   if (Segments.empty())
7907c395943SSam Clegg     return;
7919e15f359SSam Clegg 
7929e15f359SSam Clegg   SectionBookkeeping Section;
7939e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
7949e15f359SSam Clegg 
7957c395943SSam Clegg   encodeULEB128(Segments.size(), getStream()); // count
7967c395943SSam Clegg 
7977c395943SSam Clegg   for (const WasmDataSegment & Segment : Segments) {
7989e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
7999e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8007c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8019e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8027c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8037c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8047c395943SSam Clegg     writeBytes(Segment.Data); // data
8057c395943SSam Clegg   }
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   // Apply fixups.
8087c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8099e15f359SSam Clegg 
8109e15f359SSam Clegg   endSection(Section);
8119e15f359SSam Clegg }
8129e15f359SSam Clegg 
8139e15f359SSam Clegg void WasmObjectWriter::writeNameSection(
814457fb0b4SSam Clegg     ArrayRef<WasmFunction> Functions,
815457fb0b4SSam Clegg     ArrayRef<WasmImport> Imports,
8169e15f359SSam Clegg     unsigned NumFuncImports) {
8179e15f359SSam Clegg   uint32_t TotalFunctions = NumFuncImports + Functions.size();
8189e15f359SSam Clegg   if (TotalFunctions == 0)
8199e15f359SSam Clegg     return;
8209e15f359SSam Clegg 
8219e15f359SSam Clegg   SectionBookkeeping Section;
8229e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
8239e15f359SSam Clegg   SectionBookkeeping SubSection;
8249e15f359SSam Clegg   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
8259e15f359SSam Clegg 
8269e15f359SSam Clegg   encodeULEB128(TotalFunctions, getStream());
8279e15f359SSam Clegg   uint32_t Index = 0;
8289e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
8299e15f359SSam Clegg     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
8309e15f359SSam Clegg       encodeULEB128(Index, getStream());
831b7787fd0SSam Clegg       writeString(Import.FieldName);
8329e15f359SSam Clegg       ++Index;
8339e15f359SSam Clegg     }
8349e15f359SSam Clegg   }
8359e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
8369e15f359SSam Clegg     encodeULEB128(Index, getStream());
837b7787fd0SSam Clegg     writeString(Func.Sym->getName());
8389e15f359SSam Clegg     ++Index;
8399e15f359SSam Clegg   }
8409e15f359SSam Clegg 
8419e15f359SSam Clegg   endSection(SubSection);
8429e15f359SSam Clegg   endSection(Section);
8439e15f359SSam Clegg }
8449e15f359SSam Clegg 
845acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() {
8469e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8479e15f359SSam Clegg   // for descriptions of the reloc sections.
8489e15f359SSam Clegg 
8499e15f359SSam Clegg   if (CodeRelocations.empty())
8509e15f359SSam Clegg     return;
8519e15f359SSam Clegg 
8529e15f359SSam Clegg   SectionBookkeeping Section;
8539e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
8549e15f359SSam Clegg 
8559e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
856acd7d2b0SSam Clegg   encodeULEB128(CodeRelocations.size(), getStream());
8579e15f359SSam Clegg 
8587c395943SSam Clegg   writeRelocations(CodeRelocations);
8599e15f359SSam Clegg 
8609e15f359SSam Clegg   endSection(Section);
8619e15f359SSam Clegg }
8629e15f359SSam Clegg 
8637c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() {
8649e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8659e15f359SSam Clegg   // for descriptions of the reloc sections.
8669e15f359SSam Clegg 
8679e15f359SSam Clegg   if (DataRelocations.empty())
8689e15f359SSam Clegg     return;
8699e15f359SSam Clegg 
8709e15f359SSam Clegg   SectionBookkeeping Section;
8719e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
8729e15f359SSam Clegg 
8739e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
8749e15f359SSam Clegg   encodeULEB128(DataRelocations.size(), getStream());
8759e15f359SSam Clegg 
8767c395943SSam Clegg   writeRelocations(DataRelocations);
8779e15f359SSam Clegg 
8789e15f359SSam Clegg   endSection(Section);
8799e15f359SSam Clegg }
8809e15f359SSam Clegg 
8819e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
8829e1ade93SSam Clegg     uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
8839e1ade93SSam Clegg     bool HasStackPointer, uint32_t StackPointerGlobal) {
8849e15f359SSam Clegg   SectionBookkeeping Section;
8859e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
886b7787fd0SSam Clegg   SectionBookkeeping SubSection;
8879e15f359SSam Clegg 
888b7787fd0SSam Clegg   if (HasStackPointer) {
889b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_STACK_POINTER);
8909e15f359SSam Clegg     encodeULEB128(StackPointerGlobal, getStream()); // id
891b7787fd0SSam Clegg     endSection(SubSection);
892b7787fd0SSam Clegg   }
893b7787fd0SSam Clegg 
894b7787fd0SSam Clegg   if (WeakSymbols.size() != 0) {
895b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
896b7787fd0SSam Clegg     encodeULEB128(WeakSymbols.size(), getStream());
897b7787fd0SSam Clegg     for (const StringRef Export: WeakSymbols) {
898b7787fd0SSam Clegg       writeString(Export);
899b7787fd0SSam Clegg       encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
900b7787fd0SSam Clegg     }
901b7787fd0SSam Clegg     endSection(SubSection);
902b7787fd0SSam Clegg   }
9039e15f359SSam Clegg 
9049e1ade93SSam Clegg   if (DataSize > 0) {
9059e1ade93SSam Clegg     startSection(SubSection, wasm::WASM_DATA_SIZE);
9069e1ade93SSam Clegg     encodeULEB128(DataSize, getStream());
9079e1ade93SSam Clegg     endSection(SubSection);
9089e1ade93SSam Clegg 
9099e1ade93SSam Clegg     startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
9109e1ade93SSam Clegg     encodeULEB128(DataAlignment, getStream());
9119e1ade93SSam Clegg     endSection(SubSection);
9129e1ade93SSam Clegg   }
9139e1ade93SSam Clegg 
9149e15f359SSam Clegg   endSection(Section);
9159e15f359SSam Clegg }
9169e15f359SSam Clegg 
9175e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
9185e3d33a7SSam Clegg   assert(Symbol.isFunction());
9195e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
9205e3d33a7SSam Clegg   return TypeIndices[&Symbol];
9215e3d33a7SSam Clegg }
9225e3d33a7SSam Clegg 
9235e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
9245e3d33a7SSam Clegg   assert(Symbol.isFunction());
9255e3d33a7SSam Clegg 
9265e3d33a7SSam Clegg   WasmFunctionType F;
927aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
9285e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
9295e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
9305e3d33a7SSam Clegg 
9315e3d33a7SSam Clegg   auto Pair =
9325e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
9335e3d33a7SSam Clegg   if (Pair.second)
9345e3d33a7SSam Clegg     FunctionTypes.push_back(F);
9355e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
9365e3d33a7SSam Clegg 
9375e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
9385e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
9395e3d33a7SSam Clegg   return Pair.first->second;
9405e3d33a7SSam Clegg }
9415e3d33a7SSam Clegg 
94218eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
94318eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
944b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
94582607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
946b879539aSDerek Schuff   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
947d934cb88SDan Gohman 
948d934cb88SDan Gohman   // Collect information from the available symbols.
949d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
950d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
951d934cb88SDan Gohman   SmallVector<WasmImport, 4> Imports;
952d934cb88SDan Gohman   SmallVector<WasmExport, 4> Exports;
953b7787fd0SSam Clegg   SmallVector<StringRef, 4> WeakSymbols;
954d934cb88SDan Gohman   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
955d934cb88SDan Gohman   unsigned NumFuncImports = 0;
9567c395943SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
9579e1ade93SSam Clegg   uint32_t DataAlignment = 1;
958970d02c4SDan Gohman   uint32_t StackPointerGlobal = 0;
9597c395943SSam Clegg   uint32_t DataSize = 0;
960970d02c4SDan Gohman   bool HasStackPointer = false;
961d934cb88SDan Gohman 
962d934cb88SDan Gohman   // Populate the IsAddressTaken set.
963b7787fd0SSam Clegg   for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
964d934cb88SDan Gohman     switch (RelEntry.Type) {
965d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
96613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
967d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
968d934cb88SDan Gohman       break;
969d934cb88SDan Gohman     default:
970d934cb88SDan Gohman       break;
971d934cb88SDan Gohman     }
972d934cb88SDan Gohman   }
973b7787fd0SSam Clegg   for (const WasmRelocationEntry &RelEntry : DataRelocations) {
974d934cb88SDan Gohman     switch (RelEntry.Type) {
975d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
97613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
977d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
978d934cb88SDan Gohman       break;
979d934cb88SDan Gohman     default:
980d934cb88SDan Gohman       break;
981d934cb88SDan Gohman     }
982d934cb88SDan Gohman   }
983d934cb88SDan Gohman 
9847c395943SSam Clegg   // Populate FunctionTypeIndices and Imports.
985d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
9865e3d33a7SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
9875e3d33a7SSam Clegg 
9885e3d33a7SSam Clegg     if (WS.isTemporary())
9898c4baa00SSam Clegg       continue;
9908c4baa00SSam Clegg 
9915e3d33a7SSam Clegg     if (WS.isFunction())
9925e3d33a7SSam Clegg       registerFunctionType(WS);
993d934cb88SDan Gohman 
994d934cb88SDan Gohman     // If the symbol is not defined in this translation unit, import it.
9955e3d33a7SSam Clegg     if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
996d934cb88SDan Gohman       WasmImport Import;
997d934cb88SDan Gohman       Import.ModuleName = WS.getModuleName();
998d934cb88SDan Gohman       Import.FieldName = WS.getName();
999d934cb88SDan Gohman 
1000d934cb88SDan Gohman       if (WS.isFunction()) {
1001d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
10025e3d33a7SSam Clegg         Import.Type = getFunctionType(WS);
1003d934cb88SDan Gohman         SymbolIndices[&WS] = NumFuncImports;
1004d934cb88SDan Gohman         ++NumFuncImports;
1005d934cb88SDan Gohman       } else {
1006d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
10075e3d33a7SSam Clegg         Import.Type = int32_t(PtrType);
1008d934cb88SDan Gohman         SymbolIndices[&WS] = NumGlobalImports;
1009d934cb88SDan Gohman         ++NumGlobalImports;
1010d934cb88SDan Gohman       }
1011d934cb88SDan Gohman 
1012d934cb88SDan Gohman       Imports.push_back(Import);
1013d934cb88SDan Gohman     }
1014d934cb88SDan Gohman   }
1015d934cb88SDan Gohman 
101682607f56SDan Gohman   // In the special .global_variables section, we've encoded global
101782607f56SDan Gohman   // variables used by the function. Translate them into the Globals
101882607f56SDan Gohman   // list.
101982607f56SDan Gohman   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
102082607f56SDan Gohman   if (!GlobalVars->getFragmentList().empty()) {
102182607f56SDan Gohman     if (GlobalVars->getFragmentList().size() != 1)
102282607f56SDan Gohman       report_fatal_error("only one .global_variables fragment supported");
102382607f56SDan Gohman     const MCFragment &Frag = *GlobalVars->begin();
102482607f56SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
102582607f56SDan Gohman       report_fatal_error("only data supported in .global_variables");
1026fe6414b0SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
102782607f56SDan Gohman     if (!DataFrag.getFixups().empty())
102882607f56SDan Gohman       report_fatal_error("fixups not supported in .global_variables");
102982607f56SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1030970d02c4SDan Gohman     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1031970d02c4SDan Gohman                      *end = (const uint8_t *)Contents.data() + Contents.size();
1032970d02c4SDan Gohman          p != end; ) {
103382607f56SDan Gohman       WasmGlobal G;
1034970d02c4SDan Gohman       if (end - p < 3)
1035970d02c4SDan Gohman         report_fatal_error("truncated global variable encoding");
1036970d02c4SDan Gohman       G.Type = wasm::ValType(int8_t(*p++));
1037970d02c4SDan Gohman       G.IsMutable = bool(*p++);
1038970d02c4SDan Gohman       G.HasImport = bool(*p++);
1039970d02c4SDan Gohman       if (G.HasImport) {
104082607f56SDan Gohman         G.InitialValue = 0;
1041970d02c4SDan Gohman 
1042970d02c4SDan Gohman         WasmImport Import;
1043970d02c4SDan Gohman         Import.ModuleName = (const char *)p;
1044970d02c4SDan Gohman         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1045970d02c4SDan Gohman         if (!nul)
1046970d02c4SDan Gohman           report_fatal_error("global module name must be nul-terminated");
1047970d02c4SDan Gohman         p = nul + 1;
1048970d02c4SDan Gohman         nul = (const uint8_t *)memchr(p, '\0', end - p);
1049970d02c4SDan Gohman         if (!nul)
1050970d02c4SDan Gohman           report_fatal_error("global base name must be nul-terminated");
1051970d02c4SDan Gohman         Import.FieldName = (const char *)p;
1052970d02c4SDan Gohman         p = nul + 1;
1053970d02c4SDan Gohman 
1054970d02c4SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1055970d02c4SDan Gohman         Import.Type = int32_t(G.Type);
1056970d02c4SDan Gohman 
1057970d02c4SDan Gohman         G.ImportIndex = NumGlobalImports;
1058970d02c4SDan Gohman         ++NumGlobalImports;
1059970d02c4SDan Gohman 
1060970d02c4SDan Gohman         Imports.push_back(Import);
1061970d02c4SDan Gohman       } else {
1062970d02c4SDan Gohman         unsigned n;
1063970d02c4SDan Gohman         G.InitialValue = decodeSLEB128(p, &n);
1064970d02c4SDan Gohman         G.ImportIndex = 0;
1065c8da0c0bSSimon Pilgrim         if ((ptrdiff_t)n > end - p)
1066970d02c4SDan Gohman           report_fatal_error("global initial value must be valid SLEB128");
1067970d02c4SDan Gohman         p += n;
1068970d02c4SDan Gohman       }
106982607f56SDan Gohman       Globals.push_back(G);
107082607f56SDan Gohman     }
107182607f56SDan Gohman   }
107282607f56SDan Gohman 
1073970d02c4SDan Gohman   // In the special .stack_pointer section, we've encoded the stack pointer
1074970d02c4SDan Gohman   // index.
1075970d02c4SDan Gohman   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1076970d02c4SDan Gohman   if (!StackPtr->getFragmentList().empty()) {
1077970d02c4SDan Gohman     if (StackPtr->getFragmentList().size() != 1)
1078970d02c4SDan Gohman       report_fatal_error("only one .stack_pointer fragment supported");
1079970d02c4SDan Gohman     const MCFragment &Frag = *StackPtr->begin();
1080970d02c4SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1081970d02c4SDan Gohman       report_fatal_error("only data supported in .stack_pointer");
1082fe6414b0SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1083970d02c4SDan Gohman     if (!DataFrag.getFixups().empty())
1084970d02c4SDan Gohman       report_fatal_error("fixups not supported in .stack_pointer");
1085970d02c4SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1086970d02c4SDan Gohman     if (Contents.size() != 4)
1087970d02c4SDan Gohman       report_fatal_error("only one entry supported in .stack_pointer");
1088970d02c4SDan Gohman     HasStackPointer = true;
1089970d02c4SDan Gohman     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1090970d02c4SDan Gohman   }
1091970d02c4SDan Gohman 
1092b7787fd0SSam Clegg   // Handle regular defined and undefined symbols.
1093d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1094d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1095d934cb88SDan Gohman     // or used in relocations.
1096d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1097d934cb88SDan Gohman       continue;
1098b7787fd0SSam Clegg 
1099d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1100b7787fd0SSam Clegg     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1101b7787fd0SSam Clegg                  << " isDefined=" << S.isDefined() << " isExternal="
1102b7787fd0SSam Clegg                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1103b7787fd0SSam Clegg                  << " isFunction=" << WS.isFunction()
1104b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1105b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1106b7787fd0SSam Clegg 
1107b7787fd0SSam Clegg     if (WS.isWeak())
1108b7787fd0SSam Clegg       WeakSymbols.push_back(WS.getName());
1109b7787fd0SSam Clegg 
11105e3d33a7SSam Clegg     if (WS.isVariable())
11115e3d33a7SSam Clegg       continue;
11125e3d33a7SSam Clegg 
1113d934cb88SDan Gohman     unsigned Index;
1114b7787fd0SSam Clegg 
1115d934cb88SDan Gohman     if (WS.isFunction()) {
1116d934cb88SDan Gohman       if (WS.isDefined(/*SetUsed=*/false)) {
1117b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1118b7787fd0SSam Clegg           report_fatal_error(
1119b7787fd0SSam Clegg               "function sections must contain one function each");
1120b7787fd0SSam Clegg 
1121b7787fd0SSam Clegg         if (WS.getSize() == 0)
1122b7787fd0SSam Clegg           report_fatal_error(
1123b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1124b7787fd0SSam Clegg 
1125d934cb88SDan Gohman         // A definition. Take the next available index.
1126d934cb88SDan Gohman         Index = NumFuncImports + Functions.size();
1127d934cb88SDan Gohman 
1128d934cb88SDan Gohman         // Prepare the function.
1129d934cb88SDan Gohman         WasmFunction Func;
11305e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1131d934cb88SDan Gohman         Func.Sym = &WS;
1132d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1133d934cb88SDan Gohman         Functions.push_back(Func);
1134d934cb88SDan Gohman       } else {
1135d934cb88SDan Gohman         // An import; the index was assigned above.
1136d934cb88SDan Gohman         Index = SymbolIndices.find(&WS)->second;
1137d934cb88SDan Gohman       }
1138d934cb88SDan Gohman 
11395e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
11405e3d33a7SSam Clegg 
1141d934cb88SDan Gohman       // If needed, prepare the function to be called indirectly.
11425e3d33a7SSam Clegg       if (IsAddressTaken.count(&WS) != 0) {
1143d99f6078SSam Clegg         IndirectSymbolIndices[&WS] = TableElems.size();
11445e3d33a7SSam Clegg         DEBUG(dbgs() << "  -> adding to table: " << TableElems.size() << "\n");
1145d934cb88SDan Gohman         TableElems.push_back(Index);
1146d99f6078SSam Clegg       }
1147d934cb88SDan Gohman     } else {
1148c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1149c38e947eSSam Clegg         continue;
1150c38e947eSSam Clegg 
1151fe6414b0SSam Clegg       if (!WS.isDefined(/*SetUsed=*/false))
1152fe6414b0SSam Clegg         continue;
1153fe6414b0SSam Clegg 
1154d934cb88SDan Gohman       if (WS.getOffset() != 0)
1155c38e947eSSam Clegg         report_fatal_error("data sections must contain one variable each: " +
1156c38e947eSSam Clegg                            WS.getName());
1157d934cb88SDan Gohman       if (!WS.getSize())
1158c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1159c38e947eSSam Clegg                            WS.getName());
1160d934cb88SDan Gohman 
1161d934cb88SDan Gohman       int64_t Size = 0;
1162d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1163d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1164d934cb88SDan Gohman 
1165fe6414b0SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1166d934cb88SDan Gohman 
1167d934cb88SDan Gohman       if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1168d934cb88SDan Gohman         report_fatal_error("data sections must contain at most one variable");
1169d934cb88SDan Gohman 
11709e1ade93SSam Clegg       DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
1171d934cb88SDan Gohman 
11727c395943SSam Clegg       DataSegments.emplace_back();
11737c395943SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
11747c395943SSam Clegg 
11757c395943SSam Clegg       DataSize = alignTo(DataSize, DataSection.getAlignment());
11767c395943SSam Clegg       Segment.Offset = DataSize;
11777c395943SSam Clegg       Segment.Section = &DataSection;
11787c395943SSam Clegg 
11797c395943SSam Clegg       // For each global, prepare a corresponding wasm global holding its
11807c395943SSam Clegg       // address.  For externals these will also be named exports.
11817c395943SSam Clegg       Index = NumGlobalImports + Globals.size();
11827c395943SSam Clegg 
11837c395943SSam Clegg       WasmGlobal Global;
11847c395943SSam Clegg       Global.Type = PtrType;
11857c395943SSam Clegg       Global.IsMutable = false;
11867c395943SSam Clegg       Global.HasImport = false;
11877c395943SSam Clegg       Global.InitialValue = DataSize;
11887c395943SSam Clegg       Global.ImportIndex = 0;
11897c395943SSam Clegg       SymbolIndices[&WS] = Index;
11907c395943SSam Clegg       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
11917c395943SSam Clegg       Globals.push_back(Global);
1192d934cb88SDan Gohman 
1193fe6414b0SSam Clegg       for (const MCFragment &Frag : DataSection) {
1194d934cb88SDan Gohman         if (Frag.hasInstructions())
1195d934cb88SDan Gohman           report_fatal_error("only data supported in data sections");
1196d934cb88SDan Gohman 
1197fe6414b0SSam Clegg         if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1198d934cb88SDan Gohman           if (Align->getValueSize() != 1)
1199d934cb88SDan Gohman             report_fatal_error("only byte values supported for alignment");
1200d934cb88SDan Gohman           // If nops are requested, use zeros, as this is the data section.
1201d934cb88SDan Gohman           uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
12027c395943SSam Clegg           uint64_t Size = std::min<uint64_t>(
12037c395943SSam Clegg               alignTo(Segment.Data.size(), Align->getAlignment()),
12047c395943SSam Clegg               Segment.Data.size() + Align->getMaxBytesToEmit());
12057c395943SSam Clegg           Segment.Data.resize(Size, Value);
1206fe6414b0SSam Clegg         } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
12077c395943SSam Clegg           Segment.Data.insert(Segment.Data.end(), Fill->getSize(), Fill->getValue());
1208d934cb88SDan Gohman         } else {
1209fe6414b0SSam Clegg           const auto &DataFrag = cast<MCDataFragment>(Frag);
1210d934cb88SDan Gohman           const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1211d934cb88SDan Gohman 
12127c395943SSam Clegg           Segment.Data.insert(Segment.Data.end(), Contents.begin(),
12137c395943SSam Clegg                               Contents.end());
1214d934cb88SDan Gohman         }
1215d934cb88SDan Gohman       }
12167c395943SSam Clegg       DataSize += Segment.Data.size();
1217d934cb88SDan Gohman     }
1218d934cb88SDan Gohman 
1219d934cb88SDan Gohman     // If the symbol is visible outside this translation unit, export it.
12205e3d33a7SSam Clegg     if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
1221d934cb88SDan Gohman       WasmExport Export;
1222d934cb88SDan Gohman       Export.FieldName = WS.getName();
1223d934cb88SDan Gohman       Export.Index = Index;
1224d934cb88SDan Gohman       if (WS.isFunction())
1225d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1226d934cb88SDan Gohman       else
1227d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
12285e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1229d934cb88SDan Gohman       Exports.push_back(Export);
1230d934cb88SDan Gohman     }
1231d934cb88SDan Gohman   }
1232d934cb88SDan Gohman 
12335e3d33a7SSam Clegg   // Handle weak aliases. We need to process these in a separate pass because
12345e3d33a7SSam Clegg   // we need to have processed the target of the alias before the alias itself
12355e3d33a7SSam Clegg   // and the symbols are not necessarily ordered in this way.
1236b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1237b7787fd0SSam Clegg     if (!S.isVariable())
1238b7787fd0SSam Clegg       continue;
1239b7787fd0SSam Clegg     assert(S.isDefined(/*SetUsed=*/false));
1240b7787fd0SSam Clegg 
12415e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1242aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1243aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
12445e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
12455e3d33a7SSam Clegg     assert(SymbolIndices.count(ResolvedSym) > 0);
1246b7787fd0SSam Clegg     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
12475e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> index:" << Index << "\n");
1248b7787fd0SSam Clegg 
1249b7787fd0SSam Clegg     WasmExport Export;
1250b7787fd0SSam Clegg     Export.FieldName = WS.getName();
1251b7787fd0SSam Clegg     Export.Index = Index;
1252b7787fd0SSam Clegg     if (WS.isFunction())
1253b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1254b7787fd0SSam Clegg     else
1255b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
12565e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1257b7787fd0SSam Clegg     Exports.push_back(Export);
1258b7787fd0SSam Clegg   }
1259b7787fd0SSam Clegg 
1260d934cb88SDan Gohman   // Add types for indirect function calls.
1261acd7d2b0SSam Clegg   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1262acd7d2b0SSam Clegg     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1263acd7d2b0SSam Clegg       continue;
1264970d02c4SDan Gohman 
12655e3d33a7SSam Clegg     registerFunctionType(*Fixup.Symbol);
1266d934cb88SDan Gohman   }
1267d934cb88SDan Gohman 
126818eafb6cSDan Gohman   // Write out the Wasm header.
126918eafb6cSDan Gohman   writeHeader(Asm);
127018eafb6cSDan Gohman 
12719e15f359SSam Clegg   writeTypeSection(FunctionTypes);
12729e15f359SSam Clegg   writeImportSection(Imports);
12739e15f359SSam Clegg   writeFunctionSection(Functions);
1274d99f6078SSam Clegg   writeTableSection(TableElems.size());
12757c395943SSam Clegg   writeMemorySection(DataSize);
12767c395943SSam Clegg   writeGlobalSection();
12779e15f359SSam Clegg   writeExportSection(Exports);
12789e15f359SSam Clegg   // TODO: Start Section
12799e15f359SSam Clegg   writeElemSection(TableElems);
1280acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
12817c395943SSam Clegg   writeDataSection(DataSegments);
12829e15f359SSam Clegg   writeNameSection(Functions, Imports, NumFuncImports);
1283acd7d2b0SSam Clegg   writeCodeRelocSection();
12847c395943SSam Clegg   writeDataRelocSection();
12857c395943SSam Clegg   writeLinkingMetaDataSection(DataSize, DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
1286970d02c4SDan Gohman 
1287d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1288d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
128918eafb6cSDan Gohman }
129018eafb6cSDan Gohman 
129118eafb6cSDan Gohman MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
129218eafb6cSDan Gohman                                              raw_pwrite_stream &OS) {
129318eafb6cSDan Gohman   return new WasmObjectWriter(MOTW, OS);
129418eafb6cSDan Gohman }
1295