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/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.
4330e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 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;
51d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
52d934cb88SDan Gohman   uint64_t ContentsOffset;
53d934cb88SDan Gohman };
54d934cb88SDan Gohman 
559e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
569e15f359SSam Clegg // DenseMap key.
579e15f359SSam Clegg struct WasmFunctionType {
589e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
599e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
609e15f359SSam Clegg 
619e15f359SSam Clegg   // The return types of the function.
629e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
639e15f359SSam Clegg 
649e15f359SSam Clegg   // The parameter types of the function.
659e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
669e15f359SSam Clegg 
679e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
689e15f359SSam Clegg 
699e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
709e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
719e15f359SSam Clegg            Params == Other.Params;
729e15f359SSam Clegg   }
739e15f359SSam Clegg };
749e15f359SSam Clegg 
759e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
769e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
779e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
789e15f359SSam Clegg     WasmFunctionType FuncTy;
799e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
809e15f359SSam Clegg     return FuncTy;
819e15f359SSam Clegg   }
829e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
839e15f359SSam Clegg     WasmFunctionType FuncTy;
849e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
859e15f359SSam Clegg     return FuncTy;
869e15f359SSam Clegg   }
879e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
889e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
899e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
909e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
919e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
929e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
939e15f359SSam Clegg     return Value;
949e15f359SSam Clegg   }
959e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
969e15f359SSam Clegg                       const WasmFunctionType &RHS) {
979e15f359SSam Clegg     return LHS == RHS;
989e15f359SSam Clegg   }
999e15f359SSam Clegg };
1009e15f359SSam Clegg 
1017c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1027c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1037c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1047c395943SSam Clegg // wasm data segment.
1057c395943SSam Clegg struct WasmDataSegment {
1067c395943SSam Clegg   MCSectionWasm *Section;
107d95ed959SSam Clegg   StringRef Name;
1087c395943SSam Clegg   uint32_t Offset;
10963ebb813SSam Clegg   uint32_t Alignment;
11063ebb813SSam Clegg   uint32_t Flags;
1117c395943SSam Clegg   SmallVector<char, 4> Data;
1127c395943SSam Clegg };
1137c395943SSam Clegg 
1149e15f359SSam Clegg // A wasm function to be written into the function section.
1159e15f359SSam Clegg struct WasmFunction {
1169e15f359SSam Clegg   int32_t Type;
1179e15f359SSam Clegg   const MCSymbolWasm *Sym;
1189e15f359SSam Clegg };
1199e15f359SSam Clegg 
1209e15f359SSam Clegg // A wasm global to be written into the global section.
1219e15f359SSam Clegg struct WasmGlobal {
1226e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1239e15f359SSam Clegg   uint64_t InitialValue;
1249e15f359SSam Clegg };
1259e15f359SSam Clegg 
126ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
127ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
128ea7caceeSSam Clegg // WasmComdatEntry.
129ea7caceeSSam Clegg struct WasmComdatEntry {
130ea7caceeSSam Clegg   unsigned Kind;
131ea7caceeSSam Clegg   uint32_t Index;
132ea7caceeSSam Clegg };
133ea7caceeSSam Clegg 
1346dc65e91SSam Clegg // Information about a single relocation.
1356dc65e91SSam Clegg struct WasmRelocationEntry {
1366dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1376dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1386dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1396dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
140fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1416dc65e91SSam Clegg 
1426dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1436dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
144fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1456dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1466dc65e91SSam Clegg         FixupSection(FixupSection) {}
1476dc65e91SSam Clegg 
148acd7d2b0SSam Clegg   bool hasAddend() const {
149acd7d2b0SSam Clegg     switch (Type) {
15013a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
15113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
15213a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
153acd7d2b0SSam Clegg       return true;
154acd7d2b0SSam Clegg     default:
155acd7d2b0SSam Clegg       return false;
156acd7d2b0SSam Clegg     }
157acd7d2b0SSam Clegg   }
158acd7d2b0SSam Clegg 
1596dc65e91SSam Clegg   void print(raw_ostream &Out) const {
1609bf73c07SSam Clegg     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
161759631c7SSam Clegg         << ", Type=" << Type
162759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1636dc65e91SSam Clegg   }
164b7787fd0SSam Clegg 
165615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
166b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
167b7787fd0SSam Clegg #endif
1686dc65e91SSam Clegg };
1696dc65e91SSam Clegg 
1701fb8daa6SSam Clegg #if !defined(NDEBUG)
1717f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
172b7787fd0SSam Clegg   Rel.print(OS);
173b7787fd0SSam Clegg   return OS;
174b7787fd0SSam Clegg }
1751fb8daa6SSam Clegg #endif
176b7787fd0SSam Clegg 
17718eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
17818eafb6cSDan Gohman   /// The target specific Wasm writer instance.
17918eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18018eafb6cSDan Gohman 
181d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
182d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
183d934cb88SDan Gohman 
184d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
185d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
186d934cb88SDan Gohman 
187d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
188acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
189acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
190d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
191d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
192f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
193d99f6078SSam Clegg   // Maps function/global symbols to the function/global index space.
194acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
195acd7d2b0SSam Clegg 
196acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
197acd7d2b0SSam Clegg       FunctionTypeIndices;
1985e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
1997c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2009f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2017c395943SSam Clegg   unsigned NumGlobalImports = 0;
202d934cb88SDan Gohman 
20318eafb6cSDan Gohman   // TargetObjectWriter wrappers.
20418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
205ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
206ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
20718eafb6cSDan Gohman   }
20818eafb6cSDan Gohman 
209d934cb88SDan Gohman   void startSection(SectionBookkeeping &Section, unsigned SectionId,
210d934cb88SDan Gohman                     const char *Name = nullptr);
211d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
212d934cb88SDan Gohman 
21318eafb6cSDan Gohman public:
2141301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2151301a878SLang Hames                    raw_pwrite_stream &OS)
2161301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2171301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
21818eafb6cSDan Gohman 
21918eafb6cSDan Gohman   ~WasmObjectWriter() override;
22018eafb6cSDan Gohman 
2210917c9e4SDan Gohman private:
222acd7d2b0SSam Clegg   void reset() override {
223acd7d2b0SSam Clegg     CodeRelocations.clear();
224acd7d2b0SSam Clegg     DataRelocations.clear();
225acd7d2b0SSam Clegg     TypeIndices.clear();
226acd7d2b0SSam Clegg     SymbolIndices.clear();
227f9edbe95SSam Clegg     TableIndices.clear();
228acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2295e3d33a7SSam Clegg     FunctionTypes.clear();
2307c395943SSam Clegg     Globals.clear();
231acd7d2b0SSam Clegg     MCObjectWriter::reset();
2329f3fe42eSSam Clegg     NumFunctionImports = 0;
2337c395943SSam Clegg     NumGlobalImports = 0;
234acd7d2b0SSam Clegg   }
235acd7d2b0SSam Clegg 
23618eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
23718eafb6cSDan Gohman 
23818eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
23918eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
240ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
24118eafb6cSDan Gohman 
24218eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
24318eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
24418eafb6cSDan Gohman 
24518eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2469e15f359SSam Clegg 
247b7787fd0SSam Clegg   void writeString(const StringRef Str) {
248b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
249b7787fd0SSam Clegg     writeBytes(Str);
250b7787fd0SSam Clegg   }
251b7787fd0SSam Clegg 
2529e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
2539e15f359SSam Clegg     encodeSLEB128(int32_t(Ty), getStream());
2549e15f359SSam Clegg   }
2559e15f359SSam Clegg 
256457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
257*8defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
258f950b24aSSam Clegg                           uint32_t NumElements);
259457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
2607c395943SSam Clegg   void writeGlobalSection();
261*8defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
262457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
2639e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
264457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
265457fb0b4SSam Clegg   void writeDataSection(ArrayRef<WasmDataSegment> Segments);
266acd7d2b0SSam Clegg   void writeCodeRelocSection();
2677c395943SSam Clegg   void writeDataRelocSection();
26831a2c809SSam Clegg   void writeLinkingMetaDataSection(
26931a2c809SSam Clegg       ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
270ea7caceeSSam Clegg       ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
271ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
272ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
273acd7d2b0SSam Clegg 
2747c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
275acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
276acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
277acd7d2b0SSam Clegg 
2787c395943SSam Clegg   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
279acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
2805e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
2815e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
28218eafb6cSDan Gohman };
2839e15f359SSam Clegg 
28418eafb6cSDan Gohman } // end anonymous namespace
28518eafb6cSDan Gohman 
28618eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
28718eafb6cSDan Gohman 
288d934cb88SDan Gohman // Write out a section header and a patchable section size field.
289d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
290d934cb88SDan Gohman                                     unsigned SectionId,
291d934cb88SDan Gohman                                     const char *Name) {
292d934cb88SDan Gohman   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
293d934cb88SDan Gohman          "Only custom sections can have names");
294d934cb88SDan Gohman 
295b7787fd0SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
296e2688c43SDerek Schuff   encodeULEB128(SectionId, getStream());
297d934cb88SDan Gohman 
298d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
299d934cb88SDan Gohman 
300d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
301d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
302d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
303d934cb88SDan Gohman 
304d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
305d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
306d934cb88SDan Gohman 
307d934cb88SDan Gohman   // Custom sections in wasm also have a string identifier.
308d934cb88SDan Gohman   if (SectionId == wasm::WASM_SEC_CUSTOM) {
309b7787fd0SSam Clegg     assert(Name);
310b7787fd0SSam Clegg     writeString(StringRef(Name));
311d934cb88SDan Gohman   }
312d934cb88SDan Gohman }
313d934cb88SDan Gohman 
314d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
315d934cb88SDan Gohman // section size field at the start of the section.
316d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
317d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
318d934cb88SDan Gohman   if (uint32_t(Size) != Size)
319d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
320d934cb88SDan Gohman 
321b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
322d934cb88SDan Gohman 
323d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
324d934cb88SDan Gohman   // the section id byte.
325d934cb88SDan Gohman   uint8_t Buffer[16];
32666a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
327d934cb88SDan Gohman   assert(SizeLen == 5);
328d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
329d934cb88SDan Gohman }
330d934cb88SDan Gohman 
33118eafb6cSDan Gohman // Emit the Wasm header.
33218eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3337ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3347ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
33518eafb6cSDan Gohman }
33618eafb6cSDan Gohman 
33718eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
33818eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
33918eafb6cSDan Gohman }
34018eafb6cSDan Gohman 
34118eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
34218eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
34318eafb6cSDan Gohman                                         const MCFragment *Fragment,
34418eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
345ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
346ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
347ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
348ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
349fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
350d934cb88SDan Gohman   uint64_t C = Target.getConstant();
351d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
352d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
353d934cb88SDan Gohman 
354bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
355bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
356bafe6902SSam Clegg     return;
357bafe6902SSam Clegg 
358d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
359d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
360d934cb88SDan Gohman            "Should not have constructed this");
361d934cb88SDan Gohman 
362d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
363d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
364d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
365d934cb88SDan Gohman 
366d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
367d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
368d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
369d934cb88SDan Gohman     if (IsPCRel) {
370d934cb88SDan Gohman       Ctx.reportError(
371d934cb88SDan Gohman           Fixup.getLoc(),
372d934cb88SDan Gohman           "No relocation available to represent this relative expression");
373d934cb88SDan Gohman       return;
374d934cb88SDan Gohman     }
375d934cb88SDan Gohman 
376d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
377d934cb88SDan Gohman 
378d934cb88SDan Gohman     if (SymB.isUndefined()) {
379d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
380d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
381d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
382d934cb88SDan Gohman       return;
383d934cb88SDan Gohman     }
384d934cb88SDan Gohman 
385d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
386d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
387d934cb88SDan Gohman     if (&SecB != &FixupSection) {
388d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
389d934cb88SDan Gohman                       "Cannot represent a difference across sections");
390d934cb88SDan Gohman       return;
391d934cb88SDan Gohman     }
392d934cb88SDan Gohman 
393d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
394d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
395d934cb88SDan Gohman     IsPCRel = true;
396d934cb88SDan Gohman     C -= K;
397d934cb88SDan Gohman   }
398d934cb88SDan Gohman 
399d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
400d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
401d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
402d934cb88SDan Gohman 
403d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
404d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4056ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4066ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4076ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
408d934cb88SDan Gohman   }
409d934cb88SDan Gohman 
410d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
411d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
412d934cb88SDan Gohman   // be negative and don't wrap.
413d934cb88SDan Gohman   FixedValue = 0;
414d934cb88SDan Gohman 
4156ad8f190SSam Clegg   if (SymA)
416d934cb88SDan Gohman     SymA->setUsedInReloc();
417d934cb88SDan Gohman 
418ae03c1e7SSam Clegg   assert(!IsPCRel);
4199d24fb7fSSam Clegg   assert(SymA);
4209d24fb7fSSam Clegg 
421ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
422ae03c1e7SSam Clegg 
423d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
424b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
425d934cb88SDan Gohman 
42612fd3da9SSam Clegg   if (FixupSection.isWasmData())
427d934cb88SDan Gohman     DataRelocations.push_back(Rec);
42812fd3da9SSam Clegg   else if (FixupSection.getKind().isText())
42912fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
43012fd3da9SSam Clegg   else if (!FixupSection.getKind().isMetadata())
43112fd3da9SSam Clegg     // TODO(sbc): Add support for debug sections.
43212fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
433d934cb88SDan Gohman }
434d934cb88SDan Gohman 
435d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
436d934cb88SDan Gohman // to allow patching.
437d934cb88SDan Gohman static void
438d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
439d934cb88SDan Gohman   uint8_t Buffer[5];
44066a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
441d934cb88SDan Gohman   assert(SizeLen == 5);
442d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
443d934cb88SDan Gohman }
444d934cb88SDan Gohman 
445d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
446d934cb88SDan Gohman // to allow patching.
447d934cb88SDan Gohman static void
448d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
449d934cb88SDan Gohman   uint8_t Buffer[5];
45066a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
451d934cb88SDan Gohman   assert(SizeLen == 5);
452d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
453d934cb88SDan Gohman }
454d934cb88SDan Gohman 
455d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
456d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
457d934cb88SDan Gohman   uint8_t Buffer[4];
458d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
459d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
460d934cb88SDan Gohman }
461d934cb88SDan Gohman 
462aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
463aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
464aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
465aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
466aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
467aff1c4dfSSam Clegg   }
468aff1c4dfSSam Clegg   return &Symbol;
469aff1c4dfSSam Clegg }
470aff1c4dfSSam Clegg 
471d934cb88SDan Gohman // Compute a value to write into the code at the location covered
47260ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
47360ec3034SSam Clegg // to make the object format more readable and more likely to be directly
47460ec3034SSam Clegg // useable.
4757c395943SSam Clegg uint32_t
4767c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
47760ec3034SSam Clegg   switch (RelEntry.Type) {
47860ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
479f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
480f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
481f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
482f9edbe95SSam Clegg     assert(Sym->isFunction());
483f9edbe95SSam Clegg     return TableIndices[Sym];
484f9edbe95SSam Clegg   }
48560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
48660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
48760ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
488f9edbe95SSam Clegg     // Provisional value is function/type/global index itself
48960ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
49060ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
49160ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
49260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
493f9edbe95SSam Clegg     // Provisional value is address of the global
49460ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
495270ed1b3SSam Clegg     // For undefined symbols, use zero
496cd65f698SSam Clegg     if (!Sym->isDefined())
497270ed1b3SSam Clegg       return 0;
498d934cb88SDan Gohman 
4997c395943SSam Clegg     uint32_t GlobalIndex = SymbolIndices[Sym];
5007c395943SSam Clegg     const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
5017c395943SSam Clegg     uint64_t Address = Global.InitialValue + RelEntry.Addend;
502d934cb88SDan Gohman 
503d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
50460ec3034SSam Clegg     return Address;
50560ec3034SSam Clegg   }
50660ec3034SSam Clegg   default:
50760ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
50860ec3034SSam Clegg   }
509d934cb88SDan Gohman }
510d934cb88SDan Gohman 
511759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
51263ebb813SSam Clegg                     MCSectionWasm &DataSection) {
513759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
514759631c7SSam Clegg 
51563ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
51663ebb813SSam Clegg 
517c55d13f4SSam Clegg   size_t LastFragmentSize = 0;
518759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
519759631c7SSam Clegg     if (Frag.hasInstructions())
520759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
521759631c7SSam Clegg 
522759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
523759631c7SSam Clegg       if (Align->getValueSize() != 1)
524759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
525759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
526759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
527759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
528759631c7SSam Clegg                                                  Align->getAlignment()),
529759631c7SSam Clegg                                          DataBytes.size() +
530759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
531759631c7SSam Clegg       DataBytes.resize(Size, Value);
532759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
533d707c370SRafael Espindola       int64_t Size;
534d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
535d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
536d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
537759631c7SSam Clegg     } else {
538759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
539759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
540759631c7SSam Clegg 
541759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
542c55d13f4SSam Clegg       LastFragmentSize = Contents.size();
543759631c7SSam Clegg     }
544759631c7SSam Clegg   }
545759631c7SSam Clegg 
546c55d13f4SSam Clegg   // Don't allow empty segments, or segments that end with zero-sized
547c55d13f4SSam Clegg   // fragment, otherwise the linker cannot map symbols to a unique
548c55d13f4SSam Clegg   // data segment.  This can be triggered by zero-sized structs
549c55d13f4SSam Clegg   // See: test/MC/WebAssembly/bss.ll
550c55d13f4SSam Clegg   if (LastFragmentSize == 0)
551c55d13f4SSam Clegg     DataBytes.resize(DataBytes.size() + 1);
552759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
553759631c7SSam Clegg }
554759631c7SSam Clegg 
55560ec3034SSam Clegg uint32_t
55660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
55760ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
558b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
559b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
560b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
561acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
562acd7d2b0SSam Clegg   }
56360ec3034SSam Clegg 
56460ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
56560ec3034SSam Clegg     report_fatal_error("symbol not found in function/global index space: " +
56660ec3034SSam Clegg                        RelEntry.Symbol->getName());
56760ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
568acd7d2b0SSam Clegg }
569acd7d2b0SSam Clegg 
570d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
571d934cb88SDan Gohman // directly.
572acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
573acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
574acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
575d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
576d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
577d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
578d934cb88SDan Gohman                       RelEntry.Offset;
579d934cb88SDan Gohman 
580b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
58160ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
58260ec3034SSam Clegg 
583acd7d2b0SSam Clegg     switch (RelEntry.Type) {
584acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5859d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
58660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
58760ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
588d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
589d934cb88SDan Gohman       break;
59060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
59160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
592d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
593d934cb88SDan Gohman       break;
59460ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
59560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
59660ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
59760ec3034SSam Clegg       break;
598d934cb88SDan Gohman     default:
5999d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
600d934cb88SDan Gohman     }
601d934cb88SDan Gohman   }
60218eafb6cSDan Gohman }
60318eafb6cSDan Gohman 
604acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will
605970d02c4SDan Gohman // need to handle.
606acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations(
6077c395943SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
608acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
609acd7d2b0SSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
610970d02c4SDan Gohman 
611acd7d2b0SSam Clegg     uint64_t Offset = RelEntry.Offset +
6127c395943SSam Clegg                       RelEntry.FixupSection->getSectionOffset();
613acd7d2b0SSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
614970d02c4SDan Gohman 
615acd7d2b0SSam Clegg     encodeULEB128(RelEntry.Type, Stream);
616970d02c4SDan Gohman     encodeULEB128(Offset, Stream);
617acd7d2b0SSam Clegg     encodeULEB128(Index, Stream);
618acd7d2b0SSam Clegg     if (RelEntry.hasAddend())
619acd7d2b0SSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
620970d02c4SDan Gohman   }
621970d02c4SDan Gohman }
622970d02c4SDan Gohman 
6239e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
624457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
6259e15f359SSam Clegg   if (FunctionTypes.empty())
6269e15f359SSam Clegg     return;
6279e15f359SSam Clegg 
6289e15f359SSam Clegg   SectionBookkeeping Section;
6299e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6309e15f359SSam Clegg 
6319e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
6329e15f359SSam Clegg 
6339e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
6349e15f359SSam Clegg     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
6359e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
6369e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
6379e15f359SSam Clegg       writeValueType(Ty);
6389e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
6399e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
6409e15f359SSam Clegg       writeValueType(Ty);
6419e15f359SSam Clegg   }
6429e15f359SSam Clegg 
6439e15f359SSam Clegg   endSection(Section);
6449e15f359SSam Clegg }
6459e15f359SSam Clegg 
646*8defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
647f950b24aSSam Clegg                                           uint32_t DataSize,
648f950b24aSSam Clegg                                           uint32_t NumElements) {
6499e15f359SSam Clegg   if (Imports.empty())
6509e15f359SSam Clegg     return;
6519e15f359SSam Clegg 
652f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
653f950b24aSSam Clegg 
6549e15f359SSam Clegg   SectionBookkeeping Section;
6559e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
6569e15f359SSam Clegg 
6579e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
658*8defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
659*8defa952SSam Clegg     writeString(Import.Module);
660*8defa952SSam Clegg     writeString(Import.Field);
6619e15f359SSam Clegg     encodeULEB128(Import.Kind, getStream());
6629e15f359SSam Clegg 
6639e15f359SSam Clegg     switch (Import.Kind) {
6649e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
665*8defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
6669e15f359SSam Clegg       break;
6679e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
668*8defa952SSam Clegg       encodeSLEB128(Import.Global.Type, getStream());
669*8defa952SSam Clegg       encodeULEB128(uint32_t(Import.Global.Mutable), getStream());
6709e15f359SSam Clegg       break;
671f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
672f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
673f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
674f950b24aSSam Clegg       break;
675f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
676*8defa952SSam Clegg       encodeSLEB128(Import.Table.ElemType, getStream());
677f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
678f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
679f950b24aSSam Clegg       break;
6809e15f359SSam Clegg     default:
6819e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
6829e15f359SSam Clegg     }
6839e15f359SSam Clegg   }
6849e15f359SSam Clegg 
6859e15f359SSam Clegg   endSection(Section);
6869e15f359SSam Clegg }
6879e15f359SSam Clegg 
688457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
6899e15f359SSam Clegg   if (Functions.empty())
6909e15f359SSam Clegg     return;
6919e15f359SSam Clegg 
6929e15f359SSam Clegg   SectionBookkeeping Section;
6939e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
6949e15f359SSam Clegg 
6959e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
6969e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
6979e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
6989e15f359SSam Clegg 
6999e15f359SSam Clegg   endSection(Section);
7009e15f359SSam Clegg }
7019e15f359SSam Clegg 
7027c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7039e15f359SSam Clegg   if (Globals.empty())
7049e15f359SSam Clegg     return;
7059e15f359SSam Clegg 
7069e15f359SSam Clegg   SectionBookkeeping Section;
7079e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7089e15f359SSam Clegg 
7099e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7109e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7116e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7126e7f1826SSam Clegg     write8(Global.Type.Mutable);
7139e15f359SSam Clegg 
7149e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7156e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7169e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7179e15f359SSam Clegg   }
7189e15f359SSam Clegg 
7199e15f359SSam Clegg   endSection(Section);
7209e15f359SSam Clegg }
7219e15f359SSam Clegg 
722*8defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7239e15f359SSam Clegg   if (Exports.empty())
7249e15f359SSam Clegg     return;
7259e15f359SSam Clegg 
7269e15f359SSam Clegg   SectionBookkeeping Section;
7279e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7289e15f359SSam Clegg 
7299e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
730*8defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
731*8defa952SSam Clegg     writeString(Export.Name);
7329e15f359SSam Clegg     encodeSLEB128(Export.Kind, getStream());
7339e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7349e15f359SSam Clegg   }
7359e15f359SSam Clegg 
7369e15f359SSam Clegg   endSection(Section);
7379e15f359SSam Clegg }
7389e15f359SSam Clegg 
739457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7409e15f359SSam Clegg   if (TableElems.empty())
7419e15f359SSam Clegg     return;
7429e15f359SSam Clegg 
7439e15f359SSam Clegg   SectionBookkeeping Section;
7449e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7459e15f359SSam Clegg 
7469e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7479e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7489e15f359SSam Clegg 
7499e15f359SSam Clegg   // init expr for starting offset
7509e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
75130e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
7529e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7539e15f359SSam Clegg 
7549e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7559e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7569e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7579e15f359SSam Clegg 
7589e15f359SSam Clegg   endSection(Section);
7599e15f359SSam Clegg }
7609e15f359SSam Clegg 
761457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
762457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
763457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
7649e15f359SSam Clegg   if (Functions.empty())
7659e15f359SSam Clegg     return;
7669e15f359SSam Clegg 
7679e15f359SSam Clegg   SectionBookkeeping Section;
7689e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
7699e15f359SSam Clegg 
7709e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7719e15f359SSam Clegg 
7729e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
773fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
7749e15f359SSam Clegg 
7759e15f359SSam Clegg     int64_t Size = 0;
7769e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
7779e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
7789e15f359SSam Clegg 
7799e15f359SSam Clegg     encodeULEB128(Size, getStream());
780fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
7819e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
7829e15f359SSam Clegg   }
7839e15f359SSam Clegg 
7849e15f359SSam Clegg   // Apply fixups.
785acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
7869e15f359SSam Clegg 
7879e15f359SSam Clegg   endSection(Section);
7889e15f359SSam Clegg }
7899e15f359SSam Clegg 
790457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
7917c395943SSam Clegg   if (Segments.empty())
7927c395943SSam Clegg     return;
7939e15f359SSam Clegg 
7949e15f359SSam Clegg   SectionBookkeeping Section;
7959e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
7969e15f359SSam Clegg 
7977c395943SSam Clegg   encodeULEB128(Segments.size(), getStream()); // count
7987c395943SSam Clegg 
7997c395943SSam Clegg   for (const WasmDataSegment & Segment : Segments) {
8009e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8019e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8027c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8039e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8047c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8057c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8067c395943SSam Clegg     writeBytes(Segment.Data); // data
8077c395943SSam Clegg   }
8089e15f359SSam Clegg 
8099e15f359SSam Clegg   // Apply fixups.
8107c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8119e15f359SSam Clegg 
8129e15f359SSam Clegg   endSection(Section);
8139e15f359SSam Clegg }
8149e15f359SSam Clegg 
815acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() {
8169e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8179e15f359SSam Clegg   // for descriptions of the reloc sections.
8189e15f359SSam Clegg 
8199e15f359SSam Clegg   if (CodeRelocations.empty())
8209e15f359SSam Clegg     return;
8219e15f359SSam Clegg 
8229e15f359SSam Clegg   SectionBookkeeping Section;
8239e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
8249e15f359SSam Clegg 
8259e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
826acd7d2b0SSam Clegg   encodeULEB128(CodeRelocations.size(), getStream());
8279e15f359SSam Clegg 
8287c395943SSam Clegg   writeRelocations(CodeRelocations);
8299e15f359SSam Clegg 
8309e15f359SSam Clegg   endSection(Section);
8319e15f359SSam Clegg }
8329e15f359SSam Clegg 
8337c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() {
8349e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8359e15f359SSam Clegg   // for descriptions of the reloc sections.
8369e15f359SSam Clegg 
8379e15f359SSam Clegg   if (DataRelocations.empty())
8389e15f359SSam Clegg     return;
8399e15f359SSam Clegg 
8409e15f359SSam Clegg   SectionBookkeeping Section;
8419e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
8429e15f359SSam Clegg 
8439e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
8449e15f359SSam Clegg   encodeULEB128(DataRelocations.size(), getStream());
8459e15f359SSam Clegg 
8467c395943SSam Clegg   writeRelocations(DataRelocations);
8479e15f359SSam Clegg 
8489e15f359SSam Clegg   endSection(Section);
8499e15f359SSam Clegg }
8509e15f359SSam Clegg 
8519e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
852d95ed959SSam Clegg     ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
853ea7caceeSSam Clegg     ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
854ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
855ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
8569e15f359SSam Clegg   SectionBookkeeping Section;
8579e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
858b7787fd0SSam Clegg   SectionBookkeeping SubSection;
8599e15f359SSam Clegg 
86031a2c809SSam Clegg   if (SymbolFlags.size() != 0) {
861b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
86231a2c809SSam Clegg     encodeULEB128(SymbolFlags.size(), getStream());
86331a2c809SSam Clegg     for (auto Pair: SymbolFlags) {
86431a2c809SSam Clegg       writeString(Pair.first);
86531a2c809SSam Clegg       encodeULEB128(Pair.second, getStream());
866b7787fd0SSam Clegg     }
867b7787fd0SSam Clegg     endSection(SubSection);
868b7787fd0SSam Clegg   }
8699e15f359SSam Clegg 
8709e1ade93SSam Clegg   if (DataSize > 0) {
8719e1ade93SSam Clegg     startSection(SubSection, wasm::WASM_DATA_SIZE);
8729e1ade93SSam Clegg     encodeULEB128(DataSize, getStream());
8739e1ade93SSam Clegg     endSection(SubSection);
8749e1ade93SSam Clegg   }
8759e1ade93SSam Clegg 
876d95ed959SSam Clegg   if (Segments.size()) {
87763ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
878d95ed959SSam Clegg     encodeULEB128(Segments.size(), getStream());
87963ebb813SSam Clegg     for (const WasmDataSegment &Segment : Segments) {
880d95ed959SSam Clegg       writeString(Segment.Name);
88163ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
88263ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
88363ebb813SSam Clegg     }
884d95ed959SSam Clegg     endSection(SubSection);
885d95ed959SSam Clegg   }
886d95ed959SSam Clegg 
887bafe6902SSam Clegg   if (!InitFuncs.empty()) {
888bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
889bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
890bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
891bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
892bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
893bafe6902SSam Clegg     }
894bafe6902SSam Clegg     endSection(SubSection);
895bafe6902SSam Clegg   }
896bafe6902SSam Clegg 
897ea7caceeSSam Clegg   if (Comdats.size()) {
898ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
899ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
900ea7caceeSSam Clegg     for (const auto &C : Comdats) {
901ea7caceeSSam Clegg       writeString(C.first);
902ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
903ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
904ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
905ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
906ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
907ea7caceeSSam Clegg       }
908ea7caceeSSam Clegg     }
909ea7caceeSSam Clegg     endSection(SubSection);
910ea7caceeSSam Clegg   }
911ea7caceeSSam Clegg 
9129e15f359SSam Clegg   endSection(Section);
9139e15f359SSam Clegg }
9149e15f359SSam Clegg 
9155e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
9165e3d33a7SSam Clegg   assert(Symbol.isFunction());
9175e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
9185e3d33a7SSam Clegg   return TypeIndices[&Symbol];
9195e3d33a7SSam Clegg }
9205e3d33a7SSam Clegg 
9215e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
9225e3d33a7SSam Clegg   assert(Symbol.isFunction());
9235e3d33a7SSam Clegg 
9245e3d33a7SSam Clegg   WasmFunctionType F;
925aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
9265e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
9275e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
9285e3d33a7SSam Clegg 
9295e3d33a7SSam Clegg   auto Pair =
9305e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
9315e3d33a7SSam Clegg   if (Pair.second)
9325e3d33a7SSam Clegg     FunctionTypes.push_back(F);
9335e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
9345e3d33a7SSam Clegg 
9355e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
9365e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
9375e3d33a7SSam Clegg   return Pair.first->second;
9385e3d33a7SSam Clegg }
9395e3d33a7SSam Clegg 
94018eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
94118eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
942b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
94382607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
9446e7f1826SSam Clegg   int32_t PtrType = is64Bit() ? wasm::WASM_TYPE_I64 : wasm::WASM_TYPE_I32;
945d934cb88SDan Gohman 
946d934cb88SDan Gohman   // Collect information from the available symbols.
947d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
948d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
949*8defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
950*8defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
95131a2c809SSam Clegg   SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
952bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
953ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
9547c395943SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
9557c395943SSam Clegg   uint32_t DataSize = 0;
956d934cb88SDan Gohman 
957f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
958f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
959f950b24aSSam Clegg   // it if there are no loads or stores.
960f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
961f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
962*8defa952SSam Clegg   wasm::WasmImport MemImport;
963*8defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
964*8defa952SSam Clegg   MemImport.Field = MemorySym->getName();
965f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
966f950b24aSSam Clegg   Imports.push_back(MemImport);
967f950b24aSSam Clegg 
968f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
969f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
970f950b24aSSam Clegg   // it if there are no indirect calls.
971f950b24aSSam Clegg   MCSymbolWasm *TableSym =
972f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
973*8defa952SSam Clegg   wasm::WasmImport TableImport;
974*8defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
975*8defa952SSam Clegg   TableImport.Field = TableSym->getName();
976f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
977*8defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
978f950b24aSSam Clegg   Imports.push_back(TableImport);
979f950b24aSSam Clegg 
98032ce5ca0SDan Gohman   // Populate FunctionTypeIndices and Imports.
98132ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
98232ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
98332ce5ca0SDan Gohman 
98432ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
9859f3fe42eSSam Clegg     // (because wasm always needs a type signature).
98632ce5ca0SDan Gohman     if (WS.isFunction())
98732ce5ca0SDan Gohman       registerFunctionType(WS);
98832ce5ca0SDan Gohman 
98932ce5ca0SDan Gohman     if (WS.isTemporary())
99032ce5ca0SDan Gohman       continue;
99132ce5ca0SDan Gohman 
99232ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
993cd65f698SSam Clegg     if ((!WS.isDefined() && !WS.isComdat()) ||
994d423f0d2SSam Clegg         WS.isVariable()) {
995*8defa952SSam Clegg       wasm::WasmImport Import;
996*8defa952SSam Clegg       Import.Module = WS.getModuleName();
997*8defa952SSam Clegg       Import.Field = WS.getName();
99832ce5ca0SDan Gohman 
99932ce5ca0SDan Gohman       if (WS.isFunction()) {
100032ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1001*8defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
10029f3fe42eSSam Clegg         SymbolIndices[&WS] = NumFunctionImports;
10039f3fe42eSSam Clegg         ++NumFunctionImports;
100432ce5ca0SDan Gohman       } else {
100532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1006*8defa952SSam Clegg         Import.Global.Type = PtrType;
100783b16226SDan Gohman         // If this global is the stack pointer, make it mutable.
1008ad19047dSDan Gohman         if (WS.getName() == "__stack_pointer")
1009*8defa952SSam Clegg           Import.Global.Mutable = true;
1010*8defa952SSam Clegg         else
1011*8defa952SSam Clegg           Import.Global.Mutable = false;
101232ce5ca0SDan Gohman 
1013*8defa952SSam Clegg         SymbolIndices[&WS] = NumGlobalImports;
101432ce5ca0SDan Gohman         ++NumGlobalImports;
101532ce5ca0SDan Gohman       }
101632ce5ca0SDan Gohman 
101732ce5ca0SDan Gohman       Imports.push_back(Import);
101832ce5ca0SDan Gohman     }
101932ce5ca0SDan Gohman   }
102032ce5ca0SDan Gohman 
1021759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1022759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
102312fd3da9SSam Clegg     if (!Section.isWasmData())
1024759631c7SSam Clegg       continue;
1025759631c7SSam Clegg 
1026bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1027bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1028bafe6902SSam Clegg       continue;
1029bafe6902SSam Clegg 
1030329e76d5SSam Clegg     uint32_t SegmentIndex = DataSegments.size();
1031759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1032759631c7SSam Clegg     DataSegments.emplace_back();
1033759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1034d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1035759631c7SSam Clegg     Segment.Offset = DataSize;
1036759631c7SSam Clegg     Segment.Section = &Section;
103763ebb813SSam Clegg     addData(Segment.Data, Section);
103863ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
103963ebb813SSam Clegg     Segment.Flags = 0;
1040759631c7SSam Clegg     DataSize += Segment.Data.size();
1041759631c7SSam Clegg     Section.setMemoryOffset(Segment.Offset);
1042ea7caceeSSam Clegg 
1043ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1044ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1045329e76d5SSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1046ea7caceeSSam Clegg     }
1047759631c7SSam Clegg   }
1048759631c7SSam Clegg 
1049b7787fd0SSam Clegg   // Handle regular defined and undefined symbols.
1050d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1051d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1052d934cb88SDan Gohman     // or used in relocations.
1053d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1054d934cb88SDan Gohman       continue;
1055b7787fd0SSam Clegg 
1056d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1057b7787fd0SSam Clegg     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1058329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1059329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1060329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1061b7787fd0SSam Clegg                  << " isFunction=" << WS.isFunction()
1062b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1063a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1064b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1065b7787fd0SSam Clegg 
1066a2b35dacSSam Clegg     if (WS.isWeak() || WS.isHidden()) {
1067a2b35dacSSam Clegg       uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1068a2b35dacSSam Clegg           (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1069a2b35dacSSam Clegg       SymbolFlags.emplace_back(WS.getName(), Flags);
1070a2b35dacSSam Clegg     }
1071b7787fd0SSam Clegg 
10725e3d33a7SSam Clegg     if (WS.isVariable())
10735e3d33a7SSam Clegg       continue;
10745e3d33a7SSam Clegg 
1075d934cb88SDan Gohman     unsigned Index;
1076b7787fd0SSam Clegg 
1077d934cb88SDan Gohman     if (WS.isFunction()) {
1078cd65f698SSam Clegg       if (WS.isDefined()) {
1079b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1080b7787fd0SSam Clegg           report_fatal_error(
1081b7787fd0SSam Clegg               "function sections must contain one function each");
1082b7787fd0SSam Clegg 
1083b7787fd0SSam Clegg         if (WS.getSize() == 0)
1084b7787fd0SSam Clegg           report_fatal_error(
1085b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1086b7787fd0SSam Clegg 
1087d934cb88SDan Gohman         // A definition. Take the next available index.
10889f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1089d934cb88SDan Gohman 
1090d934cb88SDan Gohman         // Prepare the function.
1091d934cb88SDan Gohman         WasmFunction Func;
10925e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1093d934cb88SDan Gohman         Func.Sym = &WS;
1094d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1095d934cb88SDan Gohman         Functions.push_back(Func);
1096d934cb88SDan Gohman       } else {
1097d934cb88SDan Gohman         // An import; the index was assigned above.
1098d934cb88SDan Gohman         Index = SymbolIndices.find(&WS)->second;
1099d934cb88SDan Gohman       }
1100d934cb88SDan Gohman 
11015e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1102d934cb88SDan Gohman    } else {
1103c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1104c38e947eSSam Clegg         continue;
1105c38e947eSSam Clegg 
1106cd65f698SSam Clegg       if (!WS.isDefined())
1107fe6414b0SSam Clegg         continue;
1108fe6414b0SSam Clegg 
1109d934cb88SDan Gohman       if (!WS.getSize())
1110c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1111c38e947eSSam Clegg                            WS.getName());
1112d934cb88SDan Gohman 
1113d934cb88SDan Gohman       int64_t Size = 0;
1114d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1115d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1116d934cb88SDan Gohman 
11177c395943SSam Clegg       // For each global, prepare a corresponding wasm global holding its
11187c395943SSam Clegg       // address.  For externals these will also be named exports.
11197c395943SSam Clegg       Index = NumGlobalImports + Globals.size();
1120759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1121ea7caceeSSam Clegg       assert(DataSection.isWasmData());
11227c395943SSam Clegg 
11237c395943SSam Clegg       WasmGlobal Global;
11246e7f1826SSam Clegg       Global.Type.Type = PtrType;
11256e7f1826SSam Clegg       Global.Type.Mutable = false;
1126759631c7SSam Clegg       Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
11277c395943SSam Clegg       SymbolIndices[&WS] = Index;
11287c395943SSam Clegg       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
11297c395943SSam Clegg       Globals.push_back(Global);
1130d934cb88SDan Gohman     }
1131d934cb88SDan Gohman 
1132d934cb88SDan Gohman     // If the symbol is visible outside this translation unit, export it.
1133cd65f698SSam Clegg     if (WS.isDefined()) {
1134*8defa952SSam Clegg       wasm::WasmExport Export;
1135*8defa952SSam Clegg       Export.Name = WS.getName();
1136d934cb88SDan Gohman       Export.Index = Index;
1137d934cb88SDan Gohman       if (WS.isFunction())
1138d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1139d934cb88SDan Gohman       else
1140d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11415e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1142d934cb88SDan Gohman       Exports.push_back(Export);
1143ea7caceeSSam Clegg 
114431a2c809SSam Clegg       if (!WS.isExternal())
114531a2c809SSam Clegg         SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1146ea7caceeSSam Clegg 
1147ea7caceeSSam Clegg       if (WS.isFunction()) {
1148cd65f698SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1149ea7caceeSSam Clegg         if (const MCSymbolWasm *C = Section.getGroup())
1150ea7caceeSSam Clegg           Comdats[C->getName()].emplace_back(
1151ea7caceeSSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1152ea7caceeSSam Clegg       }
1153d934cb88SDan Gohman     }
1154d934cb88SDan Gohman   }
1155d934cb88SDan Gohman 
11565e3d33a7SSam Clegg   // Handle weak aliases. We need to process these in a separate pass because
11575e3d33a7SSam Clegg   // we need to have processed the target of the alias before the alias itself
11585e3d33a7SSam Clegg   // and the symbols are not necessarily ordered in this way.
1159b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1160b7787fd0SSam Clegg     if (!S.isVariable())
1161b7787fd0SSam Clegg       continue;
116231a2c809SSam Clegg 
1163cd65f698SSam Clegg     assert(S.isDefined());
1164b7787fd0SSam Clegg 
11655e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1166aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1167aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
11685e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
11695e3d33a7SSam Clegg     assert(SymbolIndices.count(ResolvedSym) > 0);
1170b7787fd0SSam Clegg     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
11715e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> index:" << Index << "\n");
1172b7787fd0SSam Clegg 
1173*8defa952SSam Clegg     wasm::WasmExport Export;
1174*8defa952SSam Clegg     Export.Name = WS.getName();
1175b7787fd0SSam Clegg     Export.Index = Index;
1176b7787fd0SSam Clegg     if (WS.isFunction())
1177b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1178b7787fd0SSam Clegg     else
1179b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11805e3d33a7SSam Clegg     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1181b7787fd0SSam Clegg     Exports.push_back(Export);
118231a2c809SSam Clegg 
118331a2c809SSam Clegg     if (!WS.isExternal())
118431a2c809SSam Clegg       SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1185b7787fd0SSam Clegg   }
1186b7787fd0SSam Clegg 
11876006e091SSam Clegg   {
11886006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1189f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1190f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1191f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1192f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1193f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1194f9edbe95SSam Clegg         return;
1195f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1196f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
1197f9edbe95SSam Clegg       uint32_t SymbolIndex = SymbolIndices.find(&WS)->second;
1198f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1199f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1200329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1201f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
1202f9edbe95SSam Clegg         TableElems.push_back(SymbolIndex);
12036006e091SSam Clegg         registerFunctionType(WS);
12046006e091SSam Clegg       }
12056006e091SSam Clegg     };
1206970d02c4SDan Gohman 
12076006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
12086006e091SSam Clegg       HandleReloc(RelEntry);
12096006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
12106006e091SSam Clegg       HandleReloc(RelEntry);
1211d934cb88SDan Gohman   }
1212d934cb88SDan Gohman 
1213bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1214bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1215bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1216bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1217bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1218bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1219bafe6902SSam Clegg       continue;
1220bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1221bafe6902SSam Clegg       continue;
1222bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1223bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1224bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1225bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1226bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1227bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1228bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1229bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1230bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1231bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1232bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1233bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1234bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1235bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1236bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1237bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1238bafe6902SSam Clegg     }
1239bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1240bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1241bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1242bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1243bafe6902SSam Clegg          p != end; ++p) {
1244bafe6902SSam Clegg       if (*p != 0)
1245bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1246bafe6902SSam Clegg     }
1247bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1248bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1249bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1250bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1251bafe6902SSam Clegg       if (!Sym)
1252bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1253bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1254bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1255bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1256bafe6902SSam Clegg       if (I == SymbolIndices.end())
1257bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1258bafe6902SSam Clegg       uint32_t Index = I->second;
1259bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1260bafe6902SSam Clegg     }
1261bafe6902SSam Clegg   }
1262bafe6902SSam Clegg 
126318eafb6cSDan Gohman   // Write out the Wasm header.
126418eafb6cSDan Gohman   writeHeader(Asm);
126518eafb6cSDan Gohman 
12669e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1267f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
12689e15f359SSam Clegg   writeFunctionSection(Functions);
1269f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1270f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
12717c395943SSam Clegg   writeGlobalSection();
12729e15f359SSam Clegg   writeExportSection(Exports);
12739e15f359SSam Clegg   writeElemSection(TableElems);
1274acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
12757c395943SSam Clegg   writeDataSection(DataSegments);
1276acd7d2b0SSam Clegg   writeCodeRelocSection();
12777c395943SSam Clegg   writeDataRelocSection();
1278bafe6902SSam Clegg   writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1279ea7caceeSSam Clegg                               InitFuncs, Comdats);
1280970d02c4SDan Gohman 
1281d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1282d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
128318eafb6cSDan Gohman }
128418eafb6cSDan Gohman 
128560fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
12861301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
128718eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
12880917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
128918eafb6cSDan Gohman }
1290