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 170*cfd44a2eSSam Clegg struct WasmCustomSection { 171*cfd44a2eSSam Clegg StringRef Name; 172*cfd44a2eSSam Clegg const SmallVectorImpl<char> &Contents; 173*cfd44a2eSSam Clegg 174*cfd44a2eSSam Clegg WasmCustomSection(StringRef Name, const SmallVectorImpl<char> &Contents) 175*cfd44a2eSSam Clegg : Name(Name), Contents(Contents) {} 176*cfd44a2eSSam Clegg }; 177*cfd44a2eSSam Clegg 1781fb8daa6SSam Clegg #if !defined(NDEBUG) 1797f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 180b7787fd0SSam Clegg Rel.print(OS); 181b7787fd0SSam Clegg return OS; 182b7787fd0SSam Clegg } 1831fb8daa6SSam Clegg #endif 184b7787fd0SSam Clegg 18518eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 18618eafb6cSDan Gohman /// The target specific Wasm writer instance. 18718eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 18818eafb6cSDan Gohman 189d934cb88SDan Gohman // Relocations for fixing up references in the code section. 190d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 191d934cb88SDan Gohman 192d934cb88SDan Gohman // Relocations for fixing up references in the data section. 193d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 194d934cb88SDan Gohman 195d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 196acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 197acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 198d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 199d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 200f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 2016c899ba6SSam Clegg // Maps function/global symbols to the (shared) Symbol index space. 202acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 2036c899ba6SSam Clegg // Maps function/global symbols to the function/global Wasm index space. 2046c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 2056c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2066c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 207acd7d2b0SSam Clegg 208acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 209acd7d2b0SSam Clegg FunctionTypeIndices; 2105e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2117c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2126c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 213*cfd44a2eSSam Clegg std::vector<WasmCustomSection> CustomSections; 2149f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2157c395943SSam Clegg unsigned NumGlobalImports = 0; 216d934cb88SDan Gohman 21718eafb6cSDan Gohman // TargetObjectWriter wrappers. 21818eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 219ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 220ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 22118eafb6cSDan Gohman } 22218eafb6cSDan Gohman 223d934cb88SDan Gohman void startSection(SectionBookkeeping &Section, unsigned SectionId, 224d934cb88SDan Gohman const char *Name = nullptr); 225d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 226d934cb88SDan Gohman 22718eafb6cSDan Gohman public: 2281301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2291301a878SLang Hames raw_pwrite_stream &OS) 2301301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2311301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 23218eafb6cSDan Gohman 23318eafb6cSDan Gohman ~WasmObjectWriter() override; 23418eafb6cSDan Gohman 2350917c9e4SDan Gohman private: 236acd7d2b0SSam Clegg void reset() override { 237acd7d2b0SSam Clegg CodeRelocations.clear(); 238acd7d2b0SSam Clegg DataRelocations.clear(); 239acd7d2b0SSam Clegg TypeIndices.clear(); 240acd7d2b0SSam Clegg SymbolIndices.clear(); 2416c899ba6SSam Clegg WasmIndices.clear(); 242f9edbe95SSam Clegg TableIndices.clear(); 2436c899ba6SSam Clegg DataLocations.clear(); 244acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2455e3d33a7SSam Clegg FunctionTypes.clear(); 2467c395943SSam Clegg Globals.clear(); 2476c899ba6SSam Clegg DataSegments.clear(); 248acd7d2b0SSam Clegg MCObjectWriter::reset(); 2499f3fe42eSSam Clegg NumFunctionImports = 0; 2507c395943SSam Clegg NumGlobalImports = 0; 251acd7d2b0SSam Clegg } 252acd7d2b0SSam Clegg 25318eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 25418eafb6cSDan Gohman 25518eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 25618eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 257ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 25818eafb6cSDan Gohman 25918eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 26018eafb6cSDan Gohman const MCAsmLayout &Layout) override; 26118eafb6cSDan Gohman 26218eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2639e15f359SSam Clegg 264b7787fd0SSam Clegg void writeString(const StringRef Str) { 265b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 266b7787fd0SSam Clegg writeBytes(Str); 267b7787fd0SSam Clegg } 268b7787fd0SSam Clegg 2699e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 27003e101f1SSam Clegg write8(static_cast<uint8_t>(Ty)); 2719e15f359SSam Clegg } 2729e15f359SSam Clegg 273457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 2748defa952SSam Clegg void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize, 275f950b24aSSam Clegg uint32_t NumElements); 276457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 2777c395943SSam Clegg void writeGlobalSection(); 2788defa952SSam Clegg void writeExportSection(ArrayRef<wasm::WasmExport> Exports); 279457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 2809e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 281457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 2826c899ba6SSam Clegg void writeDataSection(); 283acd7d2b0SSam Clegg void writeCodeRelocSection(); 2847c395943SSam Clegg void writeDataRelocSection(); 28531a2c809SSam Clegg void writeLinkingMetaDataSection( 28686b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 287ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 288ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 289*cfd44a2eSSam Clegg void writeUserCustomSections(ArrayRef<WasmCustomSection> CustomSections); 290acd7d2b0SSam Clegg 2917c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 292acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 293acd7d2b0SSam Clegg uint64_t ContentsOffset); 294acd7d2b0SSam Clegg 2957c395943SSam Clegg void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations); 296acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 2975e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm& Symbol); 2985e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm& Symbol); 29918eafb6cSDan Gohman }; 3009e15f359SSam Clegg 30118eafb6cSDan Gohman } // end anonymous namespace 30218eafb6cSDan Gohman 30318eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 30418eafb6cSDan Gohman 305d934cb88SDan Gohman // Write out a section header and a patchable section size field. 306d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 307d934cb88SDan Gohman unsigned SectionId, 308d934cb88SDan Gohman const char *Name) { 309d934cb88SDan Gohman assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 310d934cb88SDan Gohman "Only custom sections can have names"); 311d934cb88SDan Gohman 312b7787fd0SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n"); 31303e101f1SSam Clegg write8(SectionId); 314d934cb88SDan Gohman 315d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 316d934cb88SDan Gohman 317d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 318d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 319d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 320d934cb88SDan Gohman 321d934cb88SDan Gohman // The position where the section starts, for measuring its size. 322d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 323d934cb88SDan Gohman 324d934cb88SDan Gohman // Custom sections in wasm also have a string identifier. 325d934cb88SDan Gohman if (SectionId == wasm::WASM_SEC_CUSTOM) { 326b7787fd0SSam Clegg assert(Name); 327*cfd44a2eSSam Clegg writeString(Name); 328d934cb88SDan Gohman } 329d934cb88SDan Gohman } 330d934cb88SDan Gohman 331d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 332d934cb88SDan Gohman // section size field at the start of the section. 333d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 334d934cb88SDan Gohman uint64_t Size = getStream().tell() - Section.ContentsOffset; 335d934cb88SDan Gohman if (uint32_t(Size) != Size) 336d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 337d934cb88SDan Gohman 338b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 339d934cb88SDan Gohman 340d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 341d934cb88SDan Gohman // the section id byte. 342d934cb88SDan Gohman uint8_t Buffer[16]; 34366a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 344d934cb88SDan Gohman assert(SizeLen == 5); 345d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 346d934cb88SDan Gohman } 347d934cb88SDan Gohman 34818eafb6cSDan Gohman // Emit the Wasm header. 34918eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3507ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3517ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 35218eafb6cSDan Gohman } 35318eafb6cSDan Gohman 35418eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 35518eafb6cSDan Gohman const MCAsmLayout &Layout) { 35618eafb6cSDan Gohman } 35718eafb6cSDan Gohman 35818eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 35918eafb6cSDan Gohman const MCAsmLayout &Layout, 36018eafb6cSDan Gohman const MCFragment *Fragment, 36118eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 362ceecfe5bSRafael Espindola uint64_t &FixedValue) { 363ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 364ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 365ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 366fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 367d934cb88SDan Gohman uint64_t C = Target.getConstant(); 368d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 369d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 370d934cb88SDan Gohman 371bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 372bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 373bafe6902SSam Clegg return; 374bafe6902SSam Clegg 375b7a5469cSSam Clegg // TODO(sbc): Add support for debug sections. 376b7a5469cSSam Clegg if (FixupSection.getKind().isMetadata()) 377b7a5469cSSam Clegg return; 378b7a5469cSSam Clegg 379d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 380d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 381d934cb88SDan Gohman "Should not have constructed this"); 382d934cb88SDan Gohman 383d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 384d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 385d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 386d934cb88SDan Gohman 387d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 388d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 389d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 390d934cb88SDan Gohman if (IsPCRel) { 391d934cb88SDan Gohman Ctx.reportError( 392d934cb88SDan Gohman Fixup.getLoc(), 393d934cb88SDan Gohman "No relocation available to represent this relative expression"); 394d934cb88SDan Gohman return; 395d934cb88SDan Gohman } 396d934cb88SDan Gohman 397d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 398d934cb88SDan Gohman 399d934cb88SDan Gohman if (SymB.isUndefined()) { 400d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 401d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 402d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 403d934cb88SDan Gohman return; 404d934cb88SDan Gohman } 405d934cb88SDan Gohman 406d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 407d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 408d934cb88SDan Gohman if (&SecB != &FixupSection) { 409d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 410d934cb88SDan Gohman "Cannot represent a difference across sections"); 411d934cb88SDan Gohman return; 412d934cb88SDan Gohman } 413d934cb88SDan Gohman 414d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 415d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 416d934cb88SDan Gohman IsPCRel = true; 417d934cb88SDan Gohman C -= K; 418d934cb88SDan Gohman } 419d934cb88SDan Gohman 420d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 421d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 422d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 423d934cb88SDan Gohman 424d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 425d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4266ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4276ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4286ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 429d934cb88SDan Gohman } 430d934cb88SDan Gohman 431d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 432d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 433d934cb88SDan Gohman // be negative and don't wrap. 434d934cb88SDan Gohman FixedValue = 0; 435d934cb88SDan Gohman 4366ad8f190SSam Clegg if (SymA) 437d934cb88SDan Gohman SymA->setUsedInReloc(); 438d934cb88SDan Gohman 439ae03c1e7SSam Clegg assert(!IsPCRel); 4409d24fb7fSSam Clegg assert(SymA); 4419d24fb7fSSam Clegg 442ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 443ae03c1e7SSam Clegg 444d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 445b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 446d934cb88SDan Gohman 447b7a5469cSSam Clegg // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required 448b7a5469cSSam Clegg // to be against a named symbol. 449b7a5469cSSam Clegg // TODO(sbc): Add support for relocations against unnamed temporaries such 450b7a5469cSSam Clegg // as those generated by llvm's `blockaddress`. 451b7a5469cSSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 452b7a5469cSSam Clegg if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) 453b7a5469cSSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 454b7a5469cSSam Clegg "supported by wasm"); 455b7a5469cSSam Clegg 45612fd3da9SSam Clegg if (FixupSection.isWasmData()) 457d934cb88SDan Gohman DataRelocations.push_back(Rec); 45812fd3da9SSam Clegg else if (FixupSection.getKind().isText()) 45912fd3da9SSam Clegg CodeRelocations.push_back(Rec); 460b7a5469cSSam Clegg else 46112fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 462d934cb88SDan Gohman } 463d934cb88SDan Gohman 464d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 465d934cb88SDan Gohman // to allow patching. 466d934cb88SDan Gohman static void 467d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 468d934cb88SDan Gohman uint8_t Buffer[5]; 46966a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 470d934cb88SDan Gohman assert(SizeLen == 5); 471d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 472d934cb88SDan Gohman } 473d934cb88SDan Gohman 474d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 475d934cb88SDan Gohman // to allow patching. 476d934cb88SDan Gohman static void 477d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 478d934cb88SDan Gohman uint8_t Buffer[5]; 47966a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 480d934cb88SDan Gohman assert(SizeLen == 5); 481d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 482d934cb88SDan Gohman } 483d934cb88SDan Gohman 484d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 485d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 486d934cb88SDan Gohman uint8_t Buffer[4]; 487d934cb88SDan Gohman support::endian::write32le(Buffer, X); 488d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 489d934cb88SDan Gohman } 490d934cb88SDan Gohman 491aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 492aff1c4dfSSam Clegg if (Symbol.isVariable()) { 493aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 494aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 495aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 496aff1c4dfSSam Clegg } 497aff1c4dfSSam Clegg return &Symbol; 498aff1c4dfSSam Clegg } 499aff1c4dfSSam Clegg 500d934cb88SDan Gohman // Compute a value to write into the code at the location covered 50160ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 50260ec3034SSam Clegg // to make the object format more readable and more likely to be directly 50360ec3034SSam Clegg // useable. 5047c395943SSam Clegg uint32_t 5057c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 50660ec3034SSam Clegg switch (RelEntry.Type) { 50760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 508f9edbe95SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 509f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 510f9edbe95SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 511f9edbe95SSam Clegg assert(Sym->isFunction()); 512f9edbe95SSam Clegg return TableIndices[Sym]; 513f9edbe95SSam Clegg } 51460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5156c899ba6SSam Clegg // Provisional value is same as the index 51660ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 5176c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5186c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 5196c899ba6SSam Clegg // Provisional value is function/global Wasm index 5206c899ba6SSam Clegg if (!WasmIndices.count(RelEntry.Symbol)) 5216c899ba6SSam Clegg report_fatal_error("symbol not found in wasm index space: " + 5226c899ba6SSam Clegg RelEntry.Symbol->getName()); 5236c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 52460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 52560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 52660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 527f9edbe95SSam Clegg // Provisional value is address of the global 52860ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 529270ed1b3SSam Clegg // For undefined symbols, use zero 530cd65f698SSam Clegg if (!Sym->isDefined()) 531270ed1b3SSam Clegg return 0; 5326c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 5336c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 534d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 5356c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 53660ec3034SSam Clegg } 53760ec3034SSam Clegg default: 53860ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 53960ec3034SSam Clegg } 540d934cb88SDan Gohman } 541d934cb88SDan Gohman 542759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 54363ebb813SSam Clegg MCSectionWasm &DataSection) { 544759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 545759631c7SSam Clegg 54663ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 54763ebb813SSam Clegg 548759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 549759631c7SSam Clegg if (Frag.hasInstructions()) 550759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 551759631c7SSam Clegg 552759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 553759631c7SSam Clegg if (Align->getValueSize() != 1) 554759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 555759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 556759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 557759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 558759631c7SSam Clegg Align->getAlignment()), 559759631c7SSam Clegg DataBytes.size() + 560759631c7SSam Clegg Align->getMaxBytesToEmit()); 561759631c7SSam Clegg DataBytes.resize(Size, Value); 562759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 563d707c370SRafael Espindola int64_t Size; 564d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 565d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 566d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 567759631c7SSam Clegg } else { 568759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 569759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 570759631c7SSam Clegg 571759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 572759631c7SSam Clegg } 573759631c7SSam Clegg } 574759631c7SSam Clegg 575759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 576759631c7SSam Clegg } 577759631c7SSam Clegg 57860ec3034SSam Clegg uint32_t 57960ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 58060ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 581b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 582b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 583b7787fd0SSam Clegg RelEntry.Symbol->getName()); 584acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 585acd7d2b0SSam Clegg } 58660ec3034SSam Clegg 58760ec3034SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 5886c899ba6SSam Clegg report_fatal_error("symbol not found in symbol index space: " + 58960ec3034SSam Clegg RelEntry.Symbol->getName()); 59060ec3034SSam Clegg return SymbolIndices[RelEntry.Symbol]; 591acd7d2b0SSam Clegg } 592acd7d2b0SSam Clegg 593d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 594d934cb88SDan Gohman // directly. 595acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 596acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 597acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 598d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 599d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 600d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 601d934cb88SDan Gohman RelEntry.Offset; 602d934cb88SDan Gohman 603b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 60460ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 60560ec3034SSam Clegg 606acd7d2b0SSam Clegg switch (RelEntry.Type) { 607acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6089d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 60960ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 61060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 611d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 612d934cb88SDan Gohman break; 61360ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 61460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 615d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 616d934cb88SDan Gohman break; 61760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 61860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 61960ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 62060ec3034SSam Clegg break; 621d934cb88SDan Gohman default: 6229d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 623d934cb88SDan Gohman } 624d934cb88SDan Gohman } 62518eafb6cSDan Gohman } 62618eafb6cSDan Gohman 627acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will 628970d02c4SDan Gohman // need to handle. 629acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations( 6307c395943SSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 631acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 632acd7d2b0SSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 633970d02c4SDan Gohman 634acd7d2b0SSam Clegg uint64_t Offset = RelEntry.Offset + 6357c395943SSam Clegg RelEntry.FixupSection->getSectionOffset(); 636acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 637970d02c4SDan Gohman 63803e101f1SSam Clegg write8(RelEntry.Type); 639970d02c4SDan Gohman encodeULEB128(Offset, Stream); 640acd7d2b0SSam Clegg encodeULEB128(Index, Stream); 641acd7d2b0SSam Clegg if (RelEntry.hasAddend()) 642acd7d2b0SSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 643970d02c4SDan Gohman } 644970d02c4SDan Gohman } 645970d02c4SDan Gohman 6469e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 647457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6489e15f359SSam Clegg if (FunctionTypes.empty()) 6499e15f359SSam Clegg return; 6509e15f359SSam Clegg 6519e15f359SSam Clegg SectionBookkeeping Section; 6529e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6539e15f359SSam Clegg 6549e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6559e15f359SSam Clegg 6569e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 65703e101f1SSam Clegg write8(wasm::WASM_TYPE_FUNC); 6589e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6599e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6609e15f359SSam Clegg writeValueType(Ty); 6619e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6629e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6639e15f359SSam Clegg writeValueType(Ty); 6649e15f359SSam Clegg } 6659e15f359SSam Clegg 6669e15f359SSam Clegg endSection(Section); 6679e15f359SSam Clegg } 6689e15f359SSam Clegg 6698defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 670f950b24aSSam Clegg uint32_t DataSize, 671f950b24aSSam Clegg uint32_t NumElements) { 6729e15f359SSam Clegg if (Imports.empty()) 6739e15f359SSam Clegg return; 6749e15f359SSam Clegg 675f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 676f950b24aSSam Clegg 6779e15f359SSam Clegg SectionBookkeeping Section; 6789e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 6799e15f359SSam Clegg 6809e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 6818defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 6828defa952SSam Clegg writeString(Import.Module); 6838defa952SSam Clegg writeString(Import.Field); 68403e101f1SSam Clegg write8(Import.Kind); 6859e15f359SSam Clegg 6869e15f359SSam Clegg switch (Import.Kind) { 6879e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 6888defa952SSam Clegg encodeULEB128(Import.SigIndex, getStream()); 6899e15f359SSam Clegg break; 6909e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 69103e101f1SSam Clegg write8(Import.Global.Type); 69203e101f1SSam Clegg write8(Import.Global.Mutable ? 1 : 0); 6939e15f359SSam Clegg break; 694f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 695f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 696f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 697f950b24aSSam Clegg break; 698f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 69903e101f1SSam Clegg write8(Import.Table.ElemType); 700f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 701f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 702f950b24aSSam Clegg break; 7039e15f359SSam Clegg default: 7049e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7059e15f359SSam Clegg } 7069e15f359SSam Clegg } 7079e15f359SSam Clegg 7089e15f359SSam Clegg endSection(Section); 7099e15f359SSam Clegg } 7109e15f359SSam Clegg 711457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7129e15f359SSam Clegg if (Functions.empty()) 7139e15f359SSam Clegg return; 7149e15f359SSam Clegg 7159e15f359SSam Clegg SectionBookkeeping Section; 7169e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7179e15f359SSam Clegg 7189e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7199e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7209e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7219e15f359SSam Clegg 7229e15f359SSam Clegg endSection(Section); 7239e15f359SSam Clegg } 7249e15f359SSam Clegg 7257c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7269e15f359SSam Clegg if (Globals.empty()) 7279e15f359SSam Clegg return; 7289e15f359SSam Clegg 7299e15f359SSam Clegg SectionBookkeeping Section; 7309e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7319e15f359SSam Clegg 7329e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7339e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7346e7f1826SSam Clegg writeValueType(static_cast<wasm::ValType>(Global.Type.Type)); 7356e7f1826SSam Clegg write8(Global.Type.Mutable); 7369e15f359SSam Clegg 7379e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7386e7f1826SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); 7399e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7409e15f359SSam Clegg } 7419e15f359SSam Clegg 7429e15f359SSam Clegg endSection(Section); 7439e15f359SSam Clegg } 7449e15f359SSam Clegg 7458defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 7469e15f359SSam Clegg if (Exports.empty()) 7479e15f359SSam Clegg return; 7489e15f359SSam Clegg 7499e15f359SSam Clegg SectionBookkeeping Section; 7509e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7519e15f359SSam Clegg 7529e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7538defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 7548defa952SSam Clegg writeString(Export.Name); 75503e101f1SSam Clegg write8(Export.Kind); 7569e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7579e15f359SSam Clegg } 7589e15f359SSam Clegg 7599e15f359SSam Clegg endSection(Section); 7609e15f359SSam Clegg } 7619e15f359SSam Clegg 762457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7639e15f359SSam Clegg if (TableElems.empty()) 7649e15f359SSam Clegg return; 7659e15f359SSam Clegg 7669e15f359SSam Clegg SectionBookkeeping Section; 7679e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 7689e15f359SSam Clegg 7699e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 7709e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 7719e15f359SSam Clegg 7729e15f359SSam Clegg // init expr for starting offset 7739e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 77430e1bbc1SSam Clegg encodeSLEB128(kInitialTableOffset, getStream()); 7759e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7769e15f359SSam Clegg 7779e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 7789e15f359SSam Clegg for (uint32_t Elem : TableElems) 7799e15f359SSam Clegg encodeULEB128(Elem, getStream()); 7809e15f359SSam Clegg 7819e15f359SSam Clegg endSection(Section); 7829e15f359SSam Clegg } 7839e15f359SSam Clegg 784457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 785457fb0b4SSam Clegg const MCAsmLayout &Layout, 786457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 7879e15f359SSam Clegg if (Functions.empty()) 7889e15f359SSam Clegg return; 7899e15f359SSam Clegg 7909e15f359SSam Clegg SectionBookkeeping Section; 7919e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 7929e15f359SSam Clegg 7939e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7949e15f359SSam Clegg 7959e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 796fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 7979e15f359SSam Clegg 7989e15f359SSam Clegg int64_t Size = 0; 7999e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8009e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8019e15f359SSam Clegg 8029e15f359SSam Clegg encodeULEB128(Size, getStream()); 803fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8049e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8059e15f359SSam Clegg } 8069e15f359SSam Clegg 8079e15f359SSam Clegg // Apply fixups. 808acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8099e15f359SSam Clegg 8109e15f359SSam Clegg endSection(Section); 8119e15f359SSam Clegg } 8129e15f359SSam Clegg 8136c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 8146c899ba6SSam Clegg if (DataSegments.empty()) 8157c395943SSam Clegg return; 8169e15f359SSam Clegg 8179e15f359SSam Clegg SectionBookkeeping Section; 8189e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8199e15f359SSam Clegg 8206c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); // count 8217c395943SSam Clegg 8226c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 8239e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8249e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8257c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8269e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8277c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8287c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8297c395943SSam Clegg writeBytes(Segment.Data); // data 8307c395943SSam Clegg } 8319e15f359SSam Clegg 8329e15f359SSam Clegg // Apply fixups. 8337c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8349e15f359SSam Clegg 8359e15f359SSam Clegg endSection(Section); 8369e15f359SSam Clegg } 8379e15f359SSam Clegg 838acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() { 8399e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8409e15f359SSam Clegg // for descriptions of the reloc sections. 8419e15f359SSam Clegg 8429e15f359SSam Clegg if (CodeRelocations.empty()) 8439e15f359SSam Clegg return; 8449e15f359SSam Clegg 8459e15f359SSam Clegg SectionBookkeeping Section; 8469e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 8479e15f359SSam Clegg 8489e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_CODE, getStream()); 849acd7d2b0SSam Clegg encodeULEB128(CodeRelocations.size(), getStream()); 8509e15f359SSam Clegg 8517c395943SSam Clegg writeRelocations(CodeRelocations); 8529e15f359SSam Clegg 8539e15f359SSam Clegg endSection(Section); 8549e15f359SSam Clegg } 8559e15f359SSam Clegg 8567c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() { 8579e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8589e15f359SSam Clegg // for descriptions of the reloc sections. 8599e15f359SSam Clegg 8609e15f359SSam Clegg if (DataRelocations.empty()) 8619e15f359SSam Clegg return; 8629e15f359SSam Clegg 8639e15f359SSam Clegg SectionBookkeeping Section; 8649e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 8659e15f359SSam Clegg 8669e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_DATA, getStream()); 8679e15f359SSam Clegg encodeULEB128(DataRelocations.size(), getStream()); 8689e15f359SSam Clegg 8697c395943SSam Clegg writeRelocations(DataRelocations); 8709e15f359SSam Clegg 8719e15f359SSam Clegg endSection(Section); 8729e15f359SSam Clegg } 8739e15f359SSam Clegg 8749e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 87586b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 876ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 877ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 8789e15f359SSam Clegg SectionBookkeeping Section; 8799e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); 880b7787fd0SSam Clegg SectionBookkeeping SubSection; 8819e15f359SSam Clegg 8826c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 8836c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 8846c899ba6SSam Clegg encodeULEB128(SymbolInfos.size(), getStream()); 8856c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 8866c899ba6SSam Clegg encodeULEB128(Sym.Kind, getStream()); 8876c899ba6SSam Clegg encodeULEB128(Sym.Flags, getStream()); 8886c899ba6SSam Clegg switch (Sym.Kind) { 8896c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 8906c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 8916c899ba6SSam Clegg encodeULEB128(Sym.ElementIndex, getStream()); 8926c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) 8936c899ba6SSam Clegg writeString(Sym.Name); 8946c899ba6SSam Clegg break; 8956c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 8966c899ba6SSam Clegg writeString(Sym.Name); 8976c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 8986c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Segment, getStream()); 8996c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Offset, getStream()); 9006c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Size, getStream()); 9016c899ba6SSam Clegg } 9026c899ba6SSam Clegg break; 9036c899ba6SSam Clegg default: 9046c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 9056c899ba6SSam Clegg } 906b7787fd0SSam Clegg } 907b7787fd0SSam Clegg endSection(SubSection); 908b7787fd0SSam Clegg } 9099e15f359SSam Clegg 9106c899ba6SSam Clegg if (DataSegments.size()) { 91163ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 9126c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); 9136c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 914d95ed959SSam Clegg writeString(Segment.Name); 91563ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 91663ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 91763ebb813SSam Clegg } 918d95ed959SSam Clegg endSection(SubSection); 919d95ed959SSam Clegg } 920d95ed959SSam Clegg 921bafe6902SSam Clegg if (!InitFuncs.empty()) { 922bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 923bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 924bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 925bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 926bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 927bafe6902SSam Clegg } 928bafe6902SSam Clegg endSection(SubSection); 929bafe6902SSam Clegg } 930bafe6902SSam Clegg 931ea7caceeSSam Clegg if (Comdats.size()) { 932ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 933ea7caceeSSam Clegg encodeULEB128(Comdats.size(), getStream()); 934ea7caceeSSam Clegg for (const auto &C : Comdats) { 935ea7caceeSSam Clegg writeString(C.first); 936ea7caceeSSam Clegg encodeULEB128(0, getStream()); // flags for future use 937ea7caceeSSam Clegg encodeULEB128(C.second.size(), getStream()); 938ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 939ea7caceeSSam Clegg encodeULEB128(Entry.Kind, getStream()); 940ea7caceeSSam Clegg encodeULEB128(Entry.Index, getStream()); 941ea7caceeSSam Clegg } 942ea7caceeSSam Clegg } 943ea7caceeSSam Clegg endSection(SubSection); 944ea7caceeSSam Clegg } 945ea7caceeSSam Clegg 9469e15f359SSam Clegg endSection(Section); 9479e15f359SSam Clegg } 9489e15f359SSam Clegg 949*cfd44a2eSSam Clegg void WasmObjectWriter::writeUserCustomSections( 950*cfd44a2eSSam Clegg ArrayRef<WasmCustomSection> CustomSections) { 951*cfd44a2eSSam Clegg for (const auto &CustomSection : CustomSections) { 952*cfd44a2eSSam Clegg SectionBookkeeping Section; 953*cfd44a2eSSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, 954*cfd44a2eSSam Clegg CustomSection.Name.str().c_str()); 955*cfd44a2eSSam Clegg writeBytes(CustomSection.Contents); 956*cfd44a2eSSam Clegg endSection(Section); 957*cfd44a2eSSam Clegg } 958*cfd44a2eSSam Clegg } 959*cfd44a2eSSam Clegg 9605e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 9615e3d33a7SSam Clegg assert(Symbol.isFunction()); 9625e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 9635e3d33a7SSam Clegg return TypeIndices[&Symbol]; 9645e3d33a7SSam Clegg } 9655e3d33a7SSam Clegg 9665e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 9675e3d33a7SSam Clegg assert(Symbol.isFunction()); 9685e3d33a7SSam Clegg 9695e3d33a7SSam Clegg WasmFunctionType F; 970aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 9715e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 9725e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 9735e3d33a7SSam Clegg 9745e3d33a7SSam Clegg auto Pair = 9755e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 9765e3d33a7SSam Clegg if (Pair.second) 9775e3d33a7SSam Clegg FunctionTypes.push_back(F); 9785e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 9795e3d33a7SSam Clegg 9805e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 9815e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 9825e3d33a7SSam Clegg return Pair.first->second; 9835e3d33a7SSam Clegg } 9845e3d33a7SSam Clegg 98518eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 98618eafb6cSDan Gohman const MCAsmLayout &Layout) { 987b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 98882607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 989d934cb88SDan Gohman 990d934cb88SDan Gohman // Collect information from the available symbols. 991d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 992d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 9938defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 9948defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 9956c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 996bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 997ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 9987c395943SSam Clegg uint32_t DataSize = 0; 999d934cb88SDan Gohman 1000f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1001f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1002f950b24aSSam Clegg // it if there are no loads or stores. 1003f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1004f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 10058defa952SSam Clegg wasm::WasmImport MemImport; 10068defa952SSam Clegg MemImport.Module = MemorySym->getModuleName(); 10078defa952SSam Clegg MemImport.Field = MemorySym->getName(); 1008f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1009f950b24aSSam Clegg Imports.push_back(MemImport); 1010f950b24aSSam Clegg 1011f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1012f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1013f950b24aSSam Clegg // it if there are no indirect calls. 1014f950b24aSSam Clegg MCSymbolWasm *TableSym = 1015f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 10168defa952SSam Clegg wasm::WasmImport TableImport; 10178defa952SSam Clegg TableImport.Module = TableSym->getModuleName(); 10188defa952SSam Clegg TableImport.Field = TableSym->getName(); 1019f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 10208defa952SSam Clegg TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC; 1021f950b24aSSam Clegg Imports.push_back(TableImport); 1022f950b24aSSam Clegg 1023586320c0SNicholas Wilson // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined 1024586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1025586320c0SNicholas Wilson // symbols. 102632ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 102732ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 102832ce5ca0SDan Gohman 102932ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 10309f3fe42eSSam Clegg // (because wasm always needs a type signature). 103132ce5ca0SDan Gohman if (WS.isFunction()) 103232ce5ca0SDan Gohman registerFunctionType(WS); 103332ce5ca0SDan Gohman 103432ce5ca0SDan Gohman if (WS.isTemporary()) 103532ce5ca0SDan Gohman continue; 103632ce5ca0SDan Gohman 103732ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 10386c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 10396c899ba6SSam Clegg if (WS.isFunction()) { 10408defa952SSam Clegg wasm::WasmImport Import; 10418defa952SSam Clegg Import.Module = WS.getModuleName(); 10428defa952SSam Clegg Import.Field = WS.getName(); 104332ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 10448defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 10456c899ba6SSam Clegg Imports.push_back(Import); 10466c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 10476c899ba6SSam Clegg } else if (WS.isGlobal()) { 104815f349f7SNicholas Wilson if (WS.isWeak()) 104915f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 105015f349f7SNicholas Wilson 10516c899ba6SSam Clegg wasm::WasmImport Import; 10526c899ba6SSam Clegg Import.Module = WS.getModuleName(); 10536c899ba6SSam Clegg Import.Field = WS.getName(); 105432ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 10556c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 10566c899ba6SSam Clegg Imports.push_back(Import); 10576c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 105832ce5ca0SDan Gohman } 105932ce5ca0SDan Gohman } 106032ce5ca0SDan Gohman } 106132ce5ca0SDan Gohman 1062586320c0SNicholas Wilson // Populate DataSegments, which must be done before populating DataLocations. 1063759631c7SSam Clegg for (MCSection &Sec : Asm) { 1064759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 1065*cfd44a2eSSam Clegg 1066*cfd44a2eSSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith( 1067*cfd44a2eSSam Clegg ".custom_section.")) { 1068*cfd44a2eSSam Clegg if (Section.getFragmentList().empty()) 1069*cfd44a2eSSam Clegg continue; 1070*cfd44a2eSSam Clegg if (Section.getFragmentList().size() != 1) 1071*cfd44a2eSSam Clegg report_fatal_error( 1072*cfd44a2eSSam Clegg "only one .custom_section section fragment supported"); 1073*cfd44a2eSSam Clegg const MCFragment &Frag = *Section.begin(); 1074*cfd44a2eSSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1075*cfd44a2eSSam Clegg report_fatal_error("only data supported in .custom_section section"); 1076*cfd44a2eSSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1077*cfd44a2eSSam Clegg if (!DataFrag.getFixups().empty()) 1078*cfd44a2eSSam Clegg report_fatal_error("fixups not supported in .custom_section section"); 1079*cfd44a2eSSam Clegg StringRef UserName = Section.getSectionName().substr(16); 1080*cfd44a2eSSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1081*cfd44a2eSSam Clegg CustomSections.push_back(WasmCustomSection(UserName, Contents)); 1082*cfd44a2eSSam Clegg continue; 1083*cfd44a2eSSam Clegg } 1084*cfd44a2eSSam Clegg 108512fd3da9SSam Clegg if (!Section.isWasmData()) 1086759631c7SSam Clegg continue; 1087759631c7SSam Clegg 1088bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 1089bafe6902SSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array")) 1090bafe6902SSam Clegg continue; 1091bafe6902SSam Clegg 1092329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1093759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1094759631c7SSam Clegg DataSegments.emplace_back(); 1095759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1096d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1097759631c7SSam Clegg Segment.Offset = DataSize; 1098759631c7SSam Clegg Segment.Section = &Section; 109963ebb813SSam Clegg addData(Segment.Data, Section); 110063ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 110163ebb813SSam Clegg Segment.Flags = 0; 1102759631c7SSam Clegg DataSize += Segment.Data.size(); 11036c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1104ea7caceeSSam Clegg 1105ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1106ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1107329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1108ea7caceeSSam Clegg } 1109759631c7SSam Clegg } 1110759631c7SSam Clegg 1111586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1112d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1113d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1114d934cb88SDan Gohman // or used in relocations. 1115d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1116d934cb88SDan Gohman continue; 1117b7787fd0SSam Clegg 1118d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1119b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1120329e76d5SSam Clegg << " isDefined=" << S.isDefined() 1121329e76d5SSam Clegg << " isExternal=" << S.isExternal() 1122329e76d5SSam Clegg << " isTemporary=" << S.isTemporary() 1123b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1124b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1125a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1126b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1127b7787fd0SSam Clegg 11285e3d33a7SSam Clegg if (WS.isVariable()) 11295e3d33a7SSam Clegg continue; 11306c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 11316c899ba6SSam Clegg continue; 1132b7787fd0SSam Clegg 1133d934cb88SDan Gohman if (WS.isFunction()) { 11346c899ba6SSam Clegg unsigned Index; 1135cd65f698SSam Clegg if (WS.isDefined()) { 1136b7787fd0SSam Clegg if (WS.getOffset() != 0) 1137b7787fd0SSam Clegg report_fatal_error( 1138b7787fd0SSam Clegg "function sections must contain one function each"); 1139b7787fd0SSam Clegg 1140b7787fd0SSam Clegg if (WS.getSize() == 0) 1141b7787fd0SSam Clegg report_fatal_error( 1142b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1143b7787fd0SSam Clegg 11446c899ba6SSam Clegg // A definition. Write out the function body. 11459f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1146d934cb88SDan Gohman WasmFunction Func; 11475e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1148d934cb88SDan Gohman Func.Sym = &WS; 11496c899ba6SSam Clegg WasmIndices[&WS] = Index; 1150d934cb88SDan Gohman Functions.push_back(Func); 11516c899ba6SSam Clegg 11526c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 11536c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 11546c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 11556c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 11566c899ba6SSam Clegg } 1157d934cb88SDan Gohman } else { 1158d934cb88SDan Gohman // An import; the index was assigned above. 11596c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1160d934cb88SDan Gohman } 1161d934cb88SDan Gohman 11625e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 11636c899ba6SSam Clegg } else if (WS.isData()) { 1164c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1165c38e947eSSam Clegg continue; 1166c38e947eSSam Clegg 11676c899ba6SSam Clegg if (!WS.isDefined()) { 11686c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: -1"); 1169fe6414b0SSam Clegg continue; 11706c899ba6SSam Clegg } 1171fe6414b0SSam Clegg 1172d934cb88SDan Gohman if (!WS.getSize()) 1173c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1174c38e947eSSam Clegg WS.getName()); 1175d934cb88SDan Gohman 1176d934cb88SDan Gohman int64_t Size = 0; 1177d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1178d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1179d934cb88SDan Gohman 1180759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1181ea7caceeSSam Clegg assert(DataSection.isWasmData()); 11827c395943SSam Clegg 11836c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 11846c899ba6SSam Clegg // corresponding Wasm data segment. 11856c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 11866c899ba6SSam Clegg DataSection.getSegmentIndex(), 11876c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 11886c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 11896c899ba6SSam Clegg DataLocations[&WS] = Ref; 11906c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: " << Ref.Segment); 11916c899ba6SSam Clegg } else { 11926c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1193545932beSEric Christopher if (WS.isDefined()) 11946c899ba6SSam Clegg report_fatal_error("don't yet support defined globals"); 11956c899ba6SSam Clegg 1196545932beSEric Christopher // An import; the index was assigned above 1197545932beSEric Christopher DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second 1198545932beSEric Christopher << "\n"); 1199d934cb88SDan Gohman } 1200d934cb88SDan Gohman } 1201d934cb88SDan Gohman 1202586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1203586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1204586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1205586320c0SNicholas Wilson // necessarily ordered in this way. 1206b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1207b7787fd0SSam Clegg if (!S.isVariable()) 1208b7787fd0SSam Clegg continue; 120931a2c809SSam Clegg 1210cd65f698SSam Clegg assert(S.isDefined()); 1211b7787fd0SSam Clegg 12125e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1213aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1214aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 12155e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 1216b7787fd0SSam Clegg 12176c899ba6SSam Clegg if (WS.isFunction()) { 12186c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 12196c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 12206c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 12216c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 12226c899ba6SSam Clegg } else if (WS.isData()) { 12236c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 12246c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 12256c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 12266c899ba6SSam Clegg DataLocations[&WS] = Ref; 12276c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 12286c899ba6SSam Clegg } else { 12296c899ba6SSam Clegg report_fatal_error("don't yet support global aliases"); 12306c899ba6SSam Clegg } 1231586320c0SNicholas Wilson } 123231a2c809SSam Clegg 1233586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1234586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1235586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 1236586320c0SNicholas Wilson if (WS.isTemporary() && WS.getName().empty()) 1237586320c0SNicholas Wilson continue; 1238586320c0SNicholas Wilson if (WS.isComdat() && !WS.isDefined()) 1239586320c0SNicholas Wilson continue; 1240586320c0SNicholas Wilson if (WS.isTemporary() && WS.isData() && !WS.getSize()) 1241586320c0SNicholas Wilson continue; 1242586320c0SNicholas Wilson 1243586320c0SNicholas Wilson uint32_t Flags = 0; 1244586320c0SNicholas Wilson if (WS.isWeak()) 1245586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1246586320c0SNicholas Wilson if (WS.isHidden()) 1247586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1248586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1249586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1250586320c0SNicholas Wilson if (WS.isUndefined()) 1251586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1252586320c0SNicholas Wilson 1253586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1254586320c0SNicholas Wilson Info.Name = WS.getName(); 1255586320c0SNicholas Wilson Info.Kind = WS.getType(); 1256586320c0SNicholas Wilson Info.Flags = Flags; 1257586320c0SNicholas Wilson if (!WS.isData()) 1258586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 1259586320c0SNicholas Wilson else if (WS.isDefined()) 1260586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 1261586320c0SNicholas Wilson SymbolIndices[&WS] = SymbolInfos.size(); 1262586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1263b7787fd0SSam Clegg } 1264b7787fd0SSam Clegg 12656006e091SSam Clegg { 12666006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1267f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1268f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1269f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1270f9edbe95SSam Clegg if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 && 1271f9edbe95SSam Clegg Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB) 1272f9edbe95SSam Clegg return; 1273f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 1274f9edbe95SSam Clegg const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol); 12756c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1276f9edbe95SSam Clegg uint32_t TableIndex = TableElems.size() + kInitialTableOffset; 1277f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1278329e76d5SSam Clegg DEBUG(dbgs() << " -> adding " << WS.getName() 1279f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 12806c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 12816006e091SSam Clegg registerFunctionType(WS); 12826006e091SSam Clegg } 12836006e091SSam Clegg }; 1284970d02c4SDan Gohman 12856006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 12866006e091SSam Clegg HandleReloc(RelEntry); 12876006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 12886006e091SSam Clegg HandleReloc(RelEntry); 1289d934cb88SDan Gohman } 1290d934cb88SDan Gohman 1291bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1292bafe6902SSam Clegg for (const MCSection &S : Asm) { 1293bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1294bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1295bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1296bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1297bafe6902SSam Clegg continue; 1298bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1299bafe6902SSam Clegg continue; 1300bafe6902SSam Clegg if (WS.getFragmentList().size() != 2) 1301bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1302bafe6902SSam Clegg const MCFragment &AlignFrag = *WS.begin(); 1303bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1304bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1305bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1306bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1307bafe6902SSam Clegg const MCFragment &Frag = *std::next(WS.begin()); 1308bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1309bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1310bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 1311bafe6902SSam Clegg if (WS.getSectionName().size() != 11) { 1312bafe6902SSam Clegg if (WS.getSectionName()[11] != '.') 1313bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 1314bafe6902SSam Clegg if (WS.getSectionName().substr(12).getAsInteger(10, Priority)) 1315bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1316bafe6902SSam Clegg } 1317bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1318bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1319bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1320bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1321bafe6902SSam Clegg p != end; ++p) { 1322bafe6902SSam Clegg if (*p != 0) 1323bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1324bafe6902SSam Clegg } 1325bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1326bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1327bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1328bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1329bafe6902SSam Clegg if (!Sym) 1330bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1331bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1332bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 1333bafe6902SSam Clegg auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol())); 1334bafe6902SSam Clegg if (I == SymbolIndices.end()) 1335bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be defined"); 1336bafe6902SSam Clegg uint32_t Index = I->second; 1337bafe6902SSam Clegg InitFuncs.push_back(std::make_pair(Priority, Index)); 1338bafe6902SSam Clegg } 1339bafe6902SSam Clegg } 1340bafe6902SSam Clegg 134118eafb6cSDan Gohman // Write out the Wasm header. 134218eafb6cSDan Gohman writeHeader(Asm); 134318eafb6cSDan Gohman 13449e15f359SSam Clegg writeTypeSection(FunctionTypes); 1345f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 13469e15f359SSam Clegg writeFunctionSection(Functions); 1347f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1348f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 13497c395943SSam Clegg writeGlobalSection(); 13509e15f359SSam Clegg writeExportSection(Exports); 13519e15f359SSam Clegg writeElemSection(TableElems); 1352acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 13536c899ba6SSam Clegg writeDataSection(); 1354*cfd44a2eSSam Clegg writeUserCustomSections(CustomSections); 1355c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 1356acd7d2b0SSam Clegg writeCodeRelocSection(); 13577c395943SSam Clegg writeDataRelocSection(); 1358970d02c4SDan Gohman 1359d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1360d934cb88SDan Gohman // TODO: Translate debug sections to the output. 136118eafb6cSDan Gohman } 136218eafb6cSDan Gohman 136360fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 13641301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 136518eafb6cSDan Gohman raw_pwrite_stream &OS) { 13660917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 136718eafb6cSDan Gohman } 1368