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 import to be written into the import section. 1159e15f359SSam Clegg struct WasmImport { 1169e15f359SSam Clegg StringRef ModuleName; 1179e15f359SSam Clegg StringRef FieldName; 1189e15f359SSam Clegg unsigned Kind; 1199e15f359SSam Clegg int32_t Type; 12032ce5ca0SDan Gohman bool IsMutable; 1219e15f359SSam Clegg }; 1229e15f359SSam Clegg 1239e15f359SSam Clegg // A wasm function to be written into the function section. 1249e15f359SSam Clegg struct WasmFunction { 1259e15f359SSam Clegg int32_t Type; 1269e15f359SSam Clegg const MCSymbolWasm *Sym; 1279e15f359SSam Clegg }; 1289e15f359SSam Clegg 1299e15f359SSam Clegg // A wasm export to be written into the export section. 1309e15f359SSam Clegg struct WasmExport { 1319e15f359SSam Clegg StringRef FieldName; 1329e15f359SSam Clegg unsigned Kind; 1339e15f359SSam Clegg uint32_t Index; 1349e15f359SSam Clegg }; 1359e15f359SSam Clegg 1369e15f359SSam Clegg // A wasm global to be written into the global section. 1379e15f359SSam Clegg struct WasmGlobal { 1389e15f359SSam Clegg wasm::ValType Type; 1399e15f359SSam Clegg bool IsMutable; 1409e15f359SSam Clegg bool HasImport; 1419e15f359SSam Clegg uint64_t InitialValue; 1429e15f359SSam Clegg uint32_t ImportIndex; 1439e15f359SSam Clegg }; 1449e15f359SSam Clegg 145ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT. For each data 146ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding 147ea7caceeSSam Clegg // WasmComdatEntry. 148ea7caceeSSam Clegg struct WasmComdatEntry { 149ea7caceeSSam Clegg unsigned Kind; 150ea7caceeSSam Clegg uint32_t Index; 151ea7caceeSSam Clegg }; 152ea7caceeSSam Clegg 1536dc65e91SSam Clegg // Information about a single relocation. 1546dc65e91SSam Clegg struct WasmRelocationEntry { 1556dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1566dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1576dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1586dc65e91SSam Clegg unsigned Type; // The type of the relocation. 159fe6414b0SSam Clegg const MCSectionWasm *FixupSection;// The section the relocation is targeting. 1606dc65e91SSam Clegg 1616dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1626dc65e91SSam Clegg int64_t Addend, unsigned Type, 163fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1646dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1656dc65e91SSam Clegg FixupSection(FixupSection) {} 1666dc65e91SSam Clegg 167acd7d2b0SSam Clegg bool hasAddend() const { 168acd7d2b0SSam Clegg switch (Type) { 16913a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 17013a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 17113a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 172acd7d2b0SSam Clegg return true; 173acd7d2b0SSam Clegg default: 174acd7d2b0SSam Clegg return false; 175acd7d2b0SSam Clegg } 176acd7d2b0SSam Clegg } 177acd7d2b0SSam Clegg 1786dc65e91SSam Clegg void print(raw_ostream &Out) const { 1799bf73c07SSam Clegg Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 180759631c7SSam Clegg << ", Type=" << Type 181759631c7SSam Clegg << ", FixupSection=" << FixupSection->getSectionName(); 1826dc65e91SSam Clegg } 183b7787fd0SSam Clegg 184615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 185b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 186b7787fd0SSam Clegg #endif 1876dc65e91SSam Clegg }; 1886dc65e91SSam Clegg 1891fb8daa6SSam Clegg #if !defined(NDEBUG) 1907f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 191b7787fd0SSam Clegg Rel.print(OS); 192b7787fd0SSam Clegg return OS; 193b7787fd0SSam Clegg } 1941fb8daa6SSam Clegg #endif 195b7787fd0SSam Clegg 19618eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 19718eafb6cSDan Gohman /// The target specific Wasm writer instance. 19818eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 19918eafb6cSDan Gohman 200d934cb88SDan Gohman // Relocations for fixing up references in the code section. 201d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 202d934cb88SDan Gohman 203d934cb88SDan Gohman // Relocations for fixing up references in the data section. 204d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 205d934cb88SDan Gohman 206d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 207acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 208acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 209d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 210d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 211d99f6078SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices; 212d99f6078SSam Clegg // Maps function/global symbols to the function/global index space. 213acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 214acd7d2b0SSam Clegg 215acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 216acd7d2b0SSam Clegg FunctionTypeIndices; 2175e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2187c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2199f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2207c395943SSam Clegg unsigned NumGlobalImports = 0; 221d934cb88SDan Gohman 22218eafb6cSDan Gohman // TargetObjectWriter wrappers. 22318eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 224ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 225ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 22618eafb6cSDan Gohman } 22718eafb6cSDan Gohman 228d934cb88SDan Gohman void startSection(SectionBookkeeping &Section, unsigned SectionId, 229d934cb88SDan Gohman const char *Name = nullptr); 230d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 231d934cb88SDan Gohman 23218eafb6cSDan Gohman public: 2331301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2341301a878SLang Hames raw_pwrite_stream &OS) 2351301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2361301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 23718eafb6cSDan Gohman 23818eafb6cSDan Gohman ~WasmObjectWriter() override; 23918eafb6cSDan Gohman 2400917c9e4SDan Gohman private: 241acd7d2b0SSam Clegg void reset() override { 242acd7d2b0SSam Clegg CodeRelocations.clear(); 243acd7d2b0SSam Clegg DataRelocations.clear(); 244acd7d2b0SSam Clegg TypeIndices.clear(); 245acd7d2b0SSam Clegg SymbolIndices.clear(); 246d99f6078SSam Clegg IndirectSymbolIndices.clear(); 247acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2485e3d33a7SSam Clegg FunctionTypes.clear(); 2497c395943SSam Clegg Globals.clear(); 250acd7d2b0SSam Clegg MCObjectWriter::reset(); 2519f3fe42eSSam Clegg NumFunctionImports = 0; 2527c395943SSam Clegg NumGlobalImports = 0; 253acd7d2b0SSam Clegg } 254acd7d2b0SSam Clegg 25518eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 25618eafb6cSDan Gohman 25718eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 25818eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 259ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 26018eafb6cSDan Gohman 26118eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 26218eafb6cSDan Gohman const MCAsmLayout &Layout) override; 26318eafb6cSDan Gohman 26418eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2659e15f359SSam Clegg 266b7787fd0SSam Clegg void writeString(const StringRef Str) { 267b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 268b7787fd0SSam Clegg writeBytes(Str); 269b7787fd0SSam Clegg } 270b7787fd0SSam Clegg 2719e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 2729e15f359SSam Clegg encodeSLEB128(int32_t(Ty), getStream()); 2739e15f359SSam Clegg } 2749e15f359SSam Clegg 275457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 276f950b24aSSam Clegg void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize, 277f950b24aSSam Clegg uint32_t NumElements); 278457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 2797c395943SSam Clegg void writeGlobalSection(); 280457fb0b4SSam Clegg void writeExportSection(ArrayRef<WasmExport> Exports); 281457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 2829e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 283457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 284457fb0b4SSam Clegg void writeDataSection(ArrayRef<WasmDataSegment> Segments); 285acd7d2b0SSam Clegg void writeCodeRelocSection(); 2867c395943SSam Clegg void writeDataRelocSection(); 28731a2c809SSam Clegg void writeLinkingMetaDataSection( 28831a2c809SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 289ea7caceeSSam Clegg ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags, 290ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 291ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats); 292acd7d2b0SSam Clegg 2937c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 294acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 295acd7d2b0SSam Clegg uint64_t ContentsOffset); 296acd7d2b0SSam Clegg 2977c395943SSam Clegg void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations); 298acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 2995e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm& Symbol); 3005e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm& Symbol); 30118eafb6cSDan Gohman }; 3029e15f359SSam Clegg 30318eafb6cSDan Gohman } // end anonymous namespace 30418eafb6cSDan Gohman 30518eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 30618eafb6cSDan Gohman 307d934cb88SDan Gohman // Write out a section header and a patchable section size field. 308d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 309d934cb88SDan Gohman unsigned SectionId, 310d934cb88SDan Gohman const char *Name) { 311d934cb88SDan Gohman assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 312d934cb88SDan Gohman "Only custom sections can have names"); 313d934cb88SDan Gohman 314b7787fd0SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n"); 315e2688c43SDerek Schuff encodeULEB128(SectionId, getStream()); 316d934cb88SDan Gohman 317d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 318d934cb88SDan Gohman 319d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 320d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 321d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 322d934cb88SDan Gohman 323d934cb88SDan Gohman // The position where the section starts, for measuring its size. 324d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 325d934cb88SDan Gohman 326d934cb88SDan Gohman // Custom sections in wasm also have a string identifier. 327d934cb88SDan Gohman if (SectionId == wasm::WASM_SEC_CUSTOM) { 328b7787fd0SSam Clegg assert(Name); 329b7787fd0SSam Clegg writeString(StringRef(Name)); 330d934cb88SDan Gohman } 331d934cb88SDan Gohman } 332d934cb88SDan Gohman 333d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 334d934cb88SDan Gohman // section size field at the start of the section. 335d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 336d934cb88SDan Gohman uint64_t Size = getStream().tell() - Section.ContentsOffset; 337d934cb88SDan Gohman if (uint32_t(Size) != Size) 338d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 339d934cb88SDan Gohman 340b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 341d934cb88SDan Gohman 342d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 343d934cb88SDan Gohman // the section id byte. 344d934cb88SDan Gohman uint8_t Buffer[16]; 34566a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 346d934cb88SDan Gohman assert(SizeLen == 5); 347d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 348d934cb88SDan Gohman } 349d934cb88SDan Gohman 35018eafb6cSDan Gohman // Emit the Wasm header. 35118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3527ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3537ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 35418eafb6cSDan Gohman } 35518eafb6cSDan Gohman 35618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 35718eafb6cSDan Gohman const MCAsmLayout &Layout) { 35818eafb6cSDan Gohman } 35918eafb6cSDan Gohman 36018eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 36118eafb6cSDan Gohman const MCAsmLayout &Layout, 36218eafb6cSDan Gohman const MCFragment *Fragment, 36318eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 364ceecfe5bSRafael Espindola uint64_t &FixedValue) { 365ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 366ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 367ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 368fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 369d934cb88SDan Gohman uint64_t C = Target.getConstant(); 370d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 371d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 372d934cb88SDan Gohman 373bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 374bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 375bafe6902SSam Clegg return; 376bafe6902SSam Clegg 377d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 378d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 379d934cb88SDan Gohman "Should not have constructed this"); 380d934cb88SDan Gohman 381d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 382d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 383d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 384d934cb88SDan Gohman 385d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 386d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 387d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 388d934cb88SDan Gohman if (IsPCRel) { 389d934cb88SDan Gohman Ctx.reportError( 390d934cb88SDan Gohman Fixup.getLoc(), 391d934cb88SDan Gohman "No relocation available to represent this relative expression"); 392d934cb88SDan Gohman return; 393d934cb88SDan Gohman } 394d934cb88SDan Gohman 395d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 396d934cb88SDan Gohman 397d934cb88SDan Gohman if (SymB.isUndefined()) { 398d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 399d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 400d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 401d934cb88SDan Gohman return; 402d934cb88SDan Gohman } 403d934cb88SDan Gohman 404d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 405d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 406d934cb88SDan Gohman if (&SecB != &FixupSection) { 407d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 408d934cb88SDan Gohman "Cannot represent a difference across sections"); 409d934cb88SDan Gohman return; 410d934cb88SDan Gohman } 411d934cb88SDan Gohman 412d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 413d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 414d934cb88SDan Gohman IsPCRel = true; 415d934cb88SDan Gohman C -= K; 416d934cb88SDan Gohman } 417d934cb88SDan Gohman 418d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 419d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 420d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 421d934cb88SDan Gohman 422d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 423d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4246ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4256ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4266ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 427d934cb88SDan Gohman } 428d934cb88SDan Gohman 429d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 430d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 431d934cb88SDan Gohman // be negative and don't wrap. 432d934cb88SDan Gohman FixedValue = 0; 433d934cb88SDan Gohman 4346ad8f190SSam Clegg if (SymA) 435d934cb88SDan Gohman SymA->setUsedInReloc(); 436d934cb88SDan Gohman 437ae03c1e7SSam Clegg assert(!IsPCRel); 4389d24fb7fSSam Clegg assert(SymA); 4399d24fb7fSSam Clegg 440ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 441ae03c1e7SSam Clegg 442d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 443b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 444d934cb88SDan Gohman 44512fd3da9SSam Clegg if (FixupSection.isWasmData()) 446d934cb88SDan Gohman DataRelocations.push_back(Rec); 44712fd3da9SSam Clegg else if (FixupSection.getKind().isText()) 44812fd3da9SSam Clegg CodeRelocations.push_back(Rec); 44912fd3da9SSam Clegg else if (!FixupSection.getKind().isMetadata()) 45012fd3da9SSam Clegg // TODO(sbc): Add support for debug sections. 45112fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 452d934cb88SDan Gohman } 453d934cb88SDan Gohman 454d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 455d934cb88SDan Gohman // to allow patching. 456d934cb88SDan Gohman static void 457d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 458d934cb88SDan Gohman uint8_t Buffer[5]; 45966a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 460d934cb88SDan Gohman assert(SizeLen == 5); 461d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 462d934cb88SDan Gohman } 463d934cb88SDan Gohman 464d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 465d934cb88SDan Gohman // to allow patching. 466d934cb88SDan Gohman static void 467d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 468d934cb88SDan Gohman uint8_t Buffer[5]; 46966a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(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 a plain integer value at offset Offset in Stream. 475d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 476d934cb88SDan Gohman uint8_t Buffer[4]; 477d934cb88SDan Gohman support::endian::write32le(Buffer, X); 478d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 479d934cb88SDan Gohman } 480d934cb88SDan Gohman 481aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 482aff1c4dfSSam Clegg if (Symbol.isVariable()) { 483aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 484aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 485aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 486aff1c4dfSSam Clegg } 487aff1c4dfSSam Clegg return &Symbol; 488aff1c4dfSSam Clegg } 489aff1c4dfSSam Clegg 490d934cb88SDan Gohman // Compute a value to write into the code at the location covered 49160ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 49260ec3034SSam Clegg // to make the object format more readable and more likely to be directly 49360ec3034SSam Clegg // useable. 4947c395943SSam Clegg uint32_t 4957c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 496d934cb88SDan Gohman 49760ec3034SSam Clegg switch (RelEntry.Type) { 49860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 49960ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 50060ec3034SSam Clegg // Provitional value is the indirect symbol index 50160ec3034SSam Clegg if (!IndirectSymbolIndices.count(RelEntry.Symbol)) 50260ec3034SSam Clegg report_fatal_error("symbol not found in table index space: " + 50360ec3034SSam Clegg RelEntry.Symbol->getName()); 50460ec3034SSam Clegg return IndirectSymbolIndices[RelEntry.Symbol]; 50560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 50660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 50760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 50860ec3034SSam Clegg // Provitional value is function/type/global index itself 50960ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 51060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 51160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 51260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 51360ec3034SSam Clegg // Provitional value is address of the global 51460ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 515270ed1b3SSam Clegg // For undefined symbols, use zero 516cd65f698SSam Clegg if (!Sym->isDefined()) 517270ed1b3SSam Clegg return 0; 518d934cb88SDan Gohman 5197c395943SSam Clegg uint32_t GlobalIndex = SymbolIndices[Sym]; 5207c395943SSam Clegg const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports]; 5217c395943SSam Clegg uint64_t Address = Global.InitialValue + RelEntry.Addend; 522d934cb88SDan Gohman 523d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 52460ec3034SSam Clegg return Address; 52560ec3034SSam Clegg } 52660ec3034SSam Clegg default: 52760ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 52860ec3034SSam Clegg } 529d934cb88SDan Gohman } 530d934cb88SDan Gohman 531759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 53263ebb813SSam Clegg MCSectionWasm &DataSection) { 533759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 534759631c7SSam Clegg 53563ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 53663ebb813SSam Clegg 537c55d13f4SSam Clegg size_t LastFragmentSize = 0; 538759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 539759631c7SSam Clegg if (Frag.hasInstructions()) 540759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 541759631c7SSam Clegg 542759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 543759631c7SSam Clegg if (Align->getValueSize() != 1) 544759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 545759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 546759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 547759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 548759631c7SSam Clegg Align->getAlignment()), 549759631c7SSam Clegg DataBytes.size() + 550759631c7SSam Clegg Align->getMaxBytesToEmit()); 551759631c7SSam Clegg DataBytes.resize(Size, Value); 552759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 553d707c370SRafael Espindola int64_t Size; 554d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 555d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 556d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 557759631c7SSam Clegg } else { 558759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 559759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 560759631c7SSam Clegg 561759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 562c55d13f4SSam Clegg LastFragmentSize = Contents.size(); 563759631c7SSam Clegg } 564759631c7SSam Clegg } 565759631c7SSam Clegg 566c55d13f4SSam Clegg // Don't allow empty segments, or segments that end with zero-sized 567c55d13f4SSam Clegg // fragment, otherwise the linker cannot map symbols to a unique 568c55d13f4SSam Clegg // data segment. This can be triggered by zero-sized structs 569c55d13f4SSam Clegg // See: test/MC/WebAssembly/bss.ll 570c55d13f4SSam Clegg if (LastFragmentSize == 0) 571c55d13f4SSam Clegg DataBytes.resize(DataBytes.size() + 1); 572759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 573759631c7SSam Clegg } 574759631c7SSam Clegg 57560ec3034SSam Clegg uint32_t 57660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 57760ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 578b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 579b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 580b7787fd0SSam Clegg RelEntry.Symbol->getName()); 581acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 582acd7d2b0SSam Clegg } 58360ec3034SSam Clegg 58460ec3034SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 58560ec3034SSam Clegg report_fatal_error("symbol not found in function/global index space: " + 58660ec3034SSam Clegg RelEntry.Symbol->getName()); 58760ec3034SSam Clegg return SymbolIndices[RelEntry.Symbol]; 588acd7d2b0SSam Clegg } 589acd7d2b0SSam Clegg 590d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 591d934cb88SDan Gohman // directly. 592acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 593acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 594acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 595d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 596d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 597d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 598d934cb88SDan Gohman RelEntry.Offset; 599d934cb88SDan Gohman 600b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 60160ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 60260ec3034SSam Clegg 603acd7d2b0SSam Clegg switch (RelEntry.Type) { 604acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6059d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 60660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 60760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 608d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 609d934cb88SDan Gohman break; 61060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 61160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 612d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 613d934cb88SDan Gohman break; 61460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 61560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 61660ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 61760ec3034SSam Clegg break; 618d934cb88SDan Gohman default: 6199d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 620d934cb88SDan Gohman } 621d934cb88SDan Gohman } 62218eafb6cSDan Gohman } 62318eafb6cSDan Gohman 624acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will 625970d02c4SDan Gohman // need to handle. 626acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations( 6277c395943SSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 628acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 629acd7d2b0SSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 630970d02c4SDan Gohman 631acd7d2b0SSam Clegg uint64_t Offset = RelEntry.Offset + 6327c395943SSam Clegg RelEntry.FixupSection->getSectionOffset(); 633acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 634970d02c4SDan Gohman 635acd7d2b0SSam Clegg encodeULEB128(RelEntry.Type, Stream); 636970d02c4SDan Gohman encodeULEB128(Offset, Stream); 637acd7d2b0SSam Clegg encodeULEB128(Index, Stream); 638acd7d2b0SSam Clegg if (RelEntry.hasAddend()) 639acd7d2b0SSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 640970d02c4SDan Gohman } 641970d02c4SDan Gohman } 642970d02c4SDan Gohman 6439e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 644457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6459e15f359SSam Clegg if (FunctionTypes.empty()) 6469e15f359SSam Clegg return; 6479e15f359SSam Clegg 6489e15f359SSam Clegg SectionBookkeeping Section; 6499e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6509e15f359SSam Clegg 6519e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6529e15f359SSam Clegg 6539e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 6549e15f359SSam Clegg encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream()); 6559e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6569e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6579e15f359SSam Clegg writeValueType(Ty); 6589e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6599e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6609e15f359SSam Clegg writeValueType(Ty); 6619e15f359SSam Clegg } 6629e15f359SSam Clegg 6639e15f359SSam Clegg endSection(Section); 6649e15f359SSam Clegg } 6659e15f359SSam Clegg 666f950b24aSSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports, 667f950b24aSSam Clegg uint32_t DataSize, 668f950b24aSSam Clegg uint32_t NumElements) { 6699e15f359SSam Clegg if (Imports.empty()) 6709e15f359SSam Clegg return; 6719e15f359SSam Clegg 672f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 673f950b24aSSam Clegg 6749e15f359SSam Clegg SectionBookkeeping Section; 6759e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 6769e15f359SSam Clegg 6779e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 6789e15f359SSam Clegg for (const WasmImport &Import : Imports) { 679b7787fd0SSam Clegg writeString(Import.ModuleName); 680b7787fd0SSam Clegg writeString(Import.FieldName); 6819e15f359SSam Clegg 6829e15f359SSam Clegg encodeULEB128(Import.Kind, getStream()); 6839e15f359SSam Clegg 6849e15f359SSam Clegg switch (Import.Kind) { 6859e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 6869e15f359SSam Clegg encodeULEB128(Import.Type, getStream()); 6879e15f359SSam Clegg break; 6889e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 6899e15f359SSam Clegg encodeSLEB128(int32_t(Import.Type), getStream()); 69032ce5ca0SDan Gohman encodeULEB128(int32_t(Import.IsMutable), getStream()); 6919e15f359SSam Clegg break; 692f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 693f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 694f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 695f950b24aSSam Clegg break; 696f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 697f950b24aSSam Clegg encodeSLEB128(int32_t(Import.Type), getStream()); 698f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 699f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 700f950b24aSSam Clegg break; 7019e15f359SSam Clegg default: 7029e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7039e15f359SSam Clegg } 7049e15f359SSam Clegg } 7059e15f359SSam Clegg 7069e15f359SSam Clegg endSection(Section); 7079e15f359SSam Clegg } 7089e15f359SSam Clegg 709457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7109e15f359SSam Clegg if (Functions.empty()) 7119e15f359SSam Clegg return; 7129e15f359SSam Clegg 7139e15f359SSam Clegg SectionBookkeeping Section; 7149e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7159e15f359SSam Clegg 7169e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7179e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7189e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7199e15f359SSam Clegg 7209e15f359SSam Clegg endSection(Section); 7219e15f359SSam Clegg } 7229e15f359SSam Clegg 7237c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7249e15f359SSam Clegg if (Globals.empty()) 7259e15f359SSam Clegg return; 7269e15f359SSam Clegg 7279e15f359SSam Clegg SectionBookkeeping Section; 7289e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7299e15f359SSam Clegg 7309e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7319e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7329e15f359SSam Clegg writeValueType(Global.Type); 7339e15f359SSam Clegg write8(Global.IsMutable); 7349e15f359SSam Clegg 7359e15f359SSam Clegg if (Global.HasImport) { 7369e15f359SSam Clegg assert(Global.InitialValue == 0); 7379e15f359SSam Clegg write8(wasm::WASM_OPCODE_GET_GLOBAL); 7389e15f359SSam Clegg encodeULEB128(Global.ImportIndex, getStream()); 7399e15f359SSam Clegg } else { 7409e15f359SSam Clegg assert(Global.ImportIndex == 0); 7419e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7429e15f359SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); // offset 7439e15f359SSam Clegg } 7449e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7459e15f359SSam Clegg } 7469e15f359SSam Clegg 7479e15f359SSam Clegg endSection(Section); 7489e15f359SSam Clegg } 7499e15f359SSam Clegg 750457fb0b4SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) { 7519e15f359SSam Clegg if (Exports.empty()) 7529e15f359SSam Clegg return; 7539e15f359SSam Clegg 7549e15f359SSam Clegg SectionBookkeeping Section; 7559e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7569e15f359SSam Clegg 7579e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7589e15f359SSam Clegg for (const WasmExport &Export : Exports) { 759b7787fd0SSam Clegg writeString(Export.FieldName); 7609e15f359SSam Clegg encodeSLEB128(Export.Kind, getStream()); 7619e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7629e15f359SSam Clegg } 7639e15f359SSam Clegg 7649e15f359SSam Clegg endSection(Section); 7659e15f359SSam Clegg } 7669e15f359SSam Clegg 767457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7689e15f359SSam Clegg if (TableElems.empty()) 7699e15f359SSam Clegg return; 7709e15f359SSam Clegg 7719e15f359SSam Clegg SectionBookkeeping Section; 7729e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 7739e15f359SSam Clegg 7749e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 7759e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 7769e15f359SSam Clegg 7779e15f359SSam Clegg // init expr for starting offset 7789e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 77930e1bbc1SSam Clegg encodeSLEB128(kInitialTableOffset, getStream()); 7809e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7819e15f359SSam Clegg 7829e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 7839e15f359SSam Clegg for (uint32_t Elem : TableElems) 7849e15f359SSam Clegg encodeULEB128(Elem, getStream()); 7859e15f359SSam Clegg 7869e15f359SSam Clegg endSection(Section); 7879e15f359SSam Clegg } 7889e15f359SSam Clegg 789457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 790457fb0b4SSam Clegg const MCAsmLayout &Layout, 791457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 7929e15f359SSam Clegg if (Functions.empty()) 7939e15f359SSam Clegg return; 7949e15f359SSam Clegg 7959e15f359SSam Clegg SectionBookkeeping Section; 7969e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 7979e15f359SSam Clegg 7989e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7999e15f359SSam Clegg 8009e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 801fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8029e15f359SSam Clegg 8039e15f359SSam Clegg int64_t Size = 0; 8049e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8059e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8069e15f359SSam Clegg 8079e15f359SSam Clegg encodeULEB128(Size, getStream()); 808fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8099e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8109e15f359SSam Clegg } 8119e15f359SSam Clegg 8129e15f359SSam Clegg // Apply fixups. 813acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8149e15f359SSam Clegg 8159e15f359SSam Clegg endSection(Section); 8169e15f359SSam Clegg } 8179e15f359SSam Clegg 818457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) { 8197c395943SSam Clegg if (Segments.empty()) 8207c395943SSam Clegg return; 8219e15f359SSam Clegg 8229e15f359SSam Clegg SectionBookkeeping Section; 8239e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8249e15f359SSam Clegg 8257c395943SSam Clegg encodeULEB128(Segments.size(), getStream()); // count 8267c395943SSam Clegg 8277c395943SSam Clegg for (const WasmDataSegment & Segment : Segments) { 8289e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8299e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8307c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8319e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8327c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8337c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8347c395943SSam Clegg writeBytes(Segment.Data); // data 8357c395943SSam Clegg } 8369e15f359SSam Clegg 8379e15f359SSam Clegg // Apply fixups. 8387c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8399e15f359SSam Clegg 8409e15f359SSam Clegg endSection(Section); 8419e15f359SSam Clegg } 8429e15f359SSam Clegg 843acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() { 8449e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8459e15f359SSam Clegg // for descriptions of the reloc sections. 8469e15f359SSam Clegg 8479e15f359SSam Clegg if (CodeRelocations.empty()) 8489e15f359SSam Clegg return; 8499e15f359SSam Clegg 8509e15f359SSam Clegg SectionBookkeeping Section; 8519e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 8529e15f359SSam Clegg 8539e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_CODE, getStream()); 854acd7d2b0SSam Clegg encodeULEB128(CodeRelocations.size(), getStream()); 8559e15f359SSam Clegg 8567c395943SSam Clegg writeRelocations(CodeRelocations); 8579e15f359SSam Clegg 8589e15f359SSam Clegg endSection(Section); 8599e15f359SSam Clegg } 8609e15f359SSam Clegg 8617c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() { 8629e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8639e15f359SSam Clegg // for descriptions of the reloc sections. 8649e15f359SSam Clegg 8659e15f359SSam Clegg if (DataRelocations.empty()) 8669e15f359SSam Clegg return; 8679e15f359SSam Clegg 8689e15f359SSam Clegg SectionBookkeeping Section; 8699e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 8709e15f359SSam Clegg 8719e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_DATA, getStream()); 8729e15f359SSam Clegg encodeULEB128(DataRelocations.size(), getStream()); 8739e15f359SSam Clegg 8747c395943SSam Clegg writeRelocations(DataRelocations); 8759e15f359SSam Clegg 8769e15f359SSam Clegg endSection(Section); 8779e15f359SSam Clegg } 8789e15f359SSam Clegg 8799e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 880d95ed959SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 881ea7caceeSSam Clegg ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags, 882ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 883ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) { 8849e15f359SSam Clegg SectionBookkeeping Section; 8859e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); 886b7787fd0SSam Clegg SectionBookkeeping SubSection; 8879e15f359SSam Clegg 88831a2c809SSam Clegg if (SymbolFlags.size() != 0) { 889b7787fd0SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_INFO); 89031a2c809SSam Clegg encodeULEB128(SymbolFlags.size(), getStream()); 89131a2c809SSam Clegg for (auto Pair: SymbolFlags) { 89231a2c809SSam Clegg writeString(Pair.first); 89331a2c809SSam Clegg encodeULEB128(Pair.second, getStream()); 894b7787fd0SSam Clegg } 895b7787fd0SSam Clegg endSection(SubSection); 896b7787fd0SSam Clegg } 8979e15f359SSam Clegg 8989e1ade93SSam Clegg if (DataSize > 0) { 8999e1ade93SSam Clegg startSection(SubSection, wasm::WASM_DATA_SIZE); 9009e1ade93SSam Clegg encodeULEB128(DataSize, getStream()); 9019e1ade93SSam Clegg endSection(SubSection); 9029e1ade93SSam Clegg } 9039e1ade93SSam Clegg 904d95ed959SSam Clegg if (Segments.size()) { 90563ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 906d95ed959SSam Clegg encodeULEB128(Segments.size(), getStream()); 90763ebb813SSam Clegg for (const WasmDataSegment &Segment : Segments) { 908d95ed959SSam Clegg writeString(Segment.Name); 90963ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 91063ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 91163ebb813SSam Clegg } 912d95ed959SSam Clegg endSection(SubSection); 913d95ed959SSam Clegg } 914d95ed959SSam Clegg 915bafe6902SSam Clegg if (!InitFuncs.empty()) { 916bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 917bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 918bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 919bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 920bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 921bafe6902SSam Clegg } 922bafe6902SSam Clegg endSection(SubSection); 923bafe6902SSam Clegg } 924bafe6902SSam Clegg 925ea7caceeSSam Clegg if (Comdats.size()) { 926ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 927ea7caceeSSam Clegg encodeULEB128(Comdats.size(), getStream()); 928ea7caceeSSam Clegg for (const auto &C : Comdats) { 929ea7caceeSSam Clegg writeString(C.first); 930ea7caceeSSam Clegg encodeULEB128(0, getStream()); // flags for future use 931ea7caceeSSam Clegg encodeULEB128(C.second.size(), getStream()); 932ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 933ea7caceeSSam Clegg encodeULEB128(Entry.Kind, getStream()); 934ea7caceeSSam Clegg encodeULEB128(Entry.Index, getStream()); 935ea7caceeSSam Clegg } 936ea7caceeSSam Clegg } 937ea7caceeSSam Clegg endSection(SubSection); 938ea7caceeSSam Clegg } 939ea7caceeSSam Clegg 9409e15f359SSam Clegg endSection(Section); 9419e15f359SSam Clegg } 9429e15f359SSam Clegg 9435e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 9445e3d33a7SSam Clegg assert(Symbol.isFunction()); 9455e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 9465e3d33a7SSam Clegg return TypeIndices[&Symbol]; 9475e3d33a7SSam Clegg } 9485e3d33a7SSam Clegg 9495e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 9505e3d33a7SSam Clegg assert(Symbol.isFunction()); 9515e3d33a7SSam Clegg 9525e3d33a7SSam Clegg WasmFunctionType F; 953aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 9545e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 9555e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 9565e3d33a7SSam Clegg 9575e3d33a7SSam Clegg auto Pair = 9585e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 9595e3d33a7SSam Clegg if (Pair.second) 9605e3d33a7SSam Clegg FunctionTypes.push_back(F); 9615e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 9625e3d33a7SSam Clegg 9635e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 9645e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 9655e3d33a7SSam Clegg return Pair.first->second; 9665e3d33a7SSam Clegg } 9675e3d33a7SSam Clegg 96818eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 96918eafb6cSDan Gohman const MCAsmLayout &Layout) { 970b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 97182607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 972b879539aSDerek Schuff wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32; 973d934cb88SDan Gohman 974d934cb88SDan Gohman // Collect information from the available symbols. 975d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 976d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 977d934cb88SDan Gohman SmallVector<WasmImport, 4> Imports; 978d934cb88SDan Gohman SmallVector<WasmExport, 4> Exports; 97931a2c809SSam Clegg SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags; 980bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 981ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 9827c395943SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 9837c395943SSam Clegg uint32_t DataSize = 0; 984d934cb88SDan Gohman 98582607f56SDan Gohman // In the special .global_variables section, we've encoded global 98682607f56SDan Gohman // variables used by the function. Translate them into the Globals 98782607f56SDan Gohman // list. 98812fd3da9SSam Clegg MCSectionWasm *GlobalVars = 98912fd3da9SSam Clegg Ctx.getWasmSection(".global_variables", SectionKind::getMetadata()); 99082607f56SDan Gohman if (!GlobalVars->getFragmentList().empty()) { 99182607f56SDan Gohman if (GlobalVars->getFragmentList().size() != 1) 99282607f56SDan Gohman report_fatal_error("only one .global_variables fragment supported"); 99382607f56SDan Gohman const MCFragment &Frag = *GlobalVars->begin(); 99482607f56SDan Gohman if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 99582607f56SDan Gohman report_fatal_error("only data supported in .global_variables"); 996fe6414b0SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 99782607f56SDan Gohman if (!DataFrag.getFixups().empty()) 99882607f56SDan Gohman report_fatal_error("fixups not supported in .global_variables"); 99982607f56SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1000970d02c4SDan Gohman for (const uint8_t *p = (const uint8_t *)Contents.data(), 1001970d02c4SDan Gohman *end = (const uint8_t *)Contents.data() + Contents.size(); 1002970d02c4SDan Gohman p != end; ) { 100382607f56SDan Gohman WasmGlobal G; 1004970d02c4SDan Gohman if (end - p < 3) 1005970d02c4SDan Gohman report_fatal_error("truncated global variable encoding"); 1006970d02c4SDan Gohman G.Type = wasm::ValType(int8_t(*p++)); 1007970d02c4SDan Gohman G.IsMutable = bool(*p++); 1008970d02c4SDan Gohman G.HasImport = bool(*p++); 1009970d02c4SDan Gohman if (G.HasImport) { 101082607f56SDan Gohman G.InitialValue = 0; 1011970d02c4SDan Gohman 1012970d02c4SDan Gohman WasmImport Import; 1013970d02c4SDan Gohman Import.ModuleName = (const char *)p; 1014970d02c4SDan Gohman const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p); 1015970d02c4SDan Gohman if (!nul) 1016970d02c4SDan Gohman report_fatal_error("global module name must be nul-terminated"); 1017970d02c4SDan Gohman p = nul + 1; 1018970d02c4SDan Gohman nul = (const uint8_t *)memchr(p, '\0', end - p); 1019970d02c4SDan Gohman if (!nul) 1020970d02c4SDan Gohman report_fatal_error("global base name must be nul-terminated"); 1021970d02c4SDan Gohman Import.FieldName = (const char *)p; 1022970d02c4SDan Gohman p = nul + 1; 1023970d02c4SDan Gohman 1024970d02c4SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1025970d02c4SDan Gohman Import.Type = int32_t(G.Type); 1026970d02c4SDan Gohman 1027970d02c4SDan Gohman G.ImportIndex = NumGlobalImports; 1028970d02c4SDan Gohman ++NumGlobalImports; 1029970d02c4SDan Gohman 1030970d02c4SDan Gohman Imports.push_back(Import); 1031970d02c4SDan Gohman } else { 1032970d02c4SDan Gohman unsigned n; 1033970d02c4SDan Gohman G.InitialValue = decodeSLEB128(p, &n); 1034970d02c4SDan Gohman G.ImportIndex = 0; 1035c8da0c0bSSimon Pilgrim if ((ptrdiff_t)n > end - p) 1036970d02c4SDan Gohman report_fatal_error("global initial value must be valid SLEB128"); 1037970d02c4SDan Gohman p += n; 1038970d02c4SDan Gohman } 103982607f56SDan Gohman Globals.push_back(G); 104082607f56SDan Gohman } 104182607f56SDan Gohman } 104282607f56SDan Gohman 1043f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1044f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1045f950b24aSSam Clegg // it if there are no loads or stores. 1046f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1047f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 1048f950b24aSSam Clegg WasmImport MemImport; 1049f950b24aSSam Clegg MemImport.ModuleName = MemorySym->getModuleName(); 1050f950b24aSSam Clegg MemImport.FieldName = MemorySym->getName(); 1051f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1052f950b24aSSam Clegg Imports.push_back(MemImport); 1053f950b24aSSam Clegg 1054f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1055f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1056f950b24aSSam Clegg // it if there are no indirect calls. 1057f950b24aSSam Clegg MCSymbolWasm *TableSym = 1058f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 1059f950b24aSSam Clegg WasmImport TableImport; 1060f950b24aSSam Clegg TableImport.ModuleName = TableSym->getModuleName(); 1061f950b24aSSam Clegg TableImport.FieldName = TableSym->getName(); 1062f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 1063f950b24aSSam Clegg TableImport.Type = wasm::WASM_TYPE_ANYFUNC; 1064f950b24aSSam Clegg Imports.push_back(TableImport); 1065f950b24aSSam Clegg 106632ce5ca0SDan Gohman // Populate FunctionTypeIndices and Imports. 106732ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 106832ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 106932ce5ca0SDan Gohman 107032ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 10719f3fe42eSSam Clegg // (because wasm always needs a type signature). 107232ce5ca0SDan Gohman if (WS.isFunction()) 107332ce5ca0SDan Gohman registerFunctionType(WS); 107432ce5ca0SDan Gohman 107532ce5ca0SDan Gohman if (WS.isTemporary()) 107632ce5ca0SDan Gohman continue; 107732ce5ca0SDan Gohman 107832ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 1079cd65f698SSam Clegg if ((!WS.isDefined() && !WS.isComdat()) || 1080d423f0d2SSam Clegg WS.isVariable()) { 108132ce5ca0SDan Gohman WasmImport Import; 108232ce5ca0SDan Gohman Import.ModuleName = WS.getModuleName(); 108332ce5ca0SDan Gohman Import.FieldName = WS.getName(); 108432ce5ca0SDan Gohman 108532ce5ca0SDan Gohman if (WS.isFunction()) { 108632ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 108732ce5ca0SDan Gohman Import.Type = getFunctionType(WS); 10889f3fe42eSSam Clegg SymbolIndices[&WS] = NumFunctionImports; 10899f3fe42eSSam Clegg ++NumFunctionImports; 109032ce5ca0SDan Gohman } else { 109132ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 109232ce5ca0SDan Gohman Import.Type = int32_t(PtrType); 109332ce5ca0SDan Gohman Import.IsMutable = false; 109432ce5ca0SDan Gohman SymbolIndices[&WS] = NumGlobalImports; 109532ce5ca0SDan Gohman 109683b16226SDan Gohman // If this global is the stack pointer, make it mutable. 1097ad19047dSDan Gohman if (WS.getName() == "__stack_pointer") 109832ce5ca0SDan Gohman Import.IsMutable = true; 109932ce5ca0SDan Gohman 110032ce5ca0SDan Gohman ++NumGlobalImports; 110132ce5ca0SDan Gohman } 110232ce5ca0SDan Gohman 110332ce5ca0SDan Gohman Imports.push_back(Import); 110432ce5ca0SDan Gohman } 110532ce5ca0SDan Gohman } 110632ce5ca0SDan Gohman 1107759631c7SSam Clegg for (MCSection &Sec : Asm) { 1108759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 110912fd3da9SSam Clegg if (!Section.isWasmData()) 1110759631c7SSam Clegg continue; 1111759631c7SSam Clegg 1112bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 1113bafe6902SSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array")) 1114bafe6902SSam Clegg continue; 1115bafe6902SSam Clegg 1116*329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1117759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1118759631c7SSam Clegg DataSegments.emplace_back(); 1119759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1120d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1121759631c7SSam Clegg Segment.Offset = DataSize; 1122759631c7SSam Clegg Segment.Section = &Section; 112363ebb813SSam Clegg addData(Segment.Data, Section); 112463ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 112563ebb813SSam Clegg Segment.Flags = 0; 1126759631c7SSam Clegg DataSize += Segment.Data.size(); 1127759631c7SSam Clegg Section.setMemoryOffset(Segment.Offset); 1128ea7caceeSSam Clegg 1129ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1130ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1131*329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1132ea7caceeSSam Clegg } 1133759631c7SSam Clegg } 1134759631c7SSam Clegg 1135b7787fd0SSam Clegg // Handle regular defined and undefined symbols. 1136d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1137d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1138d934cb88SDan Gohman // or used in relocations. 1139d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1140d934cb88SDan Gohman continue; 1141b7787fd0SSam Clegg 1142d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1143b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1144*329e76d5SSam Clegg << " isDefined=" << S.isDefined() 1145*329e76d5SSam Clegg << " isExternal=" << S.isExternal() 1146*329e76d5SSam Clegg << " isTemporary=" << S.isTemporary() 1147b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1148b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1149a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1150b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1151b7787fd0SSam Clegg 1152a2b35dacSSam Clegg if (WS.isWeak() || WS.isHidden()) { 1153a2b35dacSSam Clegg uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) | 1154a2b35dacSSam Clegg (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0); 1155a2b35dacSSam Clegg SymbolFlags.emplace_back(WS.getName(), Flags); 1156a2b35dacSSam Clegg } 1157b7787fd0SSam Clegg 11585e3d33a7SSam Clegg if (WS.isVariable()) 11595e3d33a7SSam Clegg continue; 11605e3d33a7SSam Clegg 1161d934cb88SDan Gohman unsigned Index; 1162b7787fd0SSam Clegg 1163d934cb88SDan Gohman if (WS.isFunction()) { 1164cd65f698SSam Clegg if (WS.isDefined()) { 1165b7787fd0SSam Clegg if (WS.getOffset() != 0) 1166b7787fd0SSam Clegg report_fatal_error( 1167b7787fd0SSam Clegg "function sections must contain one function each"); 1168b7787fd0SSam Clegg 1169b7787fd0SSam Clegg if (WS.getSize() == 0) 1170b7787fd0SSam Clegg report_fatal_error( 1171b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1172b7787fd0SSam Clegg 1173d934cb88SDan Gohman // A definition. Take the next available index. 11749f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1175d934cb88SDan Gohman 1176d934cb88SDan Gohman // Prepare the function. 1177d934cb88SDan Gohman WasmFunction Func; 11785e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1179d934cb88SDan Gohman Func.Sym = &WS; 1180d934cb88SDan Gohman SymbolIndices[&WS] = Index; 1181d934cb88SDan Gohman Functions.push_back(Func); 1182d934cb88SDan Gohman } else { 1183d934cb88SDan Gohman // An import; the index was assigned above. 1184d934cb88SDan Gohman Index = SymbolIndices.find(&WS)->second; 1185d934cb88SDan Gohman } 1186d934cb88SDan Gohman 11875e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1188d934cb88SDan Gohman } else { 1189c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1190c38e947eSSam Clegg continue; 1191c38e947eSSam Clegg 1192cd65f698SSam Clegg if (!WS.isDefined()) 1193fe6414b0SSam Clegg continue; 1194fe6414b0SSam Clegg 1195d934cb88SDan Gohman if (!WS.getSize()) 1196c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1197c38e947eSSam Clegg WS.getName()); 1198d934cb88SDan Gohman 1199d934cb88SDan Gohman int64_t Size = 0; 1200d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1201d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1202d934cb88SDan Gohman 12037c395943SSam Clegg // For each global, prepare a corresponding wasm global holding its 12047c395943SSam Clegg // address. For externals these will also be named exports. 12057c395943SSam Clegg Index = NumGlobalImports + Globals.size(); 1206759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1207ea7caceeSSam Clegg assert(DataSection.isWasmData()); 12087c395943SSam Clegg 12097c395943SSam Clegg WasmGlobal Global; 12107c395943SSam Clegg Global.Type = PtrType; 12117c395943SSam Clegg Global.IsMutable = false; 12127c395943SSam Clegg Global.HasImport = false; 1213759631c7SSam Clegg Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS); 12147c395943SSam Clegg Global.ImportIndex = 0; 12157c395943SSam Clegg SymbolIndices[&WS] = Index; 12167c395943SSam Clegg DEBUG(dbgs() << " -> global index: " << Index << "\n"); 12177c395943SSam Clegg Globals.push_back(Global); 1218d934cb88SDan Gohman } 1219d934cb88SDan Gohman 1220d934cb88SDan Gohman // If the symbol is visible outside this translation unit, export it. 1221cd65f698SSam Clegg if (WS.isDefined()) { 1222d934cb88SDan Gohman WasmExport Export; 1223d934cb88SDan Gohman Export.FieldName = WS.getName(); 1224d934cb88SDan Gohman Export.Index = Index; 1225d934cb88SDan Gohman if (WS.isFunction()) 1226d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1227d934cb88SDan Gohman else 1228d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12295e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1230d934cb88SDan Gohman Exports.push_back(Export); 1231ea7caceeSSam Clegg 123231a2c809SSam Clegg if (!WS.isExternal()) 123331a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1234ea7caceeSSam Clegg 1235ea7caceeSSam Clegg if (WS.isFunction()) { 1236cd65f698SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 1237ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) 1238ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1239ea7caceeSSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 1240ea7caceeSSam Clegg } 1241d934cb88SDan Gohman } 1242d934cb88SDan Gohman } 1243d934cb88SDan Gohman 12445e3d33a7SSam Clegg // Handle weak aliases. We need to process these in a separate pass because 12455e3d33a7SSam Clegg // we need to have processed the target of the alias before the alias itself 12465e3d33a7SSam Clegg // and the symbols are not necessarily ordered in this way. 1247b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1248b7787fd0SSam Clegg if (!S.isVariable()) 1249b7787fd0SSam Clegg continue; 125031a2c809SSam Clegg 1251cd65f698SSam Clegg assert(S.isDefined()); 1252b7787fd0SSam Clegg 12535e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1254aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1255aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 12565e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 12575e3d33a7SSam Clegg assert(SymbolIndices.count(ResolvedSym) > 0); 1258b7787fd0SSam Clegg uint32_t Index = SymbolIndices.find(ResolvedSym)->second; 12595e3d33a7SSam Clegg DEBUG(dbgs() << " -> index:" << Index << "\n"); 1260b7787fd0SSam Clegg 1261b7787fd0SSam Clegg WasmExport Export; 1262b7787fd0SSam Clegg Export.FieldName = WS.getName(); 1263b7787fd0SSam Clegg Export.Index = Index; 1264b7787fd0SSam Clegg if (WS.isFunction()) 1265b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1266b7787fd0SSam Clegg else 1267b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12685e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1269b7787fd0SSam Clegg Exports.push_back(Export); 127031a2c809SSam Clegg 127131a2c809SSam Clegg if (!WS.isExternal()) 127231a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1273b7787fd0SSam Clegg } 1274b7787fd0SSam Clegg 12756006e091SSam Clegg { 12766006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 12776006e091SSam Clegg // Functions referenced by a relocation need to prepared to be called 12786006e091SSam Clegg // indirectly. 12796006e091SSam Clegg const MCSymbolWasm& WS = *Rel.Symbol; 12806006e091SSam Clegg if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) { 12816006e091SSam Clegg switch (Rel.Type) { 12826006e091SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 12836006e091SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 12846006e091SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 12856006e091SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 12866006e091SSam Clegg uint32_t Index = SymbolIndices.find(&WS)->second; 128730e1bbc1SSam Clegg IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset; 1288*329e76d5SSam Clegg DEBUG(dbgs() << " -> adding " << WS.getName() 1289*329e76d5SSam Clegg << " to table: " << TableElems.size() << "\n"); 12906006e091SSam Clegg TableElems.push_back(Index); 12916006e091SSam Clegg registerFunctionType(WS); 12926006e091SSam Clegg break; 12936006e091SSam Clegg } 12946006e091SSam Clegg default: 12956006e091SSam Clegg break; 12966006e091SSam Clegg } 12976006e091SSam Clegg } 12986006e091SSam Clegg }; 1299970d02c4SDan Gohman 13006006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 13016006e091SSam Clegg HandleReloc(RelEntry); 13026006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 13036006e091SSam Clegg HandleReloc(RelEntry); 1304d934cb88SDan Gohman } 1305d934cb88SDan Gohman 1306bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1307bafe6902SSam Clegg for (const MCSection &S : Asm) { 1308bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1309bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1310bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1311bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1312bafe6902SSam Clegg continue; 1313bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1314bafe6902SSam Clegg continue; 1315bafe6902SSam Clegg if (WS.getFragmentList().size() != 2) 1316bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1317bafe6902SSam Clegg const MCFragment &AlignFrag = *WS.begin(); 1318bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1319bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1320bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1321bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1322bafe6902SSam Clegg const MCFragment &Frag = *std::next(WS.begin()); 1323bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1324bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1325bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 1326bafe6902SSam Clegg if (WS.getSectionName().size() != 11) { 1327bafe6902SSam Clegg if (WS.getSectionName()[11] != '.') 1328bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 1329bafe6902SSam Clegg if (WS.getSectionName().substr(12).getAsInteger(10, Priority)) 1330bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1331bafe6902SSam Clegg } 1332bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1333bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1334bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1335bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1336bafe6902SSam Clegg p != end; ++p) { 1337bafe6902SSam Clegg if (*p != 0) 1338bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1339bafe6902SSam Clegg } 1340bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1341bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1342bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1343bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1344bafe6902SSam Clegg if (!Sym) 1345bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1346bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1347bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 1348bafe6902SSam Clegg auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol())); 1349bafe6902SSam Clegg if (I == SymbolIndices.end()) 1350bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be defined"); 1351bafe6902SSam Clegg uint32_t Index = I->second; 1352bafe6902SSam Clegg InitFuncs.push_back(std::make_pair(Priority, Index)); 1353bafe6902SSam Clegg } 1354bafe6902SSam Clegg } 1355bafe6902SSam Clegg 135618eafb6cSDan Gohman // Write out the Wasm header. 135718eafb6cSDan Gohman writeHeader(Asm); 135818eafb6cSDan Gohman 13599e15f359SSam Clegg writeTypeSection(FunctionTypes); 1360f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 13619e15f359SSam Clegg writeFunctionSection(Functions); 1362f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1363f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 13647c395943SSam Clegg writeGlobalSection(); 13659e15f359SSam Clegg writeExportSection(Exports); 13669e15f359SSam Clegg writeElemSection(TableElems); 1367acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 13687c395943SSam Clegg writeDataSection(DataSegments); 1369acd7d2b0SSam Clegg writeCodeRelocSection(); 13707c395943SSam Clegg writeDataRelocSection(); 1371bafe6902SSam Clegg writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags, 1372ea7caceeSSam Clegg InitFuncs, Comdats); 1373970d02c4SDan Gohman 1374d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1375d934cb88SDan Gohman // TODO: Translate debug sections to the output. 137618eafb6cSDan Gohman } 137718eafb6cSDan Gohman 137860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 13791301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 138018eafb6cSDan Gohman raw_pwrite_stream &OS) { 13810917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 138218eafb6cSDan Gohman } 1383