10b57cec5SDimitry Andric //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements Wasm object file writer information.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140b57cec5SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
15e8d8bef9SDimitry Andric #include "llvm/BinaryFormat/WasmTraits.h"
160b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
170b57cec5SDimitry Andric #include "llvm/MC/MCAsmBackend.h"
180b57cec5SDimitry Andric #include "llvm/MC/MCAsmLayout.h"
190b57cec5SDimitry Andric #include "llvm/MC/MCAssembler.h"
200b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
210b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
220b57cec5SDimitry Andric #include "llvm/MC/MCFixupKindInfo.h"
230b57cec5SDimitry Andric #include "llvm/MC/MCObjectWriter.h"
240b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
250b57cec5SDimitry Andric #include "llvm/MC/MCSymbolWasm.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCWasmObjectWriter.h"
280b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
290b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
305ffd83dbSDimitry Andric #include "llvm/Support/EndianStream.h"
310b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
320b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
330b57cec5SDimitry Andric #include <vector>
340b57cec5SDimitry Andric
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric
370b57cec5SDimitry Andric #define DEBUG_TYPE "mc"
380b57cec5SDimitry Andric
390b57cec5SDimitry Andric namespace {
400b57cec5SDimitry Andric
41e8d8bef9SDimitry Andric // When we create the indirect function table we start at 1, so that there is
42e8d8bef9SDimitry Andric // and empty slot at 0 and therefore calling a null function pointer will trap.
430b57cec5SDimitry Andric static const uint32_t InitialTableOffset = 1;
440b57cec5SDimitry Andric
450b57cec5SDimitry Andric // For patching purposes, we need to remember where each section starts, both
460b57cec5SDimitry Andric // for patching up the section size field, and for patching up references to
470b57cec5SDimitry Andric // locations within the section.
480b57cec5SDimitry Andric struct SectionBookkeeping {
490b57cec5SDimitry Andric // Where the size of the section is written.
500b57cec5SDimitry Andric uint64_t SizeOffset;
510b57cec5SDimitry Andric // Where the section header ends (without custom section name).
520b57cec5SDimitry Andric uint64_t PayloadOffset;
530b57cec5SDimitry Andric // Where the contents of the section starts.
540b57cec5SDimitry Andric uint64_t ContentsOffset;
550b57cec5SDimitry Andric uint32_t Index;
560b57cec5SDimitry Andric };
570b57cec5SDimitry Andric
580b57cec5SDimitry Andric // A wasm data segment. A wasm binary contains only a single data section
590b57cec5SDimitry Andric // but that can contain many segments, each with their own virtual location
600b57cec5SDimitry Andric // in memory. Each MCSection data created by llvm is modeled as its own
610b57cec5SDimitry Andric // wasm data segment.
620b57cec5SDimitry Andric struct WasmDataSegment {
630b57cec5SDimitry Andric MCSectionWasm *Section;
640b57cec5SDimitry Andric StringRef Name;
650b57cec5SDimitry Andric uint32_t InitFlags;
665ffd83dbSDimitry Andric uint64_t Offset;
670b57cec5SDimitry Andric uint32_t Alignment;
68fe6060f1SDimitry Andric uint32_t LinkingFlags;
690b57cec5SDimitry Andric SmallVector<char, 4> Data;
700b57cec5SDimitry Andric };
710b57cec5SDimitry Andric
720b57cec5SDimitry Andric // A wasm function to be written into the function section.
730b57cec5SDimitry Andric struct WasmFunction {
740b57cec5SDimitry Andric uint32_t SigIndex;
75bdd1243dSDimitry Andric MCSection *Section;
760b57cec5SDimitry Andric };
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric // A wasm global to be written into the global section.
790b57cec5SDimitry Andric struct WasmGlobal {
800b57cec5SDimitry Andric wasm::WasmGlobalType Type;
810b57cec5SDimitry Andric uint64_t InitialValue;
820b57cec5SDimitry Andric };
830b57cec5SDimitry Andric
840b57cec5SDimitry Andric // Information about a single item which is part of a COMDAT. For each data
850b57cec5SDimitry Andric // segment or function which is in the COMDAT, there is a corresponding
860b57cec5SDimitry Andric // WasmComdatEntry.
870b57cec5SDimitry Andric struct WasmComdatEntry {
880b57cec5SDimitry Andric unsigned Kind;
890b57cec5SDimitry Andric uint32_t Index;
900b57cec5SDimitry Andric };
910b57cec5SDimitry Andric
920b57cec5SDimitry Andric // Information about a single relocation.
930b57cec5SDimitry Andric struct WasmRelocationEntry {
940b57cec5SDimitry Andric uint64_t Offset; // Where is the relocation.
950b57cec5SDimitry Andric const MCSymbolWasm *Symbol; // The symbol to relocate with.
960b57cec5SDimitry Andric int64_t Addend; // A value to add to the symbol.
970b57cec5SDimitry Andric unsigned Type; // The type of the relocation.
980b57cec5SDimitry Andric const MCSectionWasm *FixupSection; // The section the relocation is targeting.
990b57cec5SDimitry Andric
WasmRelocationEntry__anonbe1f80430111::WasmRelocationEntry1000b57cec5SDimitry Andric WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1010b57cec5SDimitry Andric int64_t Addend, unsigned Type,
1020b57cec5SDimitry Andric const MCSectionWasm *FixupSection)
1030b57cec5SDimitry Andric : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1040b57cec5SDimitry Andric FixupSection(FixupSection) {}
1050b57cec5SDimitry Andric
hasAddend__anonbe1f80430111::WasmRelocationEntry1060b57cec5SDimitry Andric bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
1070b57cec5SDimitry Andric
print__anonbe1f80430111::WasmRelocationEntry1080b57cec5SDimitry Andric void print(raw_ostream &Out) const {
1090b57cec5SDimitry Andric Out << wasm::relocTypetoString(Type) << " Off=" << Offset
1100b57cec5SDimitry Andric << ", Sym=" << *Symbol << ", Addend=" << Addend
1115ffd83dbSDimitry Andric << ", FixupSection=" << FixupSection->getName();
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric
1140b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump__anonbe1f80430111::WasmRelocationEntry1150b57cec5SDimitry Andric LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1160b57cec5SDimitry Andric #endif
1170b57cec5SDimitry Andric };
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric static const uint32_t InvalidIndex = -1;
1200b57cec5SDimitry Andric
1210b57cec5SDimitry Andric struct WasmCustomSection {
1220b57cec5SDimitry Andric
1230b57cec5SDimitry Andric StringRef Name;
1240b57cec5SDimitry Andric MCSectionWasm *Section;
1250b57cec5SDimitry Andric
12681ad6265SDimitry Andric uint32_t OutputContentsOffset = 0;
12781ad6265SDimitry Andric uint32_t OutputIndex = InvalidIndex;
1280b57cec5SDimitry Andric
WasmCustomSection__anonbe1f80430111::WasmCustomSection1290b57cec5SDimitry Andric WasmCustomSection(StringRef Name, MCSectionWasm *Section)
13081ad6265SDimitry Andric : Name(Name), Section(Section) {}
1310b57cec5SDimitry Andric };
1320b57cec5SDimitry Andric
1330b57cec5SDimitry Andric #if !defined(NDEBUG)
operator <<(raw_ostream & OS,const WasmRelocationEntry & Rel)1340b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
1350b57cec5SDimitry Andric Rel.print(OS);
1360b57cec5SDimitry Andric return OS;
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric #endif
1390b57cec5SDimitry Andric
140fb03ea46SDimitry Andric // Write Value as an (unsigned) LEB value at offset Offset in Stream, padded
1410b57cec5SDimitry Andric // to allow patching.
142fb03ea46SDimitry Andric template <typename T, int W>
writePatchableULEB(raw_pwrite_stream & Stream,T Value,uint64_t Offset)143fb03ea46SDimitry Andric void writePatchableULEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1445ffd83dbSDimitry Andric uint8_t Buffer[W];
145fb03ea46SDimitry Andric unsigned SizeLen = encodeULEB128(Value, Buffer, W);
1465ffd83dbSDimitry Andric assert(SizeLen == W);
1470b57cec5SDimitry Andric Stream.pwrite((char *)Buffer, SizeLen, Offset);
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric
150fb03ea46SDimitry Andric // Write Value as an signed LEB value at offset Offset in Stream, padded
1510b57cec5SDimitry Andric // to allow patching.
152fb03ea46SDimitry Andric template <typename T, int W>
writePatchableSLEB(raw_pwrite_stream & Stream,T Value,uint64_t Offset)153fb03ea46SDimitry Andric void writePatchableSLEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1545ffd83dbSDimitry Andric uint8_t Buffer[W];
155fb03ea46SDimitry Andric unsigned SizeLen = encodeSLEB128(Value, Buffer, W);
1565ffd83dbSDimitry Andric assert(SizeLen == W);
1570b57cec5SDimitry Andric Stream.pwrite((char *)Buffer, SizeLen, Offset);
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric
writePatchableU32(raw_pwrite_stream & Stream,uint32_t Value,uint64_t Offset)160fb03ea46SDimitry Andric static void writePatchableU32(raw_pwrite_stream &Stream, uint32_t Value,
161fb03ea46SDimitry Andric uint64_t Offset) {
162fb03ea46SDimitry Andric writePatchableULEB<uint32_t, 5>(Stream, Value, Offset);
163fb03ea46SDimitry Andric }
164fb03ea46SDimitry Andric
writePatchableS32(raw_pwrite_stream & Stream,int32_t Value,uint64_t Offset)165fb03ea46SDimitry Andric static void writePatchableS32(raw_pwrite_stream &Stream, int32_t Value,
166fb03ea46SDimitry Andric uint64_t Offset) {
167fb03ea46SDimitry Andric writePatchableSLEB<int32_t, 5>(Stream, Value, Offset);
168fb03ea46SDimitry Andric }
169fb03ea46SDimitry Andric
writePatchableU64(raw_pwrite_stream & Stream,uint64_t Value,uint64_t Offset)170fb03ea46SDimitry Andric static void writePatchableU64(raw_pwrite_stream &Stream, uint64_t Value,
171fb03ea46SDimitry Andric uint64_t Offset) {
172fb03ea46SDimitry Andric writePatchableSLEB<uint64_t, 10>(Stream, Value, Offset);
173fb03ea46SDimitry Andric }
174fb03ea46SDimitry Andric
writePatchableS64(raw_pwrite_stream & Stream,int64_t Value,uint64_t Offset)175fb03ea46SDimitry Andric static void writePatchableS64(raw_pwrite_stream &Stream, int64_t Value,
176fb03ea46SDimitry Andric uint64_t Offset) {
177fb03ea46SDimitry Andric writePatchableSLEB<int64_t, 10>(Stream, Value, Offset);
178fb03ea46SDimitry Andric }
179fb03ea46SDimitry Andric
180fb03ea46SDimitry Andric // Write Value as a plain integer value at offset Offset in Stream.
patchI32(raw_pwrite_stream & Stream,uint32_t Value,uint64_t Offset)181fb03ea46SDimitry Andric static void patchI32(raw_pwrite_stream &Stream, uint32_t Value,
182fb03ea46SDimitry Andric uint64_t Offset) {
1830b57cec5SDimitry Andric uint8_t Buffer[4];
184fb03ea46SDimitry Andric support::endian::write32le(Buffer, Value);
1850b57cec5SDimitry Andric Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric
patchI64(raw_pwrite_stream & Stream,uint64_t Value,uint64_t Offset)188fb03ea46SDimitry Andric static void patchI64(raw_pwrite_stream &Stream, uint64_t Value,
189fb03ea46SDimitry Andric uint64_t Offset) {
1905ffd83dbSDimitry Andric uint8_t Buffer[8];
191fb03ea46SDimitry Andric support::endian::write64le(Buffer, Value);
1925ffd83dbSDimitry Andric Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1935ffd83dbSDimitry Andric }
1945ffd83dbSDimitry Andric
isDwoSection(const MCSection & Sec)195e8d8bef9SDimitry Andric bool isDwoSection(const MCSection &Sec) {
1965f757f3fSDimitry Andric return Sec.getName().ends_with(".dwo");
197e8d8bef9SDimitry Andric }
198e8d8bef9SDimitry Andric
1990b57cec5SDimitry Andric class WasmObjectWriter : public MCObjectWriter {
20006c3fb27SDimitry Andric support::endian::Writer *W = nullptr;
2010b57cec5SDimitry Andric
2020b57cec5SDimitry Andric /// The target specific Wasm writer instance.
2030b57cec5SDimitry Andric std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
2040b57cec5SDimitry Andric
2050b57cec5SDimitry Andric // Relocations for fixing up references in the code section.
2060b57cec5SDimitry Andric std::vector<WasmRelocationEntry> CodeRelocations;
2070b57cec5SDimitry Andric // Relocations for fixing up references in the data section.
2080b57cec5SDimitry Andric std::vector<WasmRelocationEntry> DataRelocations;
2090b57cec5SDimitry Andric
2100b57cec5SDimitry Andric // Index values to use for fixing up call_indirect type indices.
2110b57cec5SDimitry Andric // Maps function symbols to the index of the type of the function
2120b57cec5SDimitry Andric DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
2130b57cec5SDimitry Andric // Maps function symbols to the table element index space. Used
2140b57cec5SDimitry Andric // for TABLE_INDEX relocation types (i.e. address taken functions).
2150b57cec5SDimitry Andric DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
216e8d8bef9SDimitry Andric // Maps function/global/table symbols to the
217fe6060f1SDimitry Andric // function/global/table/tag/section index space.
2180b57cec5SDimitry Andric DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2190b57cec5SDimitry Andric DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2200b57cec5SDimitry Andric // Maps data symbols to the Wasm segment and offset/size with the segment.
2210b57cec5SDimitry Andric DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric // Stores output data (index, relocations, content offset) for custom
2240b57cec5SDimitry Andric // section.
2250b57cec5SDimitry Andric std::vector<WasmCustomSection> CustomSections;
2260b57cec5SDimitry Andric std::unique_ptr<WasmCustomSection> ProducersSection;
2270b57cec5SDimitry Andric std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2280b57cec5SDimitry Andric // Relocations for fixing up references in the custom sections.
2290b57cec5SDimitry Andric DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2300b57cec5SDimitry Andric CustomSectionsRelocations;
2310b57cec5SDimitry Andric
2320b57cec5SDimitry Andric // Map from section to defining function symbol.
2330b57cec5SDimitry Andric DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2340b57cec5SDimitry Andric
235e8d8bef9SDimitry Andric DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
236e8d8bef9SDimitry Andric SmallVector<wasm::WasmSignature, 4> Signatures;
2370b57cec5SDimitry Andric SmallVector<WasmDataSegment, 4> DataSegments;
2380b57cec5SDimitry Andric unsigned NumFunctionImports = 0;
2390b57cec5SDimitry Andric unsigned NumGlobalImports = 0;
240e8d8bef9SDimitry Andric unsigned NumTableImports = 0;
241fe6060f1SDimitry Andric unsigned NumTagImports = 0;
2420b57cec5SDimitry Andric uint32_t SectionCount = 0;
2430b57cec5SDimitry Andric
244e8d8bef9SDimitry Andric enum class DwoMode {
245e8d8bef9SDimitry Andric AllSections,
246e8d8bef9SDimitry Andric NonDwoOnly,
247e8d8bef9SDimitry Andric DwoOnly,
248e8d8bef9SDimitry Andric };
249e8d8bef9SDimitry Andric bool IsSplitDwarf = false;
250e8d8bef9SDimitry Andric raw_pwrite_stream *OS = nullptr;
251e8d8bef9SDimitry Andric raw_pwrite_stream *DwoOS = nullptr;
252e8d8bef9SDimitry Andric
253e8d8bef9SDimitry Andric // TargetObjectWriter wranppers.
is64Bit() const2540b57cec5SDimitry Andric bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
isEmscripten() const2558bcb0991SDimitry Andric bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
2560b57cec5SDimitry Andric
2570b57cec5SDimitry Andric void startSection(SectionBookkeeping &Section, unsigned SectionId);
2580b57cec5SDimitry Andric void startCustomSection(SectionBookkeeping &Section, StringRef Name);
2590b57cec5SDimitry Andric void endSection(SectionBookkeeping &Section);
2600b57cec5SDimitry Andric
2610b57cec5SDimitry Andric public:
WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS_)2620b57cec5SDimitry Andric WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
263e8d8bef9SDimitry Andric raw_pwrite_stream &OS_)
264e8d8bef9SDimitry Andric : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
265e8d8bef9SDimitry Andric
WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS_,raw_pwrite_stream & DwoOS_)266e8d8bef9SDimitry Andric WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
267e8d8bef9SDimitry Andric raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
268e8d8bef9SDimitry Andric : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
269e8d8bef9SDimitry Andric DwoOS(&DwoOS_) {}
2700b57cec5SDimitry Andric
2710b57cec5SDimitry Andric private:
reset()2720b57cec5SDimitry Andric void reset() override {
2730b57cec5SDimitry Andric CodeRelocations.clear();
2740b57cec5SDimitry Andric DataRelocations.clear();
2750b57cec5SDimitry Andric TypeIndices.clear();
2760b57cec5SDimitry Andric WasmIndices.clear();
2770b57cec5SDimitry Andric GOTIndices.clear();
2780b57cec5SDimitry Andric TableIndices.clear();
2790b57cec5SDimitry Andric DataLocations.clear();
2800b57cec5SDimitry Andric CustomSections.clear();
2810b57cec5SDimitry Andric ProducersSection.reset();
2820b57cec5SDimitry Andric TargetFeaturesSection.reset();
2830b57cec5SDimitry Andric CustomSectionsRelocations.clear();
2840b57cec5SDimitry Andric SignatureIndices.clear();
2850b57cec5SDimitry Andric Signatures.clear();
2860b57cec5SDimitry Andric DataSegments.clear();
2870b57cec5SDimitry Andric SectionFunctions.clear();
2880b57cec5SDimitry Andric NumFunctionImports = 0;
2890b57cec5SDimitry Andric NumGlobalImports = 0;
290e8d8bef9SDimitry Andric NumTableImports = 0;
2910b57cec5SDimitry Andric MCObjectWriter::reset();
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric
2940b57cec5SDimitry Andric void writeHeader(const MCAssembler &Asm);
2950b57cec5SDimitry Andric
2960b57cec5SDimitry Andric void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
2970b57cec5SDimitry Andric const MCFragment *Fragment, const MCFixup &Fixup,
2980b57cec5SDimitry Andric MCValue Target, uint64_t &FixedValue) override;
2990b57cec5SDimitry Andric
3000b57cec5SDimitry Andric void executePostLayoutBinding(MCAssembler &Asm,
3010b57cec5SDimitry Andric const MCAsmLayout &Layout) override;
302e8d8bef9SDimitry Andric void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
303e8d8bef9SDimitry Andric MCAssembler &Asm, const MCAsmLayout &Layout);
3040b57cec5SDimitry Andric uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3050b57cec5SDimitry Andric
306e8d8bef9SDimitry Andric uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
307e8d8bef9SDimitry Andric DwoMode Mode);
308e8d8bef9SDimitry Andric
writeString(const StringRef Str)3090b57cec5SDimitry Andric void writeString(const StringRef Str) {
310e8d8bef9SDimitry Andric encodeULEB128(Str.size(), W->OS);
311e8d8bef9SDimitry Andric W->OS << Str;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric
314349cc55cSDimitry Andric void writeStringWithAlignment(const StringRef Str, unsigned Alignment);
315349cc55cSDimitry Andric
writeI32(int32_t val)3165ffd83dbSDimitry Andric void writeI32(int32_t val) {
3175ffd83dbSDimitry Andric char Buffer[4];
3185ffd83dbSDimitry Andric support::endian::write32le(Buffer, val);
319e8d8bef9SDimitry Andric W->OS.write(Buffer, sizeof(Buffer));
3205ffd83dbSDimitry Andric }
3215ffd83dbSDimitry Andric
writeI64(int64_t val)3225ffd83dbSDimitry Andric void writeI64(int64_t val) {
3235ffd83dbSDimitry Andric char Buffer[8];
3245ffd83dbSDimitry Andric support::endian::write64le(Buffer, val);
325e8d8bef9SDimitry Andric W->OS.write(Buffer, sizeof(Buffer));
3265ffd83dbSDimitry Andric }
3275ffd83dbSDimitry Andric
writeValueType(wasm::ValType Ty)328e8d8bef9SDimitry Andric void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3290b57cec5SDimitry Andric
330e8d8bef9SDimitry Andric void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3315ffd83dbSDimitry Andric void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
3320b57cec5SDimitry Andric uint32_t NumElements);
3330b57cec5SDimitry Andric void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3340b57cec5SDimitry Andric void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
335fe6060f1SDimitry Andric void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
336fe6060f1SDimitry Andric ArrayRef<uint32_t> TableElems);
3370b57cec5SDimitry Andric void writeDataCountSection();
3385ffd83dbSDimitry Andric uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
3390b57cec5SDimitry Andric ArrayRef<WasmFunction> Functions);
3405ffd83dbSDimitry Andric uint32_t writeDataSection(const MCAsmLayout &Layout);
341349cc55cSDimitry Andric void writeTagSection(ArrayRef<uint32_t> TagTypes);
3425ffd83dbSDimitry Andric void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
343e8d8bef9SDimitry Andric void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3440b57cec5SDimitry Andric void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3450b57cec5SDimitry Andric std::vector<WasmRelocationEntry> &Relocations);
3460b57cec5SDimitry Andric void writeLinkingMetaDataSection(
3470b57cec5SDimitry Andric ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
3480b57cec5SDimitry Andric ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
3490b57cec5SDimitry Andric const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3500b57cec5SDimitry Andric void writeCustomSection(WasmCustomSection &CustomSection,
3510b57cec5SDimitry Andric const MCAssembler &Asm, const MCAsmLayout &Layout);
3520b57cec5SDimitry Andric void writeCustomRelocSections();
3530b57cec5SDimitry Andric
3545ffd83dbSDimitry Andric uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3555ffd83dbSDimitry Andric const MCAsmLayout &Layout);
3560b57cec5SDimitry Andric void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3575ffd83dbSDimitry Andric uint64_t ContentsOffset, const MCAsmLayout &Layout);
3580b57cec5SDimitry Andric
3590b57cec5SDimitry Andric uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3600b57cec5SDimitry Andric uint32_t getFunctionType(const MCSymbolWasm &Symbol);
361fe6060f1SDimitry Andric uint32_t getTagType(const MCSymbolWasm &Symbol);
3620b57cec5SDimitry Andric void registerFunctionType(const MCSymbolWasm &Symbol);
363fe6060f1SDimitry Andric void registerTagType(const MCSymbolWasm &Symbol);
3640b57cec5SDimitry Andric };
3650b57cec5SDimitry Andric
3660b57cec5SDimitry Andric } // end anonymous namespace
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric // Write out a section header and a patchable section size field.
startSection(SectionBookkeeping & Section,unsigned SectionId)3690b57cec5SDimitry Andric void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3700b57cec5SDimitry Andric unsigned SectionId) {
3710b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
372e8d8bef9SDimitry Andric W->OS << char(SectionId);
3730b57cec5SDimitry Andric
374e8d8bef9SDimitry Andric Section.SizeOffset = W->OS.tell();
3750b57cec5SDimitry Andric
3760b57cec5SDimitry Andric // The section size. We don't know the size yet, so reserve enough space
3770b57cec5SDimitry Andric // for any 32-bit value; we'll patch it later.
378e8d8bef9SDimitry Andric encodeULEB128(0, W->OS, 5);
3790b57cec5SDimitry Andric
3800b57cec5SDimitry Andric // The position where the section starts, for measuring its size.
381e8d8bef9SDimitry Andric Section.ContentsOffset = W->OS.tell();
382e8d8bef9SDimitry Andric Section.PayloadOffset = W->OS.tell();
3830b57cec5SDimitry Andric Section.Index = SectionCount++;
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric
386349cc55cSDimitry Andric // Write a string with extra paddings for trailing alignment
387349cc55cSDimitry Andric // TODO: support alignment at asm and llvm level?
writeStringWithAlignment(const StringRef Str,unsigned Alignment)388349cc55cSDimitry Andric void WasmObjectWriter::writeStringWithAlignment(const StringRef Str,
389349cc55cSDimitry Andric unsigned Alignment) {
390349cc55cSDimitry Andric
391349cc55cSDimitry Andric // Calculate the encoded size of str length and add pads based on it and
392349cc55cSDimitry Andric // alignment.
393349cc55cSDimitry Andric raw_null_ostream NullOS;
394349cc55cSDimitry Andric uint64_t StrSizeLength = encodeULEB128(Str.size(), NullOS);
395349cc55cSDimitry Andric uint64_t Offset = W->OS.tell() + StrSizeLength + Str.size();
396349cc55cSDimitry Andric uint64_t Paddings = offsetToAlignment(Offset, Align(Alignment));
397349cc55cSDimitry Andric Offset += Paddings;
398349cc55cSDimitry Andric
399349cc55cSDimitry Andric // LEB128 greater than 5 bytes is invalid
400349cc55cSDimitry Andric assert((StrSizeLength + Paddings) <= 5 && "too long string to align");
401349cc55cSDimitry Andric
402349cc55cSDimitry Andric encodeSLEB128(Str.size(), W->OS, StrSizeLength + Paddings);
403349cc55cSDimitry Andric W->OS << Str;
404349cc55cSDimitry Andric
405349cc55cSDimitry Andric assert(W->OS.tell() == Offset && "invalid padding");
406349cc55cSDimitry Andric }
407349cc55cSDimitry Andric
startCustomSection(SectionBookkeeping & Section,StringRef Name)4080b57cec5SDimitry Andric void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
4090b57cec5SDimitry Andric StringRef Name) {
4100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
4110b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_CUSTOM);
4120b57cec5SDimitry Andric
4130b57cec5SDimitry Andric // The position where the section header ends, for measuring its size.
414e8d8bef9SDimitry Andric Section.PayloadOffset = W->OS.tell();
4150b57cec5SDimitry Andric
4160b57cec5SDimitry Andric // Custom sections in wasm also have a string identifier.
417349cc55cSDimitry Andric if (Name != "__clangast") {
4180b57cec5SDimitry Andric writeString(Name);
419349cc55cSDimitry Andric } else {
420349cc55cSDimitry Andric // The on-disk hashtable in clangast needs to be aligned by 4 bytes.
421349cc55cSDimitry Andric writeStringWithAlignment(Name, 4);
422349cc55cSDimitry Andric }
4230b57cec5SDimitry Andric
4240b57cec5SDimitry Andric // The position where the custom section starts.
425e8d8bef9SDimitry Andric Section.ContentsOffset = W->OS.tell();
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric
4280b57cec5SDimitry Andric // Now that the section is complete and we know how big it is, patch up the
4290b57cec5SDimitry Andric // section size field at the start of the section.
endSection(SectionBookkeeping & Section)4300b57cec5SDimitry Andric void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
431e8d8bef9SDimitry Andric uint64_t Size = W->OS.tell();
4320b57cec5SDimitry Andric // /dev/null doesn't support seek/tell and can report offset of 0.
4330b57cec5SDimitry Andric // Simply skip this patching in that case.
4340b57cec5SDimitry Andric if (!Size)
4350b57cec5SDimitry Andric return;
4360b57cec5SDimitry Andric
4370b57cec5SDimitry Andric Size -= Section.PayloadOffset;
4380b57cec5SDimitry Andric if (uint32_t(Size) != Size)
4390b57cec5SDimitry Andric report_fatal_error("section size does not fit in a uint32_t");
4400b57cec5SDimitry Andric
4410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
4420b57cec5SDimitry Andric
4430b57cec5SDimitry Andric // Write the final section size to the payload_len field, which follows
4440b57cec5SDimitry Andric // the section id byte.
445fb03ea46SDimitry Andric writePatchableU32(static_cast<raw_pwrite_stream &>(W->OS), Size,
4460b57cec5SDimitry Andric Section.SizeOffset);
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric
4490b57cec5SDimitry Andric // Emit the Wasm header.
writeHeader(const MCAssembler & Asm)4500b57cec5SDimitry Andric void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
451e8d8bef9SDimitry Andric W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
452e8d8bef9SDimitry Andric W->write<uint32_t>(wasm::WasmVersion);
4530b57cec5SDimitry Andric }
4540b57cec5SDimitry Andric
executePostLayoutBinding(MCAssembler & Asm,const MCAsmLayout & Layout)4550b57cec5SDimitry Andric void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
4560b57cec5SDimitry Andric const MCAsmLayout &Layout) {
457fe6060f1SDimitry Andric // Some compilation units require the indirect function table to be present
458fe6060f1SDimitry Andric // but don't explicitly reference it. This is the case for call_indirect
459fe6060f1SDimitry Andric // without the reference-types feature, and also function bitcasts in all
460fe6060f1SDimitry Andric // cases. In those cases the __indirect_function_table has the
461fe6060f1SDimitry Andric // WASM_SYMBOL_NO_STRIP attribute. Here we make sure this symbol makes it to
462fe6060f1SDimitry Andric // the assembler, if needed.
463fe6060f1SDimitry Andric if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
464fe6060f1SDimitry Andric const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
465fe6060f1SDimitry Andric if (WasmSym->isNoStrip())
466e8d8bef9SDimitry Andric Asm.registerSymbol(*Sym);
467fe6060f1SDimitry Andric }
468e8d8bef9SDimitry Andric
4690b57cec5SDimitry Andric // Build a map of sections to the function that defines them, for use
4700b57cec5SDimitry Andric // in recordRelocation.
4710b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
4720b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
4730b57cec5SDimitry Andric if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4740b57cec5SDimitry Andric const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4750b57cec5SDimitry Andric auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4760b57cec5SDimitry Andric if (!Pair.second)
4770b57cec5SDimitry Andric report_fatal_error("section already has a defining function: " +
4785ffd83dbSDimitry Andric Sec.getName());
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric }
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric
recordRelocation(MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)4830b57cec5SDimitry Andric void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
4840b57cec5SDimitry Andric const MCAsmLayout &Layout,
4850b57cec5SDimitry Andric const MCFragment *Fragment,
4860b57cec5SDimitry Andric const MCFixup &Fixup, MCValue Target,
4870b57cec5SDimitry Andric uint64_t &FixedValue) {
4888bcb0991SDimitry Andric // The WebAssembly backend should never generate FKF_IsPCRel fixups
4898bcb0991SDimitry Andric assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
4908bcb0991SDimitry Andric MCFixupKindInfo::FKF_IsPCRel));
4918bcb0991SDimitry Andric
4920b57cec5SDimitry Andric const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
4930b57cec5SDimitry Andric uint64_t C = Target.getConstant();
4940b57cec5SDimitry Andric uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
4950b57cec5SDimitry Andric MCContext &Ctx = Asm.getContext();
496fe6060f1SDimitry Andric bool IsLocRel = false;
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
499fe6060f1SDimitry Andric
5008bcb0991SDimitry Andric const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
501fe6060f1SDimitry Andric
502fe6060f1SDimitry Andric if (FixupSection.getKind().isText()) {
503fe6060f1SDimitry Andric Ctx.reportError(Fixup.getLoc(),
5040b57cec5SDimitry Andric Twine("symbol '") + SymB.getName() +
505fe6060f1SDimitry Andric "' unsupported subtraction expression used in "
506fe6060f1SDimitry Andric "relocation in code section.");
5070b57cec5SDimitry Andric return;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric
510fe6060f1SDimitry Andric if (SymB.isUndefined()) {
511fe6060f1SDimitry Andric Ctx.reportError(Fixup.getLoc(),
512fe6060f1SDimitry Andric Twine("symbol '") + SymB.getName() +
513fe6060f1SDimitry Andric "' can not be undefined in a subtraction expression");
514fe6060f1SDimitry Andric return;
515fe6060f1SDimitry Andric }
516fe6060f1SDimitry Andric const MCSection &SecB = SymB.getSection();
517fe6060f1SDimitry Andric if (&SecB != &FixupSection) {
518fe6060f1SDimitry Andric Ctx.reportError(Fixup.getLoc(),
519fe6060f1SDimitry Andric Twine("symbol '") + SymB.getName() +
520fe6060f1SDimitry Andric "' can not be placed in a different section");
521fe6060f1SDimitry Andric return;
522fe6060f1SDimitry Andric }
523fe6060f1SDimitry Andric IsLocRel = true;
524fe6060f1SDimitry Andric C += FixupOffset - Layout.getSymbolOffset(SymB);
525fe6060f1SDimitry Andric }
526fe6060f1SDimitry Andric
5270b57cec5SDimitry Andric // We either rejected the fixup or folded B into C at this point.
5280b57cec5SDimitry Andric const MCSymbolRefExpr *RefA = Target.getSymA();
5298bcb0991SDimitry Andric const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
5300b57cec5SDimitry Andric
5315ffd83dbSDimitry Andric // The .init_array isn't translated as data, so don't do relocations in it.
5325f757f3fSDimitry Andric if (FixupSection.getName().starts_with(".init_array")) {
5335ffd83dbSDimitry Andric SymA->setUsedInInitArray();
5345ffd83dbSDimitry Andric return;
5355ffd83dbSDimitry Andric }
5365ffd83dbSDimitry Andric
5378bcb0991SDimitry Andric if (SymA->isVariable()) {
5380b57cec5SDimitry Andric const MCExpr *Expr = SymA->getVariableValue();
5395ffd83dbSDimitry Andric if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
5400b57cec5SDimitry Andric if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5410b57cec5SDimitry Andric llvm_unreachable("weakref used in reloc not yet implemented");
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric
5440b57cec5SDimitry Andric // Put any constant offset in an addend. Offsets can be negative, and
5450b57cec5SDimitry Andric // LLVM expects wrapping, in contrast to wasm's immediates which can't
5460b57cec5SDimitry Andric // be negative and don't wrap.
5470b57cec5SDimitry Andric FixedValue = 0;
5480b57cec5SDimitry Andric
549fe6060f1SDimitry Andric unsigned Type =
550fe6060f1SDimitry Andric TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
5510b57cec5SDimitry Andric
5520b57cec5SDimitry Andric // Absolute offset within a section or a function.
5535f757f3fSDimitry Andric // Currently only supported for metadata sections.
5540b57cec5SDimitry Andric // See: test/MC/WebAssembly/blockaddress.ll
555fe6060f1SDimitry Andric if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
556e8d8bef9SDimitry Andric Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
557fe6060f1SDimitry Andric Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
558fe6060f1SDimitry Andric SymA->isDefined()) {
559fe6060f1SDimitry Andric // SymA can be a temp data symbol that represents a function (in which case
560fe6060f1SDimitry Andric // it needs to be replaced by the section symbol), [XXX and it apparently
561fe6060f1SDimitry Andric // later gets changed again to a func symbol?] or it can be a real
562fe6060f1SDimitry Andric // function symbol, in which case it can be left as-is.
563fe6060f1SDimitry Andric
5640b57cec5SDimitry Andric if (!FixupSection.getKind().isMetadata())
5650b57cec5SDimitry Andric report_fatal_error("relocations for function or section offsets are "
5660b57cec5SDimitry Andric "only supported in metadata sections");
5670b57cec5SDimitry Andric
5680b57cec5SDimitry Andric const MCSymbol *SectionSymbol = nullptr;
5690b57cec5SDimitry Andric const MCSection &SecA = SymA->getSection();
570fe6060f1SDimitry Andric if (SecA.getKind().isText()) {
571fe6060f1SDimitry Andric auto SecSymIt = SectionFunctions.find(&SecA);
572fe6060f1SDimitry Andric if (SecSymIt == SectionFunctions.end())
573fe6060f1SDimitry Andric report_fatal_error("section doesn\'t have defining symbol");
574fe6060f1SDimitry Andric SectionSymbol = SecSymIt->second;
575fe6060f1SDimitry Andric } else {
5760b57cec5SDimitry Andric SectionSymbol = SecA.getBeginSymbol();
577fe6060f1SDimitry Andric }
5780b57cec5SDimitry Andric if (!SectionSymbol)
5790b57cec5SDimitry Andric report_fatal_error("section symbol is required for relocation");
5800b57cec5SDimitry Andric
5810b57cec5SDimitry Andric C += Layout.getSymbolOffset(*SymA);
5820b57cec5SDimitry Andric SymA = cast<MCSymbolWasm>(SectionSymbol);
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric
585e8d8bef9SDimitry Andric if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
586fe6060f1SDimitry Andric Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
587e8d8bef9SDimitry Andric Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
588e8d8bef9SDimitry Andric Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
589e8d8bef9SDimitry Andric Type == wasm::R_WASM_TABLE_INDEX_I32 ||
590e8d8bef9SDimitry Andric Type == wasm::R_WASM_TABLE_INDEX_I64) {
591e8d8bef9SDimitry Andric // TABLE_INDEX relocs implicitly use the default indirect function table.
592fe6060f1SDimitry Andric // We require the function table to have already been defined.
593e8d8bef9SDimitry Andric auto TableName = "__indirect_function_table";
594e8d8bef9SDimitry Andric MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
595fe6060f1SDimitry Andric if (!Sym) {
596fe6060f1SDimitry Andric report_fatal_error("missing indirect function table symbol");
597e8d8bef9SDimitry Andric } else {
598fe6060f1SDimitry Andric if (!Sym->isFunctionTable())
599fe6060f1SDimitry Andric report_fatal_error("__indirect_function_table symbol has wrong type");
600fe6060f1SDimitry Andric // Ensure that __indirect_function_table reaches the output.
601fe6060f1SDimitry Andric Sym->setNoStrip();
602e8d8bef9SDimitry Andric Asm.registerSymbol(*Sym);
603e8d8bef9SDimitry Andric }
604fe6060f1SDimitry Andric }
605e8d8bef9SDimitry Andric
6060b57cec5SDimitry Andric // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
6070b57cec5SDimitry Andric // against a named symbol.
6080b57cec5SDimitry Andric if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
6090b57cec5SDimitry Andric if (SymA->getName().empty())
6100b57cec5SDimitry Andric report_fatal_error("relocations against un-named temporaries are not yet "
6110b57cec5SDimitry Andric "supported by wasm");
6120b57cec5SDimitry Andric
6130b57cec5SDimitry Andric SymA->setUsedInReloc();
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric
616349cc55cSDimitry Andric switch (RefA->getKind()) {
617349cc55cSDimitry Andric case MCSymbolRefExpr::VK_GOT:
618349cc55cSDimitry Andric case MCSymbolRefExpr::VK_WASM_GOT_TLS:
6190b57cec5SDimitry Andric SymA->setUsedInGOT();
620349cc55cSDimitry Andric break;
621349cc55cSDimitry Andric default:
622349cc55cSDimitry Andric break;
623349cc55cSDimitry Andric }
6240b57cec5SDimitry Andric
6250b57cec5SDimitry Andric WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
6260b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
6270b57cec5SDimitry Andric
6280b57cec5SDimitry Andric if (FixupSection.isWasmData()) {
6290b57cec5SDimitry Andric DataRelocations.push_back(Rec);
6300b57cec5SDimitry Andric } else if (FixupSection.getKind().isText()) {
6310b57cec5SDimitry Andric CodeRelocations.push_back(Rec);
6320b57cec5SDimitry Andric } else if (FixupSection.getKind().isMetadata()) {
6330b57cec5SDimitry Andric CustomSectionsRelocations[&FixupSection].push_back(Rec);
6340b57cec5SDimitry Andric } else {
6350b57cec5SDimitry Andric llvm_unreachable("unexpected section type");
6360b57cec5SDimitry Andric }
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric
6390b57cec5SDimitry Andric // Compute a value to write into the code at the location covered
6400b57cec5SDimitry Andric // by RelEntry. This value isn't used by the static linker; it just serves
6410b57cec5SDimitry Andric // to make the object format more readable and more likely to be directly
6420b57cec5SDimitry Andric // useable.
6435ffd83dbSDimitry Andric uint64_t
getProvisionalValue(const WasmRelocationEntry & RelEntry,const MCAsmLayout & Layout)6445ffd83dbSDimitry Andric WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
6455ffd83dbSDimitry Andric const MCAsmLayout &Layout) {
6465ffd83dbSDimitry Andric if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
6475ffd83dbSDimitry Andric RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
6485ffd83dbSDimitry Andric !RelEntry.Symbol->isGlobal()) {
6490b57cec5SDimitry Andric assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
6500b57cec5SDimitry Andric return GOTIndices[RelEntry.Symbol];
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric
6530b57cec5SDimitry Andric switch (RelEntry.Type) {
6540b57cec5SDimitry Andric case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
655fe6060f1SDimitry Andric case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
6560b57cec5SDimitry Andric case wasm::R_WASM_TABLE_INDEX_SLEB:
657e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_INDEX_SLEB64:
658e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_INDEX_I32:
659e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_INDEX_I64: {
6600b57cec5SDimitry Andric // Provisional value is table address of the resolved symbol itself
6615ffd83dbSDimitry Andric const MCSymbolWasm *Base =
6625ffd83dbSDimitry Andric cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
6635ffd83dbSDimitry Andric assert(Base->isFunction());
664fe6060f1SDimitry Andric if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
665fe6060f1SDimitry Andric RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
6665ffd83dbSDimitry Andric return TableIndices[Base] - InitialTableOffset;
6675ffd83dbSDimitry Andric else
6685ffd83dbSDimitry Andric return TableIndices[Base];
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric case wasm::R_WASM_TYPE_INDEX_LEB:
6710b57cec5SDimitry Andric // Provisional value is same as the index
6720b57cec5SDimitry Andric return getRelocationIndexValue(RelEntry);
6730b57cec5SDimitry Andric case wasm::R_WASM_FUNCTION_INDEX_LEB:
67406c3fb27SDimitry Andric case wasm::R_WASM_FUNCTION_INDEX_I32:
6750b57cec5SDimitry Andric case wasm::R_WASM_GLOBAL_INDEX_LEB:
6765ffd83dbSDimitry Andric case wasm::R_WASM_GLOBAL_INDEX_I32:
677fe6060f1SDimitry Andric case wasm::R_WASM_TAG_INDEX_LEB:
678e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_NUMBER_LEB:
679fe6060f1SDimitry Andric // Provisional value is function/global/tag Wasm index
6800b57cec5SDimitry Andric assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6810b57cec5SDimitry Andric return WasmIndices[RelEntry.Symbol];
6820b57cec5SDimitry Andric case wasm::R_WASM_FUNCTION_OFFSET_I32:
683e8d8bef9SDimitry Andric case wasm::R_WASM_FUNCTION_OFFSET_I64:
6840b57cec5SDimitry Andric case wasm::R_WASM_SECTION_OFFSET_I32: {
685fe6060f1SDimitry Andric if (!RelEntry.Symbol->isDefined())
686fe6060f1SDimitry Andric return 0;
6870b57cec5SDimitry Andric const auto &Section =
6880b57cec5SDimitry Andric static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6890b57cec5SDimitry Andric return Section.getSectionOffset() + RelEntry.Addend;
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LEB:
6925ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LEB64:
6935ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_SLEB:
6945ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6950b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6965ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6975ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_I32:
698e8d8bef9SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_I64:
699fe6060f1SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
700fe6060f1SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
701fe6060f1SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
702e8d8bef9SDimitry Andric // Provisional value is address of the global plus the offset
7030b57cec5SDimitry Andric // For undefined symbols, use zero
704fe6060f1SDimitry Andric if (!RelEntry.Symbol->isDefined())
7050b57cec5SDimitry Andric return 0;
706fe6060f1SDimitry Andric const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
707fe6060f1SDimitry Andric const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
7080b57cec5SDimitry Andric // Ignore overflow. LLVM allows address arithmetic to silently wrap.
709fe6060f1SDimitry Andric return Segment.Offset + SymRef.Offset + RelEntry.Addend;
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric default:
7120b57cec5SDimitry Andric llvm_unreachable("invalid relocation type");
7130b57cec5SDimitry Andric }
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric
addData(SmallVectorImpl<char> & DataBytes,MCSectionWasm & DataSection)7160b57cec5SDimitry Andric static void addData(SmallVectorImpl<char> &DataBytes,
7170b57cec5SDimitry Andric MCSectionWasm &DataSection) {
7185ffd83dbSDimitry Andric LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
7190b57cec5SDimitry Andric
720bdd1243dSDimitry Andric DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlign()));
7210b57cec5SDimitry Andric
7220b57cec5SDimitry Andric for (const MCFragment &Frag : DataSection) {
7230b57cec5SDimitry Andric if (Frag.hasInstructions())
7240b57cec5SDimitry Andric report_fatal_error("only data supported in data sections");
7250b57cec5SDimitry Andric
7260b57cec5SDimitry Andric if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
7270b57cec5SDimitry Andric if (Align->getValueSize() != 1)
7280b57cec5SDimitry Andric report_fatal_error("only byte values supported for alignment");
7290b57cec5SDimitry Andric // If nops are requested, use zeros, as this is the data section.
7300b57cec5SDimitry Andric uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
7310b57cec5SDimitry Andric uint64_t Size =
7320b57cec5SDimitry Andric std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
7330b57cec5SDimitry Andric DataBytes.size() + Align->getMaxBytesToEmit());
7340b57cec5SDimitry Andric DataBytes.resize(Size, Value);
7350b57cec5SDimitry Andric } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
7360b57cec5SDimitry Andric int64_t NumValues;
7370b57cec5SDimitry Andric if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
7380b57cec5SDimitry Andric llvm_unreachable("The fill should be an assembler constant");
7390b57cec5SDimitry Andric DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
7400b57cec5SDimitry Andric Fill->getValue());
7410b57cec5SDimitry Andric } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
7420b57cec5SDimitry Andric const SmallVectorImpl<char> &Contents = LEB->getContents();
743e8d8bef9SDimitry Andric llvm::append_range(DataBytes, Contents);
7440b57cec5SDimitry Andric } else {
7450b57cec5SDimitry Andric const auto &DataFrag = cast<MCDataFragment>(Frag);
7460b57cec5SDimitry Andric const SmallVectorImpl<char> &Contents = DataFrag.getContents();
747e8d8bef9SDimitry Andric llvm::append_range(DataBytes, Contents);
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric }
7500b57cec5SDimitry Andric
7510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric
7540b57cec5SDimitry Andric uint32_t
getRelocationIndexValue(const WasmRelocationEntry & RelEntry)7550b57cec5SDimitry Andric WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
7560b57cec5SDimitry Andric if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
7570b57cec5SDimitry Andric if (!TypeIndices.count(RelEntry.Symbol))
7580b57cec5SDimitry Andric report_fatal_error("symbol not found in type index space: " +
7590b57cec5SDimitry Andric RelEntry.Symbol->getName());
7600b57cec5SDimitry Andric return TypeIndices[RelEntry.Symbol];
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric
7630b57cec5SDimitry Andric return RelEntry.Symbol->getIndex();
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric
7660b57cec5SDimitry Andric // Apply the portions of the relocation records that we can handle ourselves
7670b57cec5SDimitry Andric // directly.
applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,uint64_t ContentsOffset,const MCAsmLayout & Layout)7680b57cec5SDimitry Andric void WasmObjectWriter::applyRelocations(
7695ffd83dbSDimitry Andric ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
7705ffd83dbSDimitry Andric const MCAsmLayout &Layout) {
771e8d8bef9SDimitry Andric auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
7720b57cec5SDimitry Andric for (const WasmRelocationEntry &RelEntry : Relocations) {
7730b57cec5SDimitry Andric uint64_t Offset = ContentsOffset +
7740b57cec5SDimitry Andric RelEntry.FixupSection->getSectionOffset() +
7750b57cec5SDimitry Andric RelEntry.Offset;
7760b57cec5SDimitry Andric
7770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
778fb03ea46SDimitry Andric uint64_t Value = getProvisionalValue(RelEntry, Layout);
7790b57cec5SDimitry Andric
7800b57cec5SDimitry Andric switch (RelEntry.Type) {
7810b57cec5SDimitry Andric case wasm::R_WASM_FUNCTION_INDEX_LEB:
7820b57cec5SDimitry Andric case wasm::R_WASM_TYPE_INDEX_LEB:
7830b57cec5SDimitry Andric case wasm::R_WASM_GLOBAL_INDEX_LEB:
7840b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LEB:
785fe6060f1SDimitry Andric case wasm::R_WASM_TAG_INDEX_LEB:
786e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_NUMBER_LEB:
787fb03ea46SDimitry Andric writePatchableU32(Stream, Value, Offset);
7885ffd83dbSDimitry Andric break;
7895ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LEB64:
790fb03ea46SDimitry Andric writePatchableU64(Stream, Value, Offset);
7910b57cec5SDimitry Andric break;
7920b57cec5SDimitry Andric case wasm::R_WASM_TABLE_INDEX_I32:
7930b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_I32:
7940b57cec5SDimitry Andric case wasm::R_WASM_FUNCTION_OFFSET_I32:
79506c3fb27SDimitry Andric case wasm::R_WASM_FUNCTION_INDEX_I32:
7960b57cec5SDimitry Andric case wasm::R_WASM_SECTION_OFFSET_I32:
7975ffd83dbSDimitry Andric case wasm::R_WASM_GLOBAL_INDEX_I32:
798fe6060f1SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
7995ffd83dbSDimitry Andric patchI32(Stream, Value, Offset);
8005ffd83dbSDimitry Andric break;
801e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_INDEX_I64:
8025ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_I64:
803e8d8bef9SDimitry Andric case wasm::R_WASM_FUNCTION_OFFSET_I64:
8045ffd83dbSDimitry Andric patchI64(Stream, Value, Offset);
8050b57cec5SDimitry Andric break;
8060b57cec5SDimitry Andric case wasm::R_WASM_TABLE_INDEX_SLEB:
8070b57cec5SDimitry Andric case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
8080b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_SLEB:
8090b57cec5SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
810e8d8bef9SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
811fb03ea46SDimitry Andric writePatchableS32(Stream, Value, Offset);
8125ffd83dbSDimitry Andric break;
813e8d8bef9SDimitry Andric case wasm::R_WASM_TABLE_INDEX_SLEB64:
814fe6060f1SDimitry Andric case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
8155ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_SLEB64:
8165ffd83dbSDimitry Andric case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
817fe6060f1SDimitry Andric case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
818fb03ea46SDimitry Andric writePatchableS64(Stream, Value, Offset);
8190b57cec5SDimitry Andric break;
8200b57cec5SDimitry Andric default:
8210b57cec5SDimitry Andric llvm_unreachable("invalid relocation type");
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric
writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures)826e8d8bef9SDimitry Andric void WasmObjectWriter::writeTypeSection(
827e8d8bef9SDimitry Andric ArrayRef<wasm::WasmSignature> Signatures) {
8280b57cec5SDimitry Andric if (Signatures.empty())
8290b57cec5SDimitry Andric return;
8300b57cec5SDimitry Andric
8310b57cec5SDimitry Andric SectionBookkeeping Section;
8320b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_TYPE);
8330b57cec5SDimitry Andric
834e8d8bef9SDimitry Andric encodeULEB128(Signatures.size(), W->OS);
8350b57cec5SDimitry Andric
836e8d8bef9SDimitry Andric for (const wasm::WasmSignature &Sig : Signatures) {
837e8d8bef9SDimitry Andric W->OS << char(wasm::WASM_TYPE_FUNC);
838e8d8bef9SDimitry Andric encodeULEB128(Sig.Params.size(), W->OS);
8390b57cec5SDimitry Andric for (wasm::ValType Ty : Sig.Params)
8400b57cec5SDimitry Andric writeValueType(Ty);
841e8d8bef9SDimitry Andric encodeULEB128(Sig.Returns.size(), W->OS);
8420b57cec5SDimitry Andric for (wasm::ValType Ty : Sig.Returns)
8430b57cec5SDimitry Andric writeValueType(Ty);
8440b57cec5SDimitry Andric }
8450b57cec5SDimitry Andric
8460b57cec5SDimitry Andric endSection(Section);
8470b57cec5SDimitry Andric }
8480b57cec5SDimitry Andric
writeImportSection(ArrayRef<wasm::WasmImport> Imports,uint64_t DataSize,uint32_t NumElements)8490b57cec5SDimitry Andric void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
8505ffd83dbSDimitry Andric uint64_t DataSize,
8510b57cec5SDimitry Andric uint32_t NumElements) {
8520b57cec5SDimitry Andric if (Imports.empty())
8530b57cec5SDimitry Andric return;
8540b57cec5SDimitry Andric
8555ffd83dbSDimitry Andric uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
8560b57cec5SDimitry Andric
8570b57cec5SDimitry Andric SectionBookkeeping Section;
8580b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_IMPORT);
8590b57cec5SDimitry Andric
860e8d8bef9SDimitry Andric encodeULEB128(Imports.size(), W->OS);
8610b57cec5SDimitry Andric for (const wasm::WasmImport &Import : Imports) {
8620b57cec5SDimitry Andric writeString(Import.Module);
8630b57cec5SDimitry Andric writeString(Import.Field);
864e8d8bef9SDimitry Andric W->OS << char(Import.Kind);
8650b57cec5SDimitry Andric
8660b57cec5SDimitry Andric switch (Import.Kind) {
8670b57cec5SDimitry Andric case wasm::WASM_EXTERNAL_FUNCTION:
868e8d8bef9SDimitry Andric encodeULEB128(Import.SigIndex, W->OS);
8690b57cec5SDimitry Andric break;
8700b57cec5SDimitry Andric case wasm::WASM_EXTERNAL_GLOBAL:
871e8d8bef9SDimitry Andric W->OS << char(Import.Global.Type);
872e8d8bef9SDimitry Andric W->OS << char(Import.Global.Mutable ? 1 : 0);
8730b57cec5SDimitry Andric break;
8740b57cec5SDimitry Andric case wasm::WASM_EXTERNAL_MEMORY:
875e8d8bef9SDimitry Andric encodeULEB128(Import.Memory.Flags, W->OS);
876e8d8bef9SDimitry Andric encodeULEB128(NumPages, W->OS); // initial
8770b57cec5SDimitry Andric break;
8780b57cec5SDimitry Andric case wasm::WASM_EXTERNAL_TABLE:
879e8d8bef9SDimitry Andric W->OS << char(Import.Table.ElemType);
880e8d8bef9SDimitry Andric encodeULEB128(0, W->OS); // flags
881e8d8bef9SDimitry Andric encodeULEB128(NumElements, W->OS); // initial
8820b57cec5SDimitry Andric break;
883fe6060f1SDimitry Andric case wasm::WASM_EXTERNAL_TAG:
884349cc55cSDimitry Andric W->OS << char(0); // Reserved 'attribute' field
885349cc55cSDimitry Andric encodeULEB128(Import.SigIndex, W->OS);
8860b57cec5SDimitry Andric break;
8870b57cec5SDimitry Andric default:
8880b57cec5SDimitry Andric llvm_unreachable("unsupported import kind");
8890b57cec5SDimitry Andric }
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric
8920b57cec5SDimitry Andric endSection(Section);
8930b57cec5SDimitry Andric }
8940b57cec5SDimitry Andric
writeFunctionSection(ArrayRef<WasmFunction> Functions)8950b57cec5SDimitry Andric void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8960b57cec5SDimitry Andric if (Functions.empty())
8970b57cec5SDimitry Andric return;
8980b57cec5SDimitry Andric
8990b57cec5SDimitry Andric SectionBookkeeping Section;
9000b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_FUNCTION);
9010b57cec5SDimitry Andric
902e8d8bef9SDimitry Andric encodeULEB128(Functions.size(), W->OS);
9030b57cec5SDimitry Andric for (const WasmFunction &Func : Functions)
904e8d8bef9SDimitry Andric encodeULEB128(Func.SigIndex, W->OS);
9050b57cec5SDimitry Andric
9060b57cec5SDimitry Andric endSection(Section);
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric
writeTagSection(ArrayRef<uint32_t> TagTypes)909349cc55cSDimitry Andric void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) {
910349cc55cSDimitry Andric if (TagTypes.empty())
9110b57cec5SDimitry Andric return;
9120b57cec5SDimitry Andric
9130b57cec5SDimitry Andric SectionBookkeeping Section;
914fe6060f1SDimitry Andric startSection(Section, wasm::WASM_SEC_TAG);
9150b57cec5SDimitry Andric
916349cc55cSDimitry Andric encodeULEB128(TagTypes.size(), W->OS);
917349cc55cSDimitry Andric for (uint32_t Index : TagTypes) {
918349cc55cSDimitry Andric W->OS << char(0); // Reserved 'attribute' field
919349cc55cSDimitry Andric encodeULEB128(Index, W->OS);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric
9220b57cec5SDimitry Andric endSection(Section);
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric
writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals)9255ffd83dbSDimitry Andric void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
9265ffd83dbSDimitry Andric if (Globals.empty())
9275ffd83dbSDimitry Andric return;
9285ffd83dbSDimitry Andric
9295ffd83dbSDimitry Andric SectionBookkeeping Section;
9305ffd83dbSDimitry Andric startSection(Section, wasm::WASM_SEC_GLOBAL);
9315ffd83dbSDimitry Andric
932e8d8bef9SDimitry Andric encodeULEB128(Globals.size(), W->OS);
9335ffd83dbSDimitry Andric for (const wasm::WasmGlobal &Global : Globals) {
934e8d8bef9SDimitry Andric encodeULEB128(Global.Type.Type, W->OS);
935e8d8bef9SDimitry Andric W->OS << char(Global.Type.Mutable);
93681ad6265SDimitry Andric if (Global.InitExpr.Extended) {
93781ad6265SDimitry Andric llvm_unreachable("extected init expressions not supported");
93881ad6265SDimitry Andric } else {
93981ad6265SDimitry Andric W->OS << char(Global.InitExpr.Inst.Opcode);
9405ffd83dbSDimitry Andric switch (Global.Type.Type) {
9415ffd83dbSDimitry Andric case wasm::WASM_TYPE_I32:
942e8d8bef9SDimitry Andric encodeSLEB128(0, W->OS);
9435ffd83dbSDimitry Andric break;
9445ffd83dbSDimitry Andric case wasm::WASM_TYPE_I64:
945e8d8bef9SDimitry Andric encodeSLEB128(0, W->OS);
9465ffd83dbSDimitry Andric break;
9475ffd83dbSDimitry Andric case wasm::WASM_TYPE_F32:
9485ffd83dbSDimitry Andric writeI32(0);
9495ffd83dbSDimitry Andric break;
9505ffd83dbSDimitry Andric case wasm::WASM_TYPE_F64:
9515ffd83dbSDimitry Andric writeI64(0);
9525ffd83dbSDimitry Andric break;
9535ffd83dbSDimitry Andric case wasm::WASM_TYPE_EXTERNREF:
9545ffd83dbSDimitry Andric writeValueType(wasm::ValType::EXTERNREF);
9555ffd83dbSDimitry Andric break;
9565ffd83dbSDimitry Andric default:
9575ffd83dbSDimitry Andric llvm_unreachable("unexpected type");
9585ffd83dbSDimitry Andric }
95981ad6265SDimitry Andric }
960e8d8bef9SDimitry Andric W->OS << char(wasm::WASM_OPCODE_END);
9615ffd83dbSDimitry Andric }
9625ffd83dbSDimitry Andric
9635ffd83dbSDimitry Andric endSection(Section);
9645ffd83dbSDimitry Andric }
9655ffd83dbSDimitry Andric
writeTableSection(ArrayRef<wasm::WasmTable> Tables)966e8d8bef9SDimitry Andric void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
967e8d8bef9SDimitry Andric if (Tables.empty())
968e8d8bef9SDimitry Andric return;
969e8d8bef9SDimitry Andric
970e8d8bef9SDimitry Andric SectionBookkeeping Section;
971e8d8bef9SDimitry Andric startSection(Section, wasm::WASM_SEC_TABLE);
972e8d8bef9SDimitry Andric
973e8d8bef9SDimitry Andric encodeULEB128(Tables.size(), W->OS);
974e8d8bef9SDimitry Andric for (const wasm::WasmTable &Table : Tables) {
9757a6dacacSDimitry Andric encodeULEB128((uint32_t)Table.Type.ElemType, W->OS);
976e8d8bef9SDimitry Andric encodeULEB128(Table.Type.Limits.Flags, W->OS);
977fe6060f1SDimitry Andric encodeULEB128(Table.Type.Limits.Minimum, W->OS);
978e8d8bef9SDimitry Andric if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
979e8d8bef9SDimitry Andric encodeULEB128(Table.Type.Limits.Maximum, W->OS);
980e8d8bef9SDimitry Andric }
981e8d8bef9SDimitry Andric endSection(Section);
982e8d8bef9SDimitry Andric }
983e8d8bef9SDimitry Andric
writeExportSection(ArrayRef<wasm::WasmExport> Exports)9840b57cec5SDimitry Andric void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
9850b57cec5SDimitry Andric if (Exports.empty())
9860b57cec5SDimitry Andric return;
9870b57cec5SDimitry Andric
9880b57cec5SDimitry Andric SectionBookkeeping Section;
9890b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_EXPORT);
9900b57cec5SDimitry Andric
991e8d8bef9SDimitry Andric encodeULEB128(Exports.size(), W->OS);
9920b57cec5SDimitry Andric for (const wasm::WasmExport &Export : Exports) {
9930b57cec5SDimitry Andric writeString(Export.Name);
994e8d8bef9SDimitry Andric W->OS << char(Export.Kind);
995e8d8bef9SDimitry Andric encodeULEB128(Export.Index, W->OS);
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric
9980b57cec5SDimitry Andric endSection(Section);
9990b57cec5SDimitry Andric }
10000b57cec5SDimitry Andric
writeElemSection(const MCSymbolWasm * IndirectFunctionTable,ArrayRef<uint32_t> TableElems)1001fe6060f1SDimitry Andric void WasmObjectWriter::writeElemSection(
1002fe6060f1SDimitry Andric const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
10030b57cec5SDimitry Andric if (TableElems.empty())
10040b57cec5SDimitry Andric return;
10050b57cec5SDimitry Andric
1006fe6060f1SDimitry Andric assert(IndirectFunctionTable);
1007fe6060f1SDimitry Andric
10080b57cec5SDimitry Andric SectionBookkeeping Section;
10090b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_ELEM);
10100b57cec5SDimitry Andric
1011e8d8bef9SDimitry Andric encodeULEB128(1, W->OS); // number of "segments"
1012fe6060f1SDimitry Andric
1013fe6060f1SDimitry Andric assert(WasmIndices.count(IndirectFunctionTable));
1014fe6060f1SDimitry Andric uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
1015fe6060f1SDimitry Andric uint32_t Flags = 0;
1016fe6060f1SDimitry Andric if (TableNumber)
1017fe6060f1SDimitry Andric Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
1018fe6060f1SDimitry Andric encodeULEB128(Flags, W->OS);
1019fe6060f1SDimitry Andric if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
1020fe6060f1SDimitry Andric encodeULEB128(TableNumber, W->OS); // the table number
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric // init expr for starting offset
1023e8d8bef9SDimitry Andric W->OS << char(wasm::WASM_OPCODE_I32_CONST);
1024e8d8bef9SDimitry Andric encodeSLEB128(InitialTableOffset, W->OS);
1025e8d8bef9SDimitry Andric W->OS << char(wasm::WASM_OPCODE_END);
10260b57cec5SDimitry Andric
1027fe6060f1SDimitry Andric if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
1028fe6060f1SDimitry Andric // We only write active function table initializers, for which the elem kind
1029fe6060f1SDimitry Andric // is specified to be written as 0x00 and interpreted to mean "funcref".
1030fe6060f1SDimitry Andric const uint8_t ElemKind = 0;
1031fe6060f1SDimitry Andric W->OS << ElemKind;
1032fe6060f1SDimitry Andric }
1033fe6060f1SDimitry Andric
1034e8d8bef9SDimitry Andric encodeULEB128(TableElems.size(), W->OS);
10350b57cec5SDimitry Andric for (uint32_t Elem : TableElems)
1036e8d8bef9SDimitry Andric encodeULEB128(Elem, W->OS);
10370b57cec5SDimitry Andric
10380b57cec5SDimitry Andric endSection(Section);
10390b57cec5SDimitry Andric }
10400b57cec5SDimitry Andric
writeDataCountSection()10410b57cec5SDimitry Andric void WasmObjectWriter::writeDataCountSection() {
10420b57cec5SDimitry Andric if (DataSegments.empty())
10430b57cec5SDimitry Andric return;
10440b57cec5SDimitry Andric
10450b57cec5SDimitry Andric SectionBookkeeping Section;
10460b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_DATACOUNT);
1047e8d8bef9SDimitry Andric encodeULEB128(DataSegments.size(), W->OS);
10480b57cec5SDimitry Andric endSection(Section);
10490b57cec5SDimitry Andric }
10500b57cec5SDimitry Andric
writeCodeSection(const MCAssembler & Asm,const MCAsmLayout & Layout,ArrayRef<WasmFunction> Functions)10515ffd83dbSDimitry Andric uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
10520b57cec5SDimitry Andric const MCAsmLayout &Layout,
10530b57cec5SDimitry Andric ArrayRef<WasmFunction> Functions) {
10540b57cec5SDimitry Andric if (Functions.empty())
10555ffd83dbSDimitry Andric return 0;
10560b57cec5SDimitry Andric
10570b57cec5SDimitry Andric SectionBookkeeping Section;
10580b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_CODE);
10590b57cec5SDimitry Andric
1060e8d8bef9SDimitry Andric encodeULEB128(Functions.size(), W->OS);
10610b57cec5SDimitry Andric
10620b57cec5SDimitry Andric for (const WasmFunction &Func : Functions) {
1063bdd1243dSDimitry Andric auto *FuncSection = static_cast<MCSectionWasm *>(Func.Section);
10640b57cec5SDimitry Andric
1065bdd1243dSDimitry Andric int64_t Size = Layout.getSectionAddressSize(FuncSection);
1066e8d8bef9SDimitry Andric encodeULEB128(Size, W->OS);
1067bdd1243dSDimitry Andric FuncSection->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1068bdd1243dSDimitry Andric Asm.writeSectionData(W->OS, FuncSection, Layout);
10690b57cec5SDimitry Andric }
10700b57cec5SDimitry Andric
10710b57cec5SDimitry Andric // Apply fixups.
10725ffd83dbSDimitry Andric applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
10730b57cec5SDimitry Andric
10740b57cec5SDimitry Andric endSection(Section);
10755ffd83dbSDimitry Andric return Section.Index;
10760b57cec5SDimitry Andric }
10770b57cec5SDimitry Andric
writeDataSection(const MCAsmLayout & Layout)10785ffd83dbSDimitry Andric uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
10790b57cec5SDimitry Andric if (DataSegments.empty())
10805ffd83dbSDimitry Andric return 0;
10810b57cec5SDimitry Andric
10820b57cec5SDimitry Andric SectionBookkeeping Section;
10830b57cec5SDimitry Andric startSection(Section, wasm::WASM_SEC_DATA);
10840b57cec5SDimitry Andric
1085e8d8bef9SDimitry Andric encodeULEB128(DataSegments.size(), W->OS); // count
10860b57cec5SDimitry Andric
10870b57cec5SDimitry Andric for (const WasmDataSegment &Segment : DataSegments) {
1088e8d8bef9SDimitry Andric encodeULEB128(Segment.InitFlags, W->OS); // flags
1089e8d8bef9SDimitry Andric if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
1090e8d8bef9SDimitry Andric encodeULEB128(0, W->OS); // memory index
1091e8d8bef9SDimitry Andric if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
1092fe6060f1SDimitry Andric W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
10935ffd83dbSDimitry Andric : wasm::WASM_OPCODE_I32_CONST);
1094e8d8bef9SDimitry Andric encodeSLEB128(Segment.Offset, W->OS); // offset
1095e8d8bef9SDimitry Andric W->OS << char(wasm::WASM_OPCODE_END);
10960b57cec5SDimitry Andric }
1097e8d8bef9SDimitry Andric encodeULEB128(Segment.Data.size(), W->OS); // size
1098e8d8bef9SDimitry Andric Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1099e8d8bef9SDimitry Andric W->OS << Segment.Data; // data
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric
11020b57cec5SDimitry Andric // Apply fixups.
11035ffd83dbSDimitry Andric applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
11040b57cec5SDimitry Andric
11050b57cec5SDimitry Andric endSection(Section);
11065ffd83dbSDimitry Andric return Section.Index;
11070b57cec5SDimitry Andric }
11080b57cec5SDimitry Andric
writeRelocSection(uint32_t SectionIndex,StringRef Name,std::vector<WasmRelocationEntry> & Relocs)11090b57cec5SDimitry Andric void WasmObjectWriter::writeRelocSection(
11100b57cec5SDimitry Andric uint32_t SectionIndex, StringRef Name,
11110b57cec5SDimitry Andric std::vector<WasmRelocationEntry> &Relocs) {
1112349cc55cSDimitry Andric // See: https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md
11130b57cec5SDimitry Andric // for descriptions of the reloc sections.
11140b57cec5SDimitry Andric
11150b57cec5SDimitry Andric if (Relocs.empty())
11160b57cec5SDimitry Andric return;
11170b57cec5SDimitry Andric
11180b57cec5SDimitry Andric // First, ensure the relocations are sorted in offset order. In general they
11190b57cec5SDimitry Andric // should already be sorted since `recordRelocation` is called in offset
11200b57cec5SDimitry Andric // order, but for the code section we combine many MC sections into single
11210b57cec5SDimitry Andric // wasm section, and this order is determined by the order of Asm.Symbols()
11220b57cec5SDimitry Andric // not the sections order.
11230b57cec5SDimitry Andric llvm::stable_sort(
11240b57cec5SDimitry Andric Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
11250b57cec5SDimitry Andric return (A.Offset + A.FixupSection->getSectionOffset()) <
11260b57cec5SDimitry Andric (B.Offset + B.FixupSection->getSectionOffset());
11270b57cec5SDimitry Andric });
11280b57cec5SDimitry Andric
11290b57cec5SDimitry Andric SectionBookkeeping Section;
11300b57cec5SDimitry Andric startCustomSection(Section, std::string("reloc.") + Name.str());
11310b57cec5SDimitry Andric
1132e8d8bef9SDimitry Andric encodeULEB128(SectionIndex, W->OS);
1133e8d8bef9SDimitry Andric encodeULEB128(Relocs.size(), W->OS);
11340b57cec5SDimitry Andric for (const WasmRelocationEntry &RelEntry : Relocs) {
11350b57cec5SDimitry Andric uint64_t Offset =
11360b57cec5SDimitry Andric RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
11370b57cec5SDimitry Andric uint32_t Index = getRelocationIndexValue(RelEntry);
11380b57cec5SDimitry Andric
1139e8d8bef9SDimitry Andric W->OS << char(RelEntry.Type);
1140e8d8bef9SDimitry Andric encodeULEB128(Offset, W->OS);
1141e8d8bef9SDimitry Andric encodeULEB128(Index, W->OS);
11420b57cec5SDimitry Andric if (RelEntry.hasAddend())
1143e8d8bef9SDimitry Andric encodeSLEB128(RelEntry.Addend, W->OS);
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric
11460b57cec5SDimitry Andric endSection(Section);
11470b57cec5SDimitry Andric }
11480b57cec5SDimitry Andric
writeCustomRelocSections()11490b57cec5SDimitry Andric void WasmObjectWriter::writeCustomRelocSections() {
11500b57cec5SDimitry Andric for (const auto &Sec : CustomSections) {
11510b57cec5SDimitry Andric auto &Relocations = CustomSectionsRelocations[Sec.Section];
11520b57cec5SDimitry Andric writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric }
11550b57cec5SDimitry Andric
writeLinkingMetaDataSection(ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,ArrayRef<std::pair<uint16_t,uint32_t>> InitFuncs,const std::map<StringRef,std::vector<WasmComdatEntry>> & Comdats)11560b57cec5SDimitry Andric void WasmObjectWriter::writeLinkingMetaDataSection(
11570b57cec5SDimitry Andric ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
11580b57cec5SDimitry Andric ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
11590b57cec5SDimitry Andric const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
11600b57cec5SDimitry Andric SectionBookkeeping Section;
11610b57cec5SDimitry Andric startCustomSection(Section, "linking");
1162e8d8bef9SDimitry Andric encodeULEB128(wasm::WasmMetadataVersion, W->OS);
11630b57cec5SDimitry Andric
11640b57cec5SDimitry Andric SectionBookkeeping SubSection;
11650b57cec5SDimitry Andric if (SymbolInfos.size() != 0) {
11660b57cec5SDimitry Andric startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1167e8d8bef9SDimitry Andric encodeULEB128(SymbolInfos.size(), W->OS);
11680b57cec5SDimitry Andric for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1169e8d8bef9SDimitry Andric encodeULEB128(Sym.Kind, W->OS);
1170e8d8bef9SDimitry Andric encodeULEB128(Sym.Flags, W->OS);
11710b57cec5SDimitry Andric switch (Sym.Kind) {
11720b57cec5SDimitry Andric case wasm::WASM_SYMBOL_TYPE_FUNCTION:
11730b57cec5SDimitry Andric case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1174fe6060f1SDimitry Andric case wasm::WASM_SYMBOL_TYPE_TAG:
1175e8d8bef9SDimitry Andric case wasm::WASM_SYMBOL_TYPE_TABLE:
1176e8d8bef9SDimitry Andric encodeULEB128(Sym.ElementIndex, W->OS);
11770b57cec5SDimitry Andric if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
11780b57cec5SDimitry Andric (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
11790b57cec5SDimitry Andric writeString(Sym.Name);
11800b57cec5SDimitry Andric break;
11810b57cec5SDimitry Andric case wasm::WASM_SYMBOL_TYPE_DATA:
11820b57cec5SDimitry Andric writeString(Sym.Name);
11830b57cec5SDimitry Andric if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1184e8d8bef9SDimitry Andric encodeULEB128(Sym.DataRef.Segment, W->OS);
1185e8d8bef9SDimitry Andric encodeULEB128(Sym.DataRef.Offset, W->OS);
1186e8d8bef9SDimitry Andric encodeULEB128(Sym.DataRef.Size, W->OS);
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric break;
11890b57cec5SDimitry Andric case wasm::WASM_SYMBOL_TYPE_SECTION: {
11900b57cec5SDimitry Andric const uint32_t SectionIndex =
11910b57cec5SDimitry Andric CustomSections[Sym.ElementIndex].OutputIndex;
1192e8d8bef9SDimitry Andric encodeULEB128(SectionIndex, W->OS);
11930b57cec5SDimitry Andric break;
11940b57cec5SDimitry Andric }
11950b57cec5SDimitry Andric default:
11960b57cec5SDimitry Andric llvm_unreachable("unexpected kind");
11970b57cec5SDimitry Andric }
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric endSection(SubSection);
12000b57cec5SDimitry Andric }
12010b57cec5SDimitry Andric
12020b57cec5SDimitry Andric if (DataSegments.size()) {
12030b57cec5SDimitry Andric startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1204e8d8bef9SDimitry Andric encodeULEB128(DataSegments.size(), W->OS);
12050b57cec5SDimitry Andric for (const WasmDataSegment &Segment : DataSegments) {
12060b57cec5SDimitry Andric writeString(Segment.Name);
1207e8d8bef9SDimitry Andric encodeULEB128(Segment.Alignment, W->OS);
1208fe6060f1SDimitry Andric encodeULEB128(Segment.LinkingFlags, W->OS);
12090b57cec5SDimitry Andric }
12100b57cec5SDimitry Andric endSection(SubSection);
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric
12130b57cec5SDimitry Andric if (!InitFuncs.empty()) {
12140b57cec5SDimitry Andric startSection(SubSection, wasm::WASM_INIT_FUNCS);
1215e8d8bef9SDimitry Andric encodeULEB128(InitFuncs.size(), W->OS);
12160b57cec5SDimitry Andric for (auto &StartFunc : InitFuncs) {
1217e8d8bef9SDimitry Andric encodeULEB128(StartFunc.first, W->OS); // priority
1218e8d8bef9SDimitry Andric encodeULEB128(StartFunc.second, W->OS); // function index
12190b57cec5SDimitry Andric }
12200b57cec5SDimitry Andric endSection(SubSection);
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric
12230b57cec5SDimitry Andric if (Comdats.size()) {
12240b57cec5SDimitry Andric startSection(SubSection, wasm::WASM_COMDAT_INFO);
1225e8d8bef9SDimitry Andric encodeULEB128(Comdats.size(), W->OS);
12260b57cec5SDimitry Andric for (const auto &C : Comdats) {
12270b57cec5SDimitry Andric writeString(C.first);
1228e8d8bef9SDimitry Andric encodeULEB128(0, W->OS); // flags for future use
1229e8d8bef9SDimitry Andric encodeULEB128(C.second.size(), W->OS);
12300b57cec5SDimitry Andric for (const WasmComdatEntry &Entry : C.second) {
1231e8d8bef9SDimitry Andric encodeULEB128(Entry.Kind, W->OS);
1232e8d8bef9SDimitry Andric encodeULEB128(Entry.Index, W->OS);
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric }
12350b57cec5SDimitry Andric endSection(SubSection);
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric
12380b57cec5SDimitry Andric endSection(Section);
12390b57cec5SDimitry Andric }
12400b57cec5SDimitry Andric
writeCustomSection(WasmCustomSection & CustomSection,const MCAssembler & Asm,const MCAsmLayout & Layout)12410b57cec5SDimitry Andric void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
12420b57cec5SDimitry Andric const MCAssembler &Asm,
12430b57cec5SDimitry Andric const MCAsmLayout &Layout) {
12440b57cec5SDimitry Andric SectionBookkeeping Section;
12450b57cec5SDimitry Andric auto *Sec = CustomSection.Section;
12460b57cec5SDimitry Andric startCustomSection(Section, CustomSection.Name);
12470b57cec5SDimitry Andric
1248e8d8bef9SDimitry Andric Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1249e8d8bef9SDimitry Andric Asm.writeSectionData(W->OS, Sec, Layout);
12500b57cec5SDimitry Andric
12510b57cec5SDimitry Andric CustomSection.OutputContentsOffset = Section.ContentsOffset;
12520b57cec5SDimitry Andric CustomSection.OutputIndex = Section.Index;
12530b57cec5SDimitry Andric
12540b57cec5SDimitry Andric endSection(Section);
12550b57cec5SDimitry Andric
12560b57cec5SDimitry Andric // Apply fixups.
12570b57cec5SDimitry Andric auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
12585ffd83dbSDimitry Andric applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
12590b57cec5SDimitry Andric }
12600b57cec5SDimitry Andric
getFunctionType(const MCSymbolWasm & Symbol)12610b57cec5SDimitry Andric uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
12620b57cec5SDimitry Andric assert(Symbol.isFunction());
12630b57cec5SDimitry Andric assert(TypeIndices.count(&Symbol));
12640b57cec5SDimitry Andric return TypeIndices[&Symbol];
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric
getTagType(const MCSymbolWasm & Symbol)1267fe6060f1SDimitry Andric uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) {
1268fe6060f1SDimitry Andric assert(Symbol.isTag());
12690b57cec5SDimitry Andric assert(TypeIndices.count(&Symbol));
12700b57cec5SDimitry Andric return TypeIndices[&Symbol];
12710b57cec5SDimitry Andric }
12720b57cec5SDimitry Andric
registerFunctionType(const MCSymbolWasm & Symbol)12730b57cec5SDimitry Andric void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
12740b57cec5SDimitry Andric assert(Symbol.isFunction());
12750b57cec5SDimitry Andric
1276e8d8bef9SDimitry Andric wasm::WasmSignature S;
12775ffd83dbSDimitry Andric
12785ffd83dbSDimitry Andric if (auto *Sig = Symbol.getSignature()) {
12790b57cec5SDimitry Andric S.Returns = Sig->Returns;
12800b57cec5SDimitry Andric S.Params = Sig->Params;
12810b57cec5SDimitry Andric }
12820b57cec5SDimitry Andric
12830b57cec5SDimitry Andric auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
12840b57cec5SDimitry Andric if (Pair.second)
12850b57cec5SDimitry Andric Signatures.push_back(S);
12860b57cec5SDimitry Andric TypeIndices[&Symbol] = Pair.first->second;
12870b57cec5SDimitry Andric
12880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
12890b57cec5SDimitry Andric << " new:" << Pair.second << "\n");
12900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric
registerTagType(const MCSymbolWasm & Symbol)1293fe6060f1SDimitry Andric void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) {
1294fe6060f1SDimitry Andric assert(Symbol.isTag());
12950b57cec5SDimitry Andric
12960b57cec5SDimitry Andric // TODO Currently we don't generate imported exceptions, but if we do, we
12970b57cec5SDimitry Andric // should have a way of infering types of imported exceptions.
1298e8d8bef9SDimitry Andric wasm::WasmSignature S;
12990b57cec5SDimitry Andric if (auto *Sig = Symbol.getSignature()) {
13000b57cec5SDimitry Andric S.Returns = Sig->Returns;
13010b57cec5SDimitry Andric S.Params = Sig->Params;
13020b57cec5SDimitry Andric }
13030b57cec5SDimitry Andric
13040b57cec5SDimitry Andric auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
13050b57cec5SDimitry Andric if (Pair.second)
13060b57cec5SDimitry Andric Signatures.push_back(S);
13070b57cec5SDimitry Andric TypeIndices[&Symbol] = Pair.first->second;
13080b57cec5SDimitry Andric
1309fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.second
13100b57cec5SDimitry Andric << "\n");
13110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
13120b57cec5SDimitry Andric }
13130b57cec5SDimitry Andric
isInSymtab(const MCSymbolWasm & Sym)13140b57cec5SDimitry Andric static bool isInSymtab(const MCSymbolWasm &Sym) {
13155ffd83dbSDimitry Andric if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
13160b57cec5SDimitry Andric return true;
13170b57cec5SDimitry Andric
13180b57cec5SDimitry Andric if (Sym.isComdat() && !Sym.isDefined())
13190b57cec5SDimitry Andric return false;
13200b57cec5SDimitry Andric
13215ffd83dbSDimitry Andric if (Sym.isTemporary())
13220b57cec5SDimitry Andric return false;
13230b57cec5SDimitry Andric
13240b57cec5SDimitry Andric if (Sym.isSection())
13250b57cec5SDimitry Andric return false;
13260b57cec5SDimitry Andric
1327fe6060f1SDimitry Andric if (Sym.omitFromLinkingSection())
1328fe6060f1SDimitry Andric return false;
1329fe6060f1SDimitry Andric
13300b57cec5SDimitry Andric return true;
13310b57cec5SDimitry Andric }
13320b57cec5SDimitry Andric
prepareImports(SmallVectorImpl<wasm::WasmImport> & Imports,MCAssembler & Asm,const MCAsmLayout & Layout)1333e8d8bef9SDimitry Andric void WasmObjectWriter::prepareImports(
1334e8d8bef9SDimitry Andric SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
13350b57cec5SDimitry Andric const MCAsmLayout &Layout) {
13360b57cec5SDimitry Andric // For now, always emit the memory import, since loads and stores are not
13370b57cec5SDimitry Andric // valid without it. In the future, we could perhaps be more clever and omit
13380b57cec5SDimitry Andric // it if there are no loads or stores.
13390b57cec5SDimitry Andric wasm::WasmImport MemImport;
13400b57cec5SDimitry Andric MemImport.Module = "env";
13410b57cec5SDimitry Andric MemImport.Field = "__linear_memory";
13420b57cec5SDimitry Andric MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
13435ffd83dbSDimitry Andric MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
13445ffd83dbSDimitry Andric : wasm::WASM_LIMITS_FLAG_NONE;
13450b57cec5SDimitry Andric Imports.push_back(MemImport);
13460b57cec5SDimitry Andric
13470b57cec5SDimitry Andric // Populate SignatureIndices, and Imports and WasmIndices for undefined
13480b57cec5SDimitry Andric // symbols. This must be done before populating WasmIndices for defined
13490b57cec5SDimitry Andric // symbols.
13500b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
13510b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
13520b57cec5SDimitry Andric
13530b57cec5SDimitry Andric // Register types for all functions, including those with private linkage
13540b57cec5SDimitry Andric // (because wasm always needs a type signature).
13555ffd83dbSDimitry Andric if (WS.isFunction()) {
1356e8d8bef9SDimitry Andric const auto *BS = Layout.getBaseSymbol(S);
1357e8d8bef9SDimitry Andric if (!BS)
1358e8d8bef9SDimitry Andric report_fatal_error(Twine(S.getName()) +
1359e8d8bef9SDimitry Andric ": absolute addressing not supported!");
1360e8d8bef9SDimitry Andric registerFunctionType(*cast<MCSymbolWasm>(BS));
13615ffd83dbSDimitry Andric }
13620b57cec5SDimitry Andric
1363fe6060f1SDimitry Andric if (WS.isTag())
1364fe6060f1SDimitry Andric registerTagType(WS);
13650b57cec5SDimitry Andric
13660b57cec5SDimitry Andric if (WS.isTemporary())
13670b57cec5SDimitry Andric continue;
13680b57cec5SDimitry Andric
13690b57cec5SDimitry Andric // If the symbol is not defined in this translation unit, import it.
13700b57cec5SDimitry Andric if (!WS.isDefined() && !WS.isComdat()) {
13710b57cec5SDimitry Andric if (WS.isFunction()) {
13720b57cec5SDimitry Andric wasm::WasmImport Import;
13730b57cec5SDimitry Andric Import.Module = WS.getImportModule();
13740b57cec5SDimitry Andric Import.Field = WS.getImportName();
13750b57cec5SDimitry Andric Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
13760b57cec5SDimitry Andric Import.SigIndex = getFunctionType(WS);
13770b57cec5SDimitry Andric Imports.push_back(Import);
13780b57cec5SDimitry Andric assert(WasmIndices.count(&WS) == 0);
13790b57cec5SDimitry Andric WasmIndices[&WS] = NumFunctionImports++;
13800b57cec5SDimitry Andric } else if (WS.isGlobal()) {
13810b57cec5SDimitry Andric if (WS.isWeak())
13820b57cec5SDimitry Andric report_fatal_error("undefined global symbol cannot be weak");
13830b57cec5SDimitry Andric
13840b57cec5SDimitry Andric wasm::WasmImport Import;
13850b57cec5SDimitry Andric Import.Field = WS.getImportName();
13860b57cec5SDimitry Andric Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
13870b57cec5SDimitry Andric Import.Module = WS.getImportModule();
13880b57cec5SDimitry Andric Import.Global = WS.getGlobalType();
13890b57cec5SDimitry Andric Imports.push_back(Import);
13900b57cec5SDimitry Andric assert(WasmIndices.count(&WS) == 0);
13910b57cec5SDimitry Andric WasmIndices[&WS] = NumGlobalImports++;
1392fe6060f1SDimitry Andric } else if (WS.isTag()) {
13930b57cec5SDimitry Andric if (WS.isWeak())
1394fe6060f1SDimitry Andric report_fatal_error("undefined tag symbol cannot be weak");
13950b57cec5SDimitry Andric
13960b57cec5SDimitry Andric wasm::WasmImport Import;
13970b57cec5SDimitry Andric Import.Module = WS.getImportModule();
13980b57cec5SDimitry Andric Import.Field = WS.getImportName();
1399fe6060f1SDimitry Andric Import.Kind = wasm::WASM_EXTERNAL_TAG;
1400349cc55cSDimitry Andric Import.SigIndex = getTagType(WS);
14010b57cec5SDimitry Andric Imports.push_back(Import);
14020b57cec5SDimitry Andric assert(WasmIndices.count(&WS) == 0);
1403fe6060f1SDimitry Andric WasmIndices[&WS] = NumTagImports++;
1404e8d8bef9SDimitry Andric } else if (WS.isTable()) {
1405e8d8bef9SDimitry Andric if (WS.isWeak())
1406e8d8bef9SDimitry Andric report_fatal_error("undefined table symbol cannot be weak");
1407e8d8bef9SDimitry Andric
1408e8d8bef9SDimitry Andric wasm::WasmImport Import;
1409e8d8bef9SDimitry Andric Import.Module = WS.getImportModule();
1410e8d8bef9SDimitry Andric Import.Field = WS.getImportName();
1411e8d8bef9SDimitry Andric Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1412fe6060f1SDimitry Andric Import.Table = WS.getTableType();
1413e8d8bef9SDimitry Andric Imports.push_back(Import);
1414e8d8bef9SDimitry Andric assert(WasmIndices.count(&WS) == 0);
1415e8d8bef9SDimitry Andric WasmIndices[&WS] = NumTableImports++;
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric }
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric
14200b57cec5SDimitry Andric // Add imports for GOT globals
14210b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
14220b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
14230b57cec5SDimitry Andric if (WS.isUsedInGOT()) {
14240b57cec5SDimitry Andric wasm::WasmImport Import;
14250b57cec5SDimitry Andric if (WS.isFunction())
14260b57cec5SDimitry Andric Import.Module = "GOT.func";
14270b57cec5SDimitry Andric else
14280b57cec5SDimitry Andric Import.Module = "GOT.mem";
14290b57cec5SDimitry Andric Import.Field = WS.getName();
14300b57cec5SDimitry Andric Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
14310b57cec5SDimitry Andric Import.Global = {wasm::WASM_TYPE_I32, true};
14320b57cec5SDimitry Andric Imports.push_back(Import);
14330b57cec5SDimitry Andric assert(GOTIndices.count(&WS) == 0);
14340b57cec5SDimitry Andric GOTIndices[&WS] = NumGlobalImports++;
14350b57cec5SDimitry Andric }
14360b57cec5SDimitry Andric }
1437e8d8bef9SDimitry Andric }
1438e8d8bef9SDimitry Andric
writeObject(MCAssembler & Asm,const MCAsmLayout & Layout)1439e8d8bef9SDimitry Andric uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1440e8d8bef9SDimitry Andric const MCAsmLayout &Layout) {
14415f757f3fSDimitry Andric support::endian::Writer MainWriter(*OS, llvm::endianness::little);
1442e8d8bef9SDimitry Andric W = &MainWriter;
1443e8d8bef9SDimitry Andric if (IsSplitDwarf) {
1444e8d8bef9SDimitry Andric uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1445e8d8bef9SDimitry Andric assert(DwoOS);
14465f757f3fSDimitry Andric support::endian::Writer DwoWriter(*DwoOS, llvm::endianness::little);
1447e8d8bef9SDimitry Andric W = &DwoWriter;
1448e8d8bef9SDimitry Andric return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1449e8d8bef9SDimitry Andric } else {
1450e8d8bef9SDimitry Andric return writeOneObject(Asm, Layout, DwoMode::AllSections);
1451e8d8bef9SDimitry Andric }
1452e8d8bef9SDimitry Andric }
1453e8d8bef9SDimitry Andric
writeOneObject(MCAssembler & Asm,const MCAsmLayout & Layout,DwoMode Mode)1454e8d8bef9SDimitry Andric uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1455e8d8bef9SDimitry Andric const MCAsmLayout &Layout,
1456e8d8bef9SDimitry Andric DwoMode Mode) {
1457e8d8bef9SDimitry Andric uint64_t StartOffset = W->OS.tell();
1458e8d8bef9SDimitry Andric SectionCount = 0;
1459e8d8bef9SDimitry Andric CustomSections.clear();
1460e8d8bef9SDimitry Andric
1461e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1462e8d8bef9SDimitry Andric
1463e8d8bef9SDimitry Andric // Collect information from the available symbols.
1464e8d8bef9SDimitry Andric SmallVector<WasmFunction, 4> Functions;
1465e8d8bef9SDimitry Andric SmallVector<uint32_t, 4> TableElems;
1466e8d8bef9SDimitry Andric SmallVector<wasm::WasmImport, 4> Imports;
1467e8d8bef9SDimitry Andric SmallVector<wasm::WasmExport, 4> Exports;
1468349cc55cSDimitry Andric SmallVector<uint32_t, 2> TagTypes;
1469e8d8bef9SDimitry Andric SmallVector<wasm::WasmGlobal, 1> Globals;
1470e8d8bef9SDimitry Andric SmallVector<wasm::WasmTable, 1> Tables;
1471e8d8bef9SDimitry Andric SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1472e8d8bef9SDimitry Andric SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1473e8d8bef9SDimitry Andric std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1474e8d8bef9SDimitry Andric uint64_t DataSize = 0;
1475e8d8bef9SDimitry Andric if (Mode != DwoMode::DwoOnly) {
1476e8d8bef9SDimitry Andric prepareImports(Imports, Asm, Layout);
1477e8d8bef9SDimitry Andric }
14780b57cec5SDimitry Andric
14790b57cec5SDimitry Andric // Populate DataSegments and CustomSections, which must be done before
14800b57cec5SDimitry Andric // populating DataLocations.
14810b57cec5SDimitry Andric for (MCSection &Sec : Asm) {
14820b57cec5SDimitry Andric auto &Section = static_cast<MCSectionWasm &>(Sec);
14835ffd83dbSDimitry Andric StringRef SectionName = Section.getName();
14840b57cec5SDimitry Andric
1485e8d8bef9SDimitry Andric if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1486e8d8bef9SDimitry Andric continue;
1487e8d8bef9SDimitry Andric if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1488e8d8bef9SDimitry Andric continue;
1489e8d8bef9SDimitry Andric
1490e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << " group "
1491e8d8bef9SDimitry Andric << Section.getGroup() << "\n";);
1492e8d8bef9SDimitry Andric
14930b57cec5SDimitry Andric // .init_array sections are handled specially elsewhere.
14945f757f3fSDimitry Andric if (SectionName.starts_with(".init_array"))
14950b57cec5SDimitry Andric continue;
14960b57cec5SDimitry Andric
14970b57cec5SDimitry Andric // Code is handled separately
14980b57cec5SDimitry Andric if (Section.getKind().isText())
14990b57cec5SDimitry Andric continue;
15000b57cec5SDimitry Andric
15010b57cec5SDimitry Andric if (Section.isWasmData()) {
15020b57cec5SDimitry Andric uint32_t SegmentIndex = DataSegments.size();
1503bdd1243dSDimitry Andric DataSize = alignTo(DataSize, Section.getAlign());
15040b57cec5SDimitry Andric DataSegments.emplace_back();
15050b57cec5SDimitry Andric WasmDataSegment &Segment = DataSegments.back();
15060b57cec5SDimitry Andric Segment.Name = SectionName;
1507e8d8bef9SDimitry Andric Segment.InitFlags = Section.getPassive()
1508e8d8bef9SDimitry Andric ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1509e8d8bef9SDimitry Andric : 0;
15100b57cec5SDimitry Andric Segment.Offset = DataSize;
15110b57cec5SDimitry Andric Segment.Section = &Section;
15120b57cec5SDimitry Andric addData(Segment.Data, Section);
1513bdd1243dSDimitry Andric Segment.Alignment = Log2(Section.getAlign());
1514fe6060f1SDimitry Andric Segment.LinkingFlags = Section.getSegmentFlags();
15150b57cec5SDimitry Andric DataSize += Segment.Data.size();
15160b57cec5SDimitry Andric Section.setSegmentIndex(SegmentIndex);
15170b57cec5SDimitry Andric
15180b57cec5SDimitry Andric if (const MCSymbolWasm *C = Section.getGroup()) {
15190b57cec5SDimitry Andric Comdats[C->getName()].emplace_back(
15200b57cec5SDimitry Andric WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
15210b57cec5SDimitry Andric }
15220b57cec5SDimitry Andric } else {
15230b57cec5SDimitry Andric // Create custom sections
15240b57cec5SDimitry Andric assert(Sec.getKind().isMetadata());
15250b57cec5SDimitry Andric
15260b57cec5SDimitry Andric StringRef Name = SectionName;
15270b57cec5SDimitry Andric
15280b57cec5SDimitry Andric // For user-defined custom sections, strip the prefix
1529647cbc5dSDimitry Andric Name.consume_front(".custom_section.");
15300b57cec5SDimitry Andric
15310b57cec5SDimitry Andric MCSymbol *Begin = Sec.getBeginSymbol();
15320b57cec5SDimitry Andric if (Begin) {
1533e8d8bef9SDimitry Andric assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
15340b57cec5SDimitry Andric WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
15350b57cec5SDimitry Andric }
15360b57cec5SDimitry Andric
15370b57cec5SDimitry Andric // Separate out the producers and target features sections
15380b57cec5SDimitry Andric if (Name == "producers") {
15398bcb0991SDimitry Andric ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
15400b57cec5SDimitry Andric continue;
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric if (Name == "target_features") {
15430b57cec5SDimitry Andric TargetFeaturesSection =
15448bcb0991SDimitry Andric std::make_unique<WasmCustomSection>(Name, &Section);
15450b57cec5SDimitry Andric continue;
15460b57cec5SDimitry Andric }
15470b57cec5SDimitry Andric
1548e8d8bef9SDimitry Andric // Custom sections can also belong to COMDAT groups. In this case the
1549e8d8bef9SDimitry Andric // decriptor's "index" field is the section index (in the final object
1550e8d8bef9SDimitry Andric // file), but that is not known until after layout, so it must be fixed up
1551e8d8bef9SDimitry Andric // later
1552e8d8bef9SDimitry Andric if (const MCSymbolWasm *C = Section.getGroup()) {
1553e8d8bef9SDimitry Andric Comdats[C->getName()].emplace_back(
1554e8d8bef9SDimitry Andric WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1555e8d8bef9SDimitry Andric static_cast<uint32_t>(CustomSections.size())});
1556e8d8bef9SDimitry Andric }
1557e8d8bef9SDimitry Andric
15580b57cec5SDimitry Andric CustomSections.emplace_back(Name, &Section);
15590b57cec5SDimitry Andric }
15600b57cec5SDimitry Andric }
15610b57cec5SDimitry Andric
1562e8d8bef9SDimitry Andric if (Mode != DwoMode::DwoOnly) {
15630b57cec5SDimitry Andric // Populate WasmIndices and DataLocations for defined symbols.
15640b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
15650b57cec5SDimitry Andric // Ignore unnamed temporary symbols, which aren't ever exported, imported,
15660b57cec5SDimitry Andric // or used in relocations.
15670b57cec5SDimitry Andric if (S.isTemporary() && S.getName().empty())
15680b57cec5SDimitry Andric continue;
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
157181ad6265SDimitry Andric LLVM_DEBUG(
157281ad6265SDimitry Andric dbgs() << "MCSymbol: "
157381ad6265SDimitry Andric << toString(WS.getType().value_or(wasm::WASM_SYMBOL_TYPE_DATA))
1574fe6060f1SDimitry Andric << " '" << S << "'"
15750b57cec5SDimitry Andric << " isDefined=" << S.isDefined() << " isExternal="
15760b57cec5SDimitry Andric << S.isExternal() << " isTemporary=" << S.isTemporary()
15770b57cec5SDimitry Andric << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
15780b57cec5SDimitry Andric << " isVariable=" << WS.isVariable() << "\n");
15790b57cec5SDimitry Andric
15800b57cec5SDimitry Andric if (WS.isVariable())
15810b57cec5SDimitry Andric continue;
15820b57cec5SDimitry Andric if (WS.isComdat() && !WS.isDefined())
15830b57cec5SDimitry Andric continue;
15840b57cec5SDimitry Andric
15850b57cec5SDimitry Andric if (WS.isFunction()) {
15860b57cec5SDimitry Andric unsigned Index;
15870b57cec5SDimitry Andric if (WS.isDefined()) {
15880b57cec5SDimitry Andric if (WS.getOffset() != 0)
15890b57cec5SDimitry Andric report_fatal_error(
15900b57cec5SDimitry Andric "function sections must contain one function each");
15910b57cec5SDimitry Andric
15920b57cec5SDimitry Andric // A definition. Write out the function body.
15930b57cec5SDimitry Andric Index = NumFunctionImports + Functions.size();
15940b57cec5SDimitry Andric WasmFunction Func;
15950b57cec5SDimitry Andric Func.SigIndex = getFunctionType(WS);
1596bdd1243dSDimitry Andric Func.Section = &WS.getSection();
1597e8d8bef9SDimitry Andric assert(WasmIndices.count(&WS) == 0);
15980b57cec5SDimitry Andric WasmIndices[&WS] = Index;
15990b57cec5SDimitry Andric Functions.push_back(Func);
16000b57cec5SDimitry Andric
16010b57cec5SDimitry Andric auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
16020b57cec5SDimitry Andric if (const MCSymbolWasm *C = Section.getGroup()) {
16030b57cec5SDimitry Andric Comdats[C->getName()].emplace_back(
16040b57cec5SDimitry Andric WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
16050b57cec5SDimitry Andric }
1606480093f4SDimitry Andric
1607480093f4SDimitry Andric if (WS.hasExportName()) {
1608480093f4SDimitry Andric wasm::WasmExport Export;
1609480093f4SDimitry Andric Export.Name = WS.getExportName();
1610480093f4SDimitry Andric Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1611480093f4SDimitry Andric Export.Index = Index;
1612480093f4SDimitry Andric Exports.push_back(Export);
1613480093f4SDimitry Andric }
16140b57cec5SDimitry Andric } else {
16150b57cec5SDimitry Andric // An import; the index was assigned above.
16160b57cec5SDimitry Andric Index = WasmIndices.find(&WS)->second;
16170b57cec5SDimitry Andric }
16180b57cec5SDimitry Andric
16190b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
16200b57cec5SDimitry Andric
16210b57cec5SDimitry Andric } else if (WS.isData()) {
16220b57cec5SDimitry Andric if (!isInSymtab(WS))
16230b57cec5SDimitry Andric continue;
16240b57cec5SDimitry Andric
16250b57cec5SDimitry Andric if (!WS.isDefined()) {
16260b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> segment index: -1"
16270b57cec5SDimitry Andric << "\n");
16280b57cec5SDimitry Andric continue;
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric
16310b57cec5SDimitry Andric if (!WS.getSize())
16320b57cec5SDimitry Andric report_fatal_error("data symbols must have a size set with .size: " +
16330b57cec5SDimitry Andric WS.getName());
16340b57cec5SDimitry Andric
16350b57cec5SDimitry Andric int64_t Size = 0;
16360b57cec5SDimitry Andric if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
16370b57cec5SDimitry Andric report_fatal_error(".size expression must be evaluatable");
16380b57cec5SDimitry Andric
16390b57cec5SDimitry Andric auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
16408bcb0991SDimitry Andric if (!DataSection.isWasmData())
16418bcb0991SDimitry Andric report_fatal_error("data symbols must live in a data section: " +
16428bcb0991SDimitry Andric WS.getName());
16430b57cec5SDimitry Andric
16440b57cec5SDimitry Andric // For each data symbol, export it in the symtab as a reference to the
16450b57cec5SDimitry Andric // corresponding Wasm data segment.
16460b57cec5SDimitry Andric wasm::WasmDataReference Ref = wasm::WasmDataReference{
16475ffd83dbSDimitry Andric DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
16485ffd83dbSDimitry Andric static_cast<uint64_t>(Size)};
1649e8d8bef9SDimitry Andric assert(DataLocations.count(&WS) == 0);
16500b57cec5SDimitry Andric DataLocations[&WS] = Ref;
16510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
16520b57cec5SDimitry Andric
16530b57cec5SDimitry Andric } else if (WS.isGlobal()) {
16540b57cec5SDimitry Andric // A "true" Wasm global (currently just __stack_pointer)
16555ffd83dbSDimitry Andric if (WS.isDefined()) {
16565ffd83dbSDimitry Andric wasm::WasmGlobal Global;
16575ffd83dbSDimitry Andric Global.Type = WS.getGlobalType();
16585ffd83dbSDimitry Andric Global.Index = NumGlobalImports + Globals.size();
165981ad6265SDimitry Andric Global.InitExpr.Extended = false;
16605ffd83dbSDimitry Andric switch (Global.Type.Type) {
16615ffd83dbSDimitry Andric case wasm::WASM_TYPE_I32:
166281ad6265SDimitry Andric Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;
16635ffd83dbSDimitry Andric break;
16645ffd83dbSDimitry Andric case wasm::WASM_TYPE_I64:
166581ad6265SDimitry Andric Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_I64_CONST;
16665ffd83dbSDimitry Andric break;
16675ffd83dbSDimitry Andric case wasm::WASM_TYPE_F32:
166881ad6265SDimitry Andric Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_F32_CONST;
16695ffd83dbSDimitry Andric break;
16705ffd83dbSDimitry Andric case wasm::WASM_TYPE_F64:
167181ad6265SDimitry Andric Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_F64_CONST;
16725ffd83dbSDimitry Andric break;
16735ffd83dbSDimitry Andric case wasm::WASM_TYPE_EXTERNREF:
167481ad6265SDimitry Andric Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_REF_NULL;
16755ffd83dbSDimitry Andric break;
16765ffd83dbSDimitry Andric default:
16775ffd83dbSDimitry Andric llvm_unreachable("unexpected type");
16785ffd83dbSDimitry Andric }
1679e8d8bef9SDimitry Andric assert(WasmIndices.count(&WS) == 0);
16805ffd83dbSDimitry Andric WasmIndices[&WS] = Global.Index;
16815ffd83dbSDimitry Andric Globals.push_back(Global);
16825ffd83dbSDimitry Andric } else {
16830b57cec5SDimitry Andric // An import; the index was assigned above
16840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> global index: "
16850b57cec5SDimitry Andric << WasmIndices.find(&WS)->second << "\n");
16865ffd83dbSDimitry Andric }
1687e8d8bef9SDimitry Andric } else if (WS.isTable()) {
1688e8d8bef9SDimitry Andric if (WS.isDefined()) {
1689e8d8bef9SDimitry Andric wasm::WasmTable Table;
1690e8d8bef9SDimitry Andric Table.Index = NumTableImports + Tables.size();
1691fe6060f1SDimitry Andric Table.Type = WS.getTableType();
1692e8d8bef9SDimitry Andric assert(WasmIndices.count(&WS) == 0);
1693e8d8bef9SDimitry Andric WasmIndices[&WS] = Table.Index;
1694e8d8bef9SDimitry Andric Tables.push_back(Table);
1695e8d8bef9SDimitry Andric }
1696e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << " -> table index: "
1697e8d8bef9SDimitry Andric << WasmIndices.find(&WS)->second << "\n");
1698fe6060f1SDimitry Andric } else if (WS.isTag()) {
1699349cc55cSDimitry Andric // C++ exception symbol (__cpp_exception) or longjmp symbol
1700349cc55cSDimitry Andric // (__c_longjmp)
17010b57cec5SDimitry Andric unsigned Index;
17020b57cec5SDimitry Andric if (WS.isDefined()) {
1703349cc55cSDimitry Andric Index = NumTagImports + TagTypes.size();
1704349cc55cSDimitry Andric uint32_t SigIndex = getTagType(WS);
1705e8d8bef9SDimitry Andric assert(WasmIndices.count(&WS) == 0);
17060b57cec5SDimitry Andric WasmIndices[&WS] = Index;
1707349cc55cSDimitry Andric TagTypes.push_back(SigIndex);
17080b57cec5SDimitry Andric } else {
17090b57cec5SDimitry Andric // An import; the index was assigned above.
17100b57cec5SDimitry Andric assert(WasmIndices.count(&WS) > 0);
17110b57cec5SDimitry Andric }
1712fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << " -> tag index: " << WasmIndices.find(&WS)->second
1713fe6060f1SDimitry Andric << "\n");
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric } else {
17160b57cec5SDimitry Andric assert(WS.isSection());
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric }
17190b57cec5SDimitry Andric
17200b57cec5SDimitry Andric // Populate WasmIndices and DataLocations for aliased symbols. We need to
17210b57cec5SDimitry Andric // process these in a separate pass because we need to have processed the
17220b57cec5SDimitry Andric // target of the alias before the alias itself and the symbols are not
17230b57cec5SDimitry Andric // necessarily ordered in this way.
17240b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
17250b57cec5SDimitry Andric if (!S.isVariable())
17260b57cec5SDimitry Andric continue;
17270b57cec5SDimitry Andric
17280b57cec5SDimitry Andric assert(S.isDefined());
17290b57cec5SDimitry Andric
1730e8d8bef9SDimitry Andric const auto *BS = Layout.getBaseSymbol(S);
1731e8d8bef9SDimitry Andric if (!BS)
1732e8d8bef9SDimitry Andric report_fatal_error(Twine(S.getName()) +
1733e8d8bef9SDimitry Andric ": absolute addressing not supported!");
1734e8d8bef9SDimitry Andric const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
17355ffd83dbSDimitry Andric
17360b57cec5SDimitry Andric // Find the target symbol of this weak alias and export that index
17370b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
1738e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
1739e8d8bef9SDimitry Andric << "'\n");
17400b57cec5SDimitry Andric
17415ffd83dbSDimitry Andric if (Base->isFunction()) {
17425ffd83dbSDimitry Andric assert(WasmIndices.count(Base) > 0);
17435ffd83dbSDimitry Andric uint32_t WasmIndex = WasmIndices.find(Base)->second;
17440b57cec5SDimitry Andric assert(WasmIndices.count(&WS) == 0);
17450b57cec5SDimitry Andric WasmIndices[&WS] = WasmIndex;
17460b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
17475ffd83dbSDimitry Andric } else if (Base->isData()) {
17485ffd83dbSDimitry Andric auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
17495ffd83dbSDimitry Andric uint64_t Offset = Layout.getSymbolOffset(S);
17505ffd83dbSDimitry Andric int64_t Size = 0;
17515ffd83dbSDimitry Andric // For data symbol alias we use the size of the base symbol as the
17525ffd83dbSDimitry Andric // size of the alias. When an offset from the base is involved this
17535ffd83dbSDimitry Andric // can result in a offset + size goes past the end of the data section
17545ffd83dbSDimitry Andric // which out object format doesn't support. So we must clamp it.
17555ffd83dbSDimitry Andric if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
17565ffd83dbSDimitry Andric report_fatal_error(".size expression must be evaluatable");
17575ffd83dbSDimitry Andric const WasmDataSegment &Segment =
17585ffd83dbSDimitry Andric DataSegments[DataSection.getSegmentIndex()];
17595ffd83dbSDimitry Andric Size =
17605ffd83dbSDimitry Andric std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
17615ffd83dbSDimitry Andric wasm::WasmDataReference Ref = wasm::WasmDataReference{
17625ffd83dbSDimitry Andric DataSection.getSegmentIndex(),
17635ffd83dbSDimitry Andric static_cast<uint32_t>(Layout.getSymbolOffset(S)),
17645ffd83dbSDimitry Andric static_cast<uint32_t>(Size)};
17650b57cec5SDimitry Andric DataLocations[&WS] = Ref;
17660b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
17670b57cec5SDimitry Andric } else {
1768fe6060f1SDimitry Andric report_fatal_error("don't yet support global/tag aliases");
17690b57cec5SDimitry Andric }
17700b57cec5SDimitry Andric }
1771e8d8bef9SDimitry Andric }
17720b57cec5SDimitry Andric
17730b57cec5SDimitry Andric // Finally, populate the symbol table itself, in its "natural" order.
17740b57cec5SDimitry Andric for (const MCSymbol &S : Asm.symbols()) {
17750b57cec5SDimitry Andric const auto &WS = static_cast<const MCSymbolWasm &>(S);
17760b57cec5SDimitry Andric if (!isInSymtab(WS)) {
17770b57cec5SDimitry Andric WS.setIndex(InvalidIndex);
17780b57cec5SDimitry Andric continue;
17790b57cec5SDimitry Andric }
17800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
17810b57cec5SDimitry Andric
17820b57cec5SDimitry Andric uint32_t Flags = 0;
17830b57cec5SDimitry Andric if (WS.isWeak())
17840b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
17850b57cec5SDimitry Andric if (WS.isHidden())
17860b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
17870b57cec5SDimitry Andric if (!WS.isExternal() && WS.isDefined())
17880b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
17890b57cec5SDimitry Andric if (WS.isUndefined())
17900b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_UNDEFINED;
17918bcb0991SDimitry Andric if (WS.isNoStrip()) {
17928bcb0991SDimitry Andric Flags |= wasm::WASM_SYMBOL_NO_STRIP;
17938bcb0991SDimitry Andric if (isEmscripten()) {
17940b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_EXPORTED;
17958bcb0991SDimitry Andric }
17968bcb0991SDimitry Andric }
1797480093f4SDimitry Andric if (WS.hasImportName())
17980b57cec5SDimitry Andric Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1799480093f4SDimitry Andric if (WS.hasExportName())
1800480093f4SDimitry Andric Flags |= wasm::WASM_SYMBOL_EXPORTED;
1801349cc55cSDimitry Andric if (WS.isTLS())
1802349cc55cSDimitry Andric Flags |= wasm::WASM_SYMBOL_TLS;
18030b57cec5SDimitry Andric
18040b57cec5SDimitry Andric wasm::WasmSymbolInfo Info;
18050b57cec5SDimitry Andric Info.Name = WS.getName();
180681ad6265SDimitry Andric Info.Kind = WS.getType().value_or(wasm::WASM_SYMBOL_TYPE_DATA);
18070b57cec5SDimitry Andric Info.Flags = Flags;
18080b57cec5SDimitry Andric if (!WS.isData()) {
18090b57cec5SDimitry Andric assert(WasmIndices.count(&WS) > 0);
18100b57cec5SDimitry Andric Info.ElementIndex = WasmIndices.find(&WS)->second;
18110b57cec5SDimitry Andric } else if (WS.isDefined()) {
18120b57cec5SDimitry Andric assert(DataLocations.count(&WS) > 0);
18130b57cec5SDimitry Andric Info.DataRef = DataLocations.find(&WS)->second;
18140b57cec5SDimitry Andric }
18150b57cec5SDimitry Andric WS.setIndex(SymbolInfos.size());
18160b57cec5SDimitry Andric SymbolInfos.emplace_back(Info);
18170b57cec5SDimitry Andric }
18180b57cec5SDimitry Andric
18190b57cec5SDimitry Andric {
18200b57cec5SDimitry Andric auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
18210b57cec5SDimitry Andric // Functions referenced by a relocation need to put in the table. This is
18220b57cec5SDimitry Andric // purely to make the object file's provisional values readable, and is
18230b57cec5SDimitry Andric // ignored by the linker, which re-calculates the relocations itself.
18240b57cec5SDimitry Andric if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1825e8d8bef9SDimitry Andric Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
18265ffd83dbSDimitry Andric Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1827e8d8bef9SDimitry Andric Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1828fe6060f1SDimitry Andric Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB &&
1829fe6060f1SDimitry Andric Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
18300b57cec5SDimitry Andric return;
18310b57cec5SDimitry Andric assert(Rel.Symbol->isFunction());
18325ffd83dbSDimitry Andric const MCSymbolWasm *Base =
18335ffd83dbSDimitry Andric cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
18345ffd83dbSDimitry Andric uint32_t FunctionIndex = WasmIndices.find(Base)->second;
18350b57cec5SDimitry Andric uint32_t TableIndex = TableElems.size() + InitialTableOffset;
18365ffd83dbSDimitry Andric if (TableIndices.try_emplace(Base, TableIndex).second) {
18375ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << " -> adding " << Base->getName()
18380b57cec5SDimitry Andric << " to table: " << TableIndex << "\n");
18390b57cec5SDimitry Andric TableElems.push_back(FunctionIndex);
18405ffd83dbSDimitry Andric registerFunctionType(*Base);
18410b57cec5SDimitry Andric }
18420b57cec5SDimitry Andric };
18430b57cec5SDimitry Andric
18440b57cec5SDimitry Andric for (const WasmRelocationEntry &RelEntry : CodeRelocations)
18450b57cec5SDimitry Andric HandleReloc(RelEntry);
18460b57cec5SDimitry Andric for (const WasmRelocationEntry &RelEntry : DataRelocations)
18470b57cec5SDimitry Andric HandleReloc(RelEntry);
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric
18500b57cec5SDimitry Andric // Translate .init_array section contents into start functions.
18510b57cec5SDimitry Andric for (const MCSection &S : Asm) {
18520b57cec5SDimitry Andric const auto &WS = static_cast<const MCSectionWasm &>(S);
18535f757f3fSDimitry Andric if (WS.getName().starts_with(".fini_array"))
18540b57cec5SDimitry Andric report_fatal_error(".fini_array sections are unsupported");
18555f757f3fSDimitry Andric if (!WS.getName().starts_with(".init_array"))
18560b57cec5SDimitry Andric continue;
18570b57cec5SDimitry Andric if (WS.getFragmentList().empty())
18580b57cec5SDimitry Andric continue;
18590b57cec5SDimitry Andric
18600b57cec5SDimitry Andric // init_array is expected to contain a single non-empty data fragment
18610b57cec5SDimitry Andric if (WS.getFragmentList().size() != 3)
18620b57cec5SDimitry Andric report_fatal_error("only one .init_array section fragment supported");
18630b57cec5SDimitry Andric
18640b57cec5SDimitry Andric auto IT = WS.begin();
18650b57cec5SDimitry Andric const MCFragment &EmptyFrag = *IT;
18660b57cec5SDimitry Andric if (EmptyFrag.getKind() != MCFragment::FT_Data)
18670b57cec5SDimitry Andric report_fatal_error(".init_array section should be aligned");
18680b57cec5SDimitry Andric
18690b57cec5SDimitry Andric IT = std::next(IT);
18700b57cec5SDimitry Andric const MCFragment &AlignFrag = *IT;
18710b57cec5SDimitry Andric if (AlignFrag.getKind() != MCFragment::FT_Align)
18720b57cec5SDimitry Andric report_fatal_error(".init_array section should be aligned");
187381ad6265SDimitry Andric if (cast<MCAlignFragment>(AlignFrag).getAlignment() !=
187481ad6265SDimitry Andric Align(is64Bit() ? 8 : 4))
18750b57cec5SDimitry Andric report_fatal_error(".init_array section should be aligned for pointers");
18760b57cec5SDimitry Andric
18770b57cec5SDimitry Andric const MCFragment &Frag = *std::next(IT);
18780b57cec5SDimitry Andric if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
18790b57cec5SDimitry Andric report_fatal_error("only data supported in .init_array section");
18800b57cec5SDimitry Andric
18810b57cec5SDimitry Andric uint16_t Priority = UINT16_MAX;
18820b57cec5SDimitry Andric unsigned PrefixLength = strlen(".init_array");
18835ffd83dbSDimitry Andric if (WS.getName().size() > PrefixLength) {
18845ffd83dbSDimitry Andric if (WS.getName()[PrefixLength] != '.')
18850b57cec5SDimitry Andric report_fatal_error(
18860b57cec5SDimitry Andric ".init_array section priority should start with '.'");
18875ffd83dbSDimitry Andric if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
18880b57cec5SDimitry Andric report_fatal_error("invalid .init_array section priority");
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric const auto &DataFrag = cast<MCDataFragment>(Frag);
18910b57cec5SDimitry Andric const SmallVectorImpl<char> &Contents = DataFrag.getContents();
18920b57cec5SDimitry Andric for (const uint8_t *
18930b57cec5SDimitry Andric P = (const uint8_t *)Contents.data(),
18940b57cec5SDimitry Andric *End = (const uint8_t *)Contents.data() + Contents.size();
18950b57cec5SDimitry Andric P != End; ++P) {
18960b57cec5SDimitry Andric if (*P != 0)
18970b57cec5SDimitry Andric report_fatal_error("non-symbolic data in .init_array section");
18980b57cec5SDimitry Andric }
18990b57cec5SDimitry Andric for (const MCFixup &Fixup : DataFrag.getFixups()) {
19000b57cec5SDimitry Andric assert(Fixup.getKind() ==
19010b57cec5SDimitry Andric MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
19020b57cec5SDimitry Andric const MCExpr *Expr = Fixup.getValue();
19030b57cec5SDimitry Andric auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
19040b57cec5SDimitry Andric if (!SymRef)
19050b57cec5SDimitry Andric report_fatal_error("fixups in .init_array should be symbol references");
19060b57cec5SDimitry Andric const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
19070b57cec5SDimitry Andric if (TargetSym.getIndex() == InvalidIndex)
19085ffd83dbSDimitry Andric report_fatal_error("symbols in .init_array should exist in symtab");
19090b57cec5SDimitry Andric if (!TargetSym.isFunction())
19100b57cec5SDimitry Andric report_fatal_error("symbols in .init_array should be for functions");
19110b57cec5SDimitry Andric InitFuncs.push_back(
19120b57cec5SDimitry Andric std::make_pair(Priority, TargetSym.getIndex()));
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric }
19150b57cec5SDimitry Andric
19160b57cec5SDimitry Andric // Write out the Wasm header.
19170b57cec5SDimitry Andric writeHeader(Asm);
19180b57cec5SDimitry Andric
1919e8d8bef9SDimitry Andric uint32_t CodeSectionIndex, DataSectionIndex;
1920e8d8bef9SDimitry Andric if (Mode != DwoMode::DwoOnly) {
19210b57cec5SDimitry Andric writeTypeSection(Signatures);
19220b57cec5SDimitry Andric writeImportSection(Imports, DataSize, TableElems.size());
19230b57cec5SDimitry Andric writeFunctionSection(Functions);
1924e8d8bef9SDimitry Andric writeTableSection(Tables);
19250b57cec5SDimitry Andric // Skip the "memory" section; we import the memory instead.
1926349cc55cSDimitry Andric writeTagSection(TagTypes);
19275ffd83dbSDimitry Andric writeGlobalSection(Globals);
19280b57cec5SDimitry Andric writeExportSection(Exports);
1929fe6060f1SDimitry Andric const MCSymbol *IndirectFunctionTable =
1930fe6060f1SDimitry Andric Asm.getContext().lookupSymbol("__indirect_function_table");
1931fe6060f1SDimitry Andric writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1932fe6060f1SDimitry Andric TableElems);
19330b57cec5SDimitry Andric writeDataCountSection();
1934e8d8bef9SDimitry Andric
1935e8d8bef9SDimitry Andric CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1936e8d8bef9SDimitry Andric DataSectionIndex = writeDataSection(Layout);
1937e8d8bef9SDimitry Andric }
1938e8d8bef9SDimitry Andric
1939e8d8bef9SDimitry Andric // The Sections in the COMDAT list have placeholder indices (their index among
1940e8d8bef9SDimitry Andric // custom sections, rather than among all sections). Fix them up here.
1941e8d8bef9SDimitry Andric for (auto &Group : Comdats) {
1942e8d8bef9SDimitry Andric for (auto &Entry : Group.second) {
1943e8d8bef9SDimitry Andric if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
1944e8d8bef9SDimitry Andric Entry.Index += SectionCount;
1945e8d8bef9SDimitry Andric }
1946e8d8bef9SDimitry Andric }
1947e8d8bef9SDimitry Andric }
19480b57cec5SDimitry Andric for (auto &CustomSection : CustomSections)
19490b57cec5SDimitry Andric writeCustomSection(CustomSection, Asm, Layout);
1950e8d8bef9SDimitry Andric
1951e8d8bef9SDimitry Andric if (Mode != DwoMode::DwoOnly) {
19520b57cec5SDimitry Andric writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1953e8d8bef9SDimitry Andric
19540b57cec5SDimitry Andric writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
19550b57cec5SDimitry Andric writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1956e8d8bef9SDimitry Andric }
19570b57cec5SDimitry Andric writeCustomRelocSections();
19580b57cec5SDimitry Andric if (ProducersSection)
19590b57cec5SDimitry Andric writeCustomSection(*ProducersSection, Asm, Layout);
19600b57cec5SDimitry Andric if (TargetFeaturesSection)
19610b57cec5SDimitry Andric writeCustomSection(*TargetFeaturesSection, Asm, Layout);
19620b57cec5SDimitry Andric
19630b57cec5SDimitry Andric // TODO: Translate the .comment section to the output.
1964e8d8bef9SDimitry Andric return W->OS.tell() - StartOffset;
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric
19670b57cec5SDimitry Andric std::unique_ptr<MCObjectWriter>
createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS)19680b57cec5SDimitry Andric llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
19690b57cec5SDimitry Andric raw_pwrite_stream &OS) {
19708bcb0991SDimitry Andric return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
19710b57cec5SDimitry Andric }
1972e8d8bef9SDimitry Andric
1973e8d8bef9SDimitry Andric std::unique_ptr<MCObjectWriter>
createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS,raw_pwrite_stream & DwoOS)1974e8d8bef9SDimitry Andric llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1975e8d8bef9SDimitry Andric raw_pwrite_stream &OS,
1976e8d8bef9SDimitry Andric raw_pwrite_stream &DwoOS) {
1977e8d8bef9SDimitry Andric return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1978e8d8bef9SDimitry Andric }
1979