LCOV - code coverage report
Current view: top level - lib/MC - WasmObjectWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 0 594 0.0 %
Date: 2017-09-14 15:23:50 Functions: 0 37 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements Wasm object file writer information.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/ADT/STLExtras.h"
      15             : #include "llvm/ADT/SmallPtrSet.h"
      16             : #include "llvm/BinaryFormat/Wasm.h"
      17             : #include "llvm/MC/MCAsmBackend.h"
      18             : #include "llvm/MC/MCAsmInfo.h"
      19             : #include "llvm/MC/MCAsmLayout.h"
      20             : #include "llvm/MC/MCAssembler.h"
      21             : #include "llvm/MC/MCContext.h"
      22             : #include "llvm/MC/MCExpr.h"
      23             : #include "llvm/MC/MCFixupKindInfo.h"
      24             : #include "llvm/MC/MCObjectFileInfo.h"
      25             : #include "llvm/MC/MCObjectWriter.h"
      26             : #include "llvm/MC/MCSectionWasm.h"
      27             : #include "llvm/MC/MCSymbolWasm.h"
      28             : #include "llvm/MC/MCValue.h"
      29             : #include "llvm/MC/MCWasmObjectWriter.h"
      30             : #include "llvm/Support/Casting.h"
      31             : #include "llvm/Support/Debug.h"
      32             : #include "llvm/Support/ErrorHandling.h"
      33             : #include "llvm/Support/LEB128.h"
      34             : #include "llvm/Support/StringSaver.h"
      35             : #include <vector>
      36             : 
      37             : using namespace llvm;
      38             : 
      39             : #define DEBUG_TYPE "mc"
      40             : 
      41             : namespace {
      42             : 
      43             : // For patching purposes, we need to remember where each section starts, both
      44             : // for patching up the section size field, and for patching up references to
      45             : // locations within the section.
      46             : struct SectionBookkeeping {
      47             :   // Where the size of the section is written.
      48             :   uint64_t SizeOffset;
      49             :   // Where the contents of the section starts (after the header).
      50             :   uint64_t ContentsOffset;
      51             : };
      52             : 
      53             : // The signature of a wasm function, in a struct capable of being used as a
      54             : // DenseMap key.
      55           0 : struct WasmFunctionType {
      56             :   // Support empty and tombstone instances, needed by DenseMap.
      57             :   enum { Plain, Empty, Tombstone } State;
      58             : 
      59             :   // The return types of the function.
      60             :   SmallVector<wasm::ValType, 1> Returns;
      61             : 
      62             :   // The parameter types of the function.
      63             :   SmallVector<wasm::ValType, 4> Params;
      64             : 
      65           0 :   WasmFunctionType() : State(Plain) {}
      66             : 
      67           0 :   bool operator==(const WasmFunctionType &Other) const {
      68           0 :     return State == Other.State && Returns == Other.Returns &&
      69           0 :            Params == Other.Params;
      70             :   }
      71             : };
      72             : 
      73             : // Traits for using WasmFunctionType in a DenseMap.
      74             : struct WasmFunctionTypeDenseMapInfo {
      75             :   static WasmFunctionType getEmptyKey() {
      76           0 :     WasmFunctionType FuncTy;
      77           0 :     FuncTy.State = WasmFunctionType::Empty;
      78             :     return FuncTy;
      79             :   }
      80             :   static WasmFunctionType getTombstoneKey() {
      81           0 :     WasmFunctionType FuncTy;
      82           0 :     FuncTy.State = WasmFunctionType::Tombstone;
      83             :     return FuncTy;
      84             :   }
      85             :   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
      86           0 :     uintptr_t Value = FuncTy.State;
      87           0 :     for (wasm::ValType Ret : FuncTy.Returns)
      88           0 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
      89           0 :     for (wasm::ValType Param : FuncTy.Params)
      90           0 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
      91           0 :     return Value;
      92             :   }
      93             :   static bool isEqual(const WasmFunctionType &LHS,
      94             :                       const WasmFunctionType &RHS) {
      95           0 :     return LHS == RHS;
      96             :   }
      97             : };
      98             : 
      99             : // A wasm import to be written into the import section.
     100           0 : struct WasmImport {
     101             :   StringRef ModuleName;
     102             :   StringRef FieldName;
     103             :   unsigned Kind;
     104             :   int32_t Type;
     105             : };
     106             : 
     107             : // A wasm function to be written into the function section.
     108             : struct WasmFunction {
     109             :   int32_t Type;
     110             :   const MCSymbolWasm *Sym;
     111             : };
     112             : 
     113             : // A wasm export to be written into the export section.
     114           0 : struct WasmExport {
     115             :   StringRef FieldName;
     116             :   unsigned Kind;
     117             :   uint32_t Index;
     118             : };
     119             : 
     120             : // A wasm global to be written into the global section.
     121             : struct WasmGlobal {
     122             :   wasm::ValType Type;
     123             :   bool IsMutable;
     124             :   bool HasImport;
     125             :   uint64_t InitialValue;
     126             :   uint32_t ImportIndex;
     127             : };
     128             : 
     129             : // Information about a single relocation.
     130             : struct WasmRelocationEntry {
     131             :   uint64_t Offset;                  // Where is the relocation.
     132             :   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
     133             :   int64_t Addend;                   // A value to add to the symbol.
     134             :   unsigned Type;                    // The type of the relocation.
     135             :   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
     136             : 
     137             :   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
     138             :                       int64_t Addend, unsigned Type,
     139             :                       const MCSectionWasm *FixupSection)
     140           0 :       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
     141           0 :         FixupSection(FixupSection) {}
     142             : 
     143             :   bool hasAddend() const {
     144           0 :     switch (Type) {
     145             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     146             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     147             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     148             :       return true;
     149             :     default:
     150             :       return false;
     151             :     }
     152             :   }
     153             : 
     154             :   void print(raw_ostream &Out) const {
     155             :     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
     156             :         << ", Type=" << Type << ", FixupSection=" << FixupSection;
     157             :   }
     158             : 
     159             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     160             :   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
     161             : #endif
     162             : };
     163             : 
     164             : #if !defined(NDEBUG)
     165             : raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
     166             :   Rel.print(OS);
     167             :   return OS;
     168             : }
     169             : #endif
     170             : 
     171             : class WasmObjectWriter : public MCObjectWriter {
     172             :   /// Helper struct for containing some precomputed information on symbols.
     173             :   struct WasmSymbolData {
     174             :     const MCSymbolWasm *Symbol;
     175             :     StringRef Name;
     176             : 
     177             :     // Support lexicographic sorting.
     178             :     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
     179             :   };
     180             : 
     181             :   /// The target specific Wasm writer instance.
     182             :   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
     183             : 
     184             :   // Relocations for fixing up references in the code section.
     185             :   std::vector<WasmRelocationEntry> CodeRelocations;
     186             : 
     187             :   // Relocations for fixing up references in the data section.
     188             :   std::vector<WasmRelocationEntry> DataRelocations;
     189             : 
     190             :   // Index values to use for fixing up call_indirect type indices.
     191             :   // Maps function symbols to the index of the type of the function
     192             :   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
     193             :   // Maps function symbols to the table element index space. Used
     194             :   // for TABLE_INDEX relocation types (i.e. address taken functions).
     195             :   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
     196             :   // Maps function/global symbols to the function/global index space.
     197             :   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
     198             : 
     199             :   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
     200             :       FunctionTypeIndices;
     201             :   SmallVector<WasmFunctionType, 4> FunctionTypes;
     202             : 
     203             :   // TargetObjectWriter wrappers.
     204           0 :   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
     205             :   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
     206           0 :     return TargetObjectWriter->getRelocType(Target, Fixup);
     207             :   }
     208             : 
     209             :   void startSection(SectionBookkeeping &Section, unsigned SectionId,
     210             :                     const char *Name = nullptr);
     211             :   void endSection(SectionBookkeeping &Section);
     212             : 
     213             : public:
     214           0 :   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
     215           0 :       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
     216             : 
     217             : private:
     218             :   ~WasmObjectWriter() override;
     219             : 
     220           0 :   void reset() override {
     221           0 :     CodeRelocations.clear();
     222           0 :     DataRelocations.clear();
     223           0 :     TypeIndices.clear();
     224           0 :     SymbolIndices.clear();
     225           0 :     IndirectSymbolIndices.clear();
     226           0 :     FunctionTypeIndices.clear();
     227           0 :     FunctionTypes.clear();
     228           0 :     MCObjectWriter::reset();
     229           0 :   }
     230             : 
     231             :   void writeHeader(const MCAssembler &Asm);
     232             : 
     233             :   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
     234             :                         const MCFragment *Fragment, const MCFixup &Fixup,
     235             :                         MCValue Target, uint64_t &FixedValue) override;
     236             : 
     237             :   void executePostLayoutBinding(MCAssembler &Asm,
     238             :                                 const MCAsmLayout &Layout) override;
     239             : 
     240             :   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
     241             : 
     242           0 :   void writeString(const StringRef Str) {
     243           0 :     encodeULEB128(Str.size(), getStream());
     244           0 :     writeBytes(Str);
     245           0 :   }
     246             : 
     247             :   void writeValueType(wasm::ValType Ty) {
     248           0 :     encodeSLEB128(int32_t(Ty), getStream());
     249             :   }
     250             : 
     251             :   void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
     252             :   void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
     253             :   void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
     254             :   void writeTableSection(uint32_t NumElements);
     255             :   void writeMemorySection(const SmallVector<char, 0> &DataBytes);
     256             :   void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
     257             :   void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
     258             :   void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
     259             :   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
     260             :                         const SmallVector<WasmFunction, 4> &Functions);
     261             :   uint64_t
     262             :   writeDataSection(const SmallVector<char, 0> &DataBytes);
     263             :   void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
     264             :                         const SmallVector<WasmImport, 4> &Imports,
     265             :                         uint32_t NumFuncImports);
     266             :   void writeCodeRelocSection();
     267             :   void writeDataRelocSection(uint64_t DataSectionHeaderSize);
     268             :   void writeLinkingMetaDataSection(uint32_t DataSize, uint32_t DataAlignment,
     269             :                                    ArrayRef<StringRef> WeakSymbols,
     270             :                                    bool HasStackPointer,
     271             :                                    uint32_t StackPointerGlobal);
     272             : 
     273             :   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
     274             :                         uint64_t ContentsOffset);
     275             : 
     276             :   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
     277             :                         uint64_t HeaderSize);
     278             :   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
     279             :   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
     280             :   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
     281             : };
     282             : 
     283             : } // end anonymous namespace
     284             : 
     285           0 : WasmObjectWriter::~WasmObjectWriter() {}
     286             : 
     287             : // Return the padding size to write a 32-bit value into a 5-byte ULEB128.
     288             : static unsigned PaddingFor5ByteULEB128(uint32_t X) {
     289           0 :   return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
     290             : }
     291             : 
     292             : // Return the padding size to write a 32-bit value into a 5-byte SLEB128.
     293             : static unsigned PaddingFor5ByteSLEB128(int32_t X) {
     294           0 :   return 5 - getSLEB128Size(X);
     295             : }
     296             : 
     297             : // Write out a section header and a patchable section size field.
     298           0 : void WasmObjectWriter::startSection(SectionBookkeeping &Section,
     299             :                                     unsigned SectionId,
     300             :                                     const char *Name) {
     301             :   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
     302             :          "Only custom sections can have names");
     303             : 
     304             :   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
     305           0 :   encodeULEB128(SectionId, getStream());
     306             : 
     307           0 :   Section.SizeOffset = getStream().tell();
     308             : 
     309             :   // The section size. We don't know the size yet, so reserve enough space
     310             :   // for any 32-bit value; we'll patch it later.
     311           0 :   encodeULEB128(UINT32_MAX, getStream());
     312             : 
     313             :   // The position where the section starts, for measuring its size.
     314           0 :   Section.ContentsOffset = getStream().tell();
     315             : 
     316             :   // Custom sections in wasm also have a string identifier.
     317           0 :   if (SectionId == wasm::WASM_SEC_CUSTOM) {
     318             :     assert(Name);
     319           0 :     writeString(StringRef(Name));
     320             :   }
     321           0 : }
     322             : 
     323             : // Now that the section is complete and we know how big it is, patch up the
     324             : // section size field at the start of the section.
     325           0 : void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
     326           0 :   uint64_t Size = getStream().tell() - Section.ContentsOffset;
     327           0 :   if (uint32_t(Size) != Size)
     328           0 :     report_fatal_error("section size does not fit in a uint32_t");
     329             : 
     330             :   DEBUG(dbgs() << "endSection size=" << Size << "\n");
     331           0 :   unsigned Padding = PaddingFor5ByteULEB128(Size);
     332             : 
     333             :   // Write the final section size to the payload_len field, which follows
     334             :   // the section id byte.
     335             :   uint8_t Buffer[16];
     336           0 :   unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
     337             :   assert(SizeLen == 5);
     338           0 :   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
     339           0 : }
     340             : 
     341             : // Emit the Wasm header.
     342           0 : void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
     343           0 :   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
     344           0 :   writeLE32(wasm::WasmVersion);
     345           0 : }
     346             : 
     347           0 : void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
     348             :                                                 const MCAsmLayout &Layout) {
     349           0 : }
     350             : 
     351           0 : void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
     352             :                                         const MCAsmLayout &Layout,
     353             :                                         const MCFragment *Fragment,
     354             :                                         const MCFixup &Fixup, MCValue Target,
     355             :                                         uint64_t &FixedValue) {
     356           0 :   MCAsmBackend &Backend = Asm.getBackend();
     357           0 :   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
     358           0 :                  MCFixupKindInfo::FKF_IsPCRel;
     359           0 :   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
     360           0 :   uint64_t C = Target.getConstant();
     361           0 :   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
     362           0 :   MCContext &Ctx = Asm.getContext();
     363             : 
     364           0 :   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
     365             :     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
     366             :            "Should not have constructed this");
     367             : 
     368             :     // Let A, B and C being the components of Target and R be the location of
     369             :     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
     370             :     // If it is pcrel, we want to compute (A - B + C - R).
     371             : 
     372             :     // In general, Wasm has no relocations for -B. It can only represent (A + C)
     373             :     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
     374             :     // replace B to implement it: (A - R - K + C)
     375           0 :     if (IsPCRel) {
     376           0 :       Ctx.reportError(
     377             :           Fixup.getLoc(),
     378             :           "No relocation available to represent this relative expression");
     379           0 :       return;
     380             :     }
     381             : 
     382           0 :     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
     383             : 
     384           0 :     if (SymB.isUndefined()) {
     385           0 :       Ctx.reportError(Fixup.getLoc(),
     386           0 :                       Twine("symbol '") + SymB.getName() +
     387           0 :                           "' can not be undefined in a subtraction expression");
     388           0 :       return;
     389             :     }
     390             : 
     391             :     assert(!SymB.isAbsolute() && "Should have been folded");
     392           0 :     const MCSection &SecB = SymB.getSection();
     393           0 :     if (&SecB != &FixupSection) {
     394           0 :       Ctx.reportError(Fixup.getLoc(),
     395             :                       "Cannot represent a difference across sections");
     396           0 :       return;
     397             :     }
     398             : 
     399           0 :     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
     400           0 :     uint64_t K = SymBOffset - FixupOffset;
     401           0 :     IsPCRel = true;
     402           0 :     C -= K;
     403             :   }
     404             : 
     405             :   // We either rejected the fixup or folded B into C at this point.
     406           0 :   const MCSymbolRefExpr *RefA = Target.getSymA();
     407           0 :   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
     408             : 
     409           0 :   if (SymA && SymA->isVariable()) {
     410           0 :     const MCExpr *Expr = SymA->getVariableValue();
     411           0 :     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
     412           0 :     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
     413           0 :       llvm_unreachable("weakref used in reloc not yet implemented");
     414             :   }
     415             : 
     416             :   // Put any constant offset in an addend. Offsets can be negative, and
     417             :   // LLVM expects wrapping, in contrast to wasm's immediates which can't
     418             :   // be negative and don't wrap.
     419           0 :   FixedValue = 0;
     420             : 
     421           0 :   if (SymA)
     422           0 :     SymA->setUsedInReloc();
     423             : 
     424             :   assert(!IsPCRel);
     425             :   assert(SymA);
     426             : 
     427           0 :   unsigned Type = getRelocType(Target, Fixup);
     428             : 
     429           0 :   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
     430             :   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
     431             : 
     432           0 :   if (FixupSection.hasInstructions())
     433           0 :     CodeRelocations.push_back(Rec);
     434             :   else
     435           0 :     DataRelocations.push_back(Rec);
     436             : }
     437             : 
     438             : // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
     439             : // to allow patching.
     440             : static void
     441           0 : WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
     442             :   uint8_t Buffer[5];
     443           0 :   unsigned Padding = PaddingFor5ByteULEB128(X);
     444           0 :   unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
     445             :   assert(SizeLen == 5);
     446           0 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     447           0 : }
     448             : 
     449             : // Write X as an signed LEB value at offset Offset in Stream, padded
     450             : // to allow patching.
     451             : static void
     452           0 : WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
     453             :   uint8_t Buffer[5];
     454           0 :   unsigned Padding = PaddingFor5ByteSLEB128(X);
     455           0 :   unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
     456             :   assert(SizeLen == 5);
     457           0 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     458           0 : }
     459             : 
     460             : // Write X as a plain integer value at offset Offset in Stream.
     461             : static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
     462             :   uint8_t Buffer[4];
     463           0 :   support::endian::write32le(Buffer, X);
     464           0 :   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
     465             : }
     466             : 
     467             : // Compute a value to write into the code at the location covered
     468             : // by RelEntry. This value isn't used by the static linker, since
     469             : // we have addends; it just serves to make the code more readable
     470             : // and to make standalone wasm modules directly usable.
     471           0 : static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
     472           0 :   const MCSymbolWasm *Sym = RelEntry.Symbol;
     473             : 
     474             :   // For undefined symbols, use a hopefully invalid value.
     475           0 :   if (!Sym->isDefined(/*SetUsed=*/false))
     476             :     return UINT32_MAX;
     477             : 
     478           0 :   const auto &Section = cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
     479           0 :   uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
     480             : 
     481             :   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
     482           0 :   uint32_t Value = Address;
     483             : 
     484             :   return Value;
     485             : }
     486             : 
     487           0 : uint32_t WasmObjectWriter::getRelocationIndexValue(
     488             :     const WasmRelocationEntry &RelEntry) {
     489           0 :   switch (RelEntry.Type) {
     490           0 :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     491             :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
     492           0 :     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
     493           0 :       report_fatal_error("symbol not found table index space: " +
     494           0 :                          RelEntry.Symbol->getName());
     495           0 :     return IndirectSymbolIndices[RelEntry.Symbol];
     496           0 :   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     497             :   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
     498             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     499             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     500             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     501           0 :     if (!SymbolIndices.count(RelEntry.Symbol))
     502           0 :       report_fatal_error("symbol not found function/global index space: " +
     503           0 :                          RelEntry.Symbol->getName());
     504           0 :     return SymbolIndices[RelEntry.Symbol];
     505           0 :   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     506           0 :     if (!TypeIndices.count(RelEntry.Symbol))
     507           0 :       report_fatal_error("symbol not found in type index space: " +
     508           0 :                          RelEntry.Symbol->getName());
     509           0 :     return TypeIndices[RelEntry.Symbol];
     510           0 :   default:
     511           0 :     llvm_unreachable("invalid relocation type");
     512             :   }
     513             : }
     514             : 
     515             : // Apply the portions of the relocation records that we can handle ourselves
     516             : // directly.
     517           0 : void WasmObjectWriter::applyRelocations(
     518             :     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
     519           0 :   raw_pwrite_stream &Stream = getStream();
     520           0 :   for (const WasmRelocationEntry &RelEntry : Relocations) {
     521           0 :     uint64_t Offset = ContentsOffset +
     522           0 :                       RelEntry.FixupSection->getSectionOffset() +
     523           0 :                       RelEntry.Offset;
     524             : 
     525             :     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
     526           0 :     switch (RelEntry.Type) {
     527           0 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     528             :     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     529             :     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     530             :     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
     531           0 :       uint32_t Index = getRelocationIndexValue(RelEntry);
     532           0 :       WritePatchableSLEB(Stream, Index, Offset);
     533           0 :       break;
     534             :     }
     535           0 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
     536           0 :       uint32_t Index = getRelocationIndexValue(RelEntry);
     537             :       WriteI32(Stream, Index, Offset);
     538             :       break;
     539             :     }
     540           0 :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
     541           0 :       uint32_t Value = ProvisionalValue(RelEntry);
     542           0 :       WritePatchableSLEB(Stream, Value, Offset);
     543           0 :       break;
     544             :     }
     545           0 :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
     546           0 :       uint32_t Value = ProvisionalValue(RelEntry);
     547           0 :       WritePatchableLEB(Stream, Value, Offset);
     548           0 :       break;
     549             :     }
     550           0 :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
     551           0 :       uint32_t Value = ProvisionalValue(RelEntry);
     552             :       WriteI32(Stream, Value, Offset);
     553             :       break;
     554             :     }
     555           0 :     default:
     556           0 :       llvm_unreachable("invalid relocation type");
     557             :     }
     558             :   }
     559           0 : }
     560             : 
     561             : // Write out the portions of the relocation records that the linker will
     562             : // need to handle.
     563           0 : void WasmObjectWriter::writeRelocations(
     564             :     ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
     565           0 :   raw_pwrite_stream &Stream = getStream();
     566           0 :   for (const WasmRelocationEntry& RelEntry : Relocations) {
     567             : 
     568           0 :     uint64_t Offset = RelEntry.Offset +
     569           0 :                       RelEntry.FixupSection->getSectionOffset() + HeaderSize;
     570           0 :     uint32_t Index = getRelocationIndexValue(RelEntry);
     571             : 
     572           0 :     encodeULEB128(RelEntry.Type, Stream);
     573           0 :     encodeULEB128(Offset, Stream);
     574           0 :     encodeULEB128(Index, Stream);
     575           0 :     if (RelEntry.hasAddend())
     576           0 :       encodeSLEB128(RelEntry.Addend, Stream);
     577             :   }
     578           0 : }
     579             : 
     580           0 : void WasmObjectWriter::writeTypeSection(
     581             :     const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
     582           0 :   if (FunctionTypes.empty())
     583           0 :     return;
     584             : 
     585             :   SectionBookkeeping Section;
     586           0 :   startSection(Section, wasm::WASM_SEC_TYPE);
     587             : 
     588           0 :   encodeULEB128(FunctionTypes.size(), getStream());
     589             : 
     590           0 :   for (const WasmFunctionType &FuncTy : FunctionTypes) {
     591           0 :     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
     592           0 :     encodeULEB128(FuncTy.Params.size(), getStream());
     593           0 :     for (wasm::ValType Ty : FuncTy.Params)
     594           0 :       writeValueType(Ty);
     595           0 :     encodeULEB128(FuncTy.Returns.size(), getStream());
     596           0 :     for (wasm::ValType Ty : FuncTy.Returns)
     597           0 :       writeValueType(Ty);
     598             :   }
     599             : 
     600           0 :   endSection(Section);
     601             : }
     602             : 
     603             : 
     604           0 : void WasmObjectWriter::writeImportSection(
     605             :     const SmallVector<WasmImport, 4> &Imports) {
     606           0 :   if (Imports.empty())
     607           0 :     return;
     608             : 
     609             :   SectionBookkeeping Section;
     610           0 :   startSection(Section, wasm::WASM_SEC_IMPORT);
     611             : 
     612           0 :   encodeULEB128(Imports.size(), getStream());
     613           0 :   for (const WasmImport &Import : Imports) {
     614           0 :     writeString(Import.ModuleName);
     615           0 :     writeString(Import.FieldName);
     616             : 
     617           0 :     encodeULEB128(Import.Kind, getStream());
     618             : 
     619           0 :     switch (Import.Kind) {
     620           0 :     case wasm::WASM_EXTERNAL_FUNCTION:
     621           0 :       encodeULEB128(Import.Type, getStream());
     622           0 :       break;
     623           0 :     case wasm::WASM_EXTERNAL_GLOBAL:
     624           0 :       encodeSLEB128(int32_t(Import.Type), getStream());
     625           0 :       encodeULEB128(0, getStream()); // mutability
     626           0 :       break;
     627           0 :     default:
     628           0 :       llvm_unreachable("unsupported import kind");
     629             :     }
     630             :   }
     631             : 
     632           0 :   endSection(Section);
     633             : }
     634             : 
     635           0 : void WasmObjectWriter::writeFunctionSection(
     636             :     const SmallVector<WasmFunction, 4> &Functions) {
     637           0 :   if (Functions.empty())
     638           0 :     return;
     639             : 
     640             :   SectionBookkeeping Section;
     641           0 :   startSection(Section, wasm::WASM_SEC_FUNCTION);
     642             : 
     643           0 :   encodeULEB128(Functions.size(), getStream());
     644           0 :   for (const WasmFunction &Func : Functions)
     645           0 :     encodeULEB128(Func.Type, getStream());
     646             : 
     647           0 :   endSection(Section);
     648             : }
     649             : 
     650           0 : void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
     651             :   // For now, always emit the table section, since indirect calls are not
     652             :   // valid without it. In the future, we could perhaps be more clever and omit
     653             :   // it if there are no indirect calls.
     654             : 
     655             :   SectionBookkeeping Section;
     656           0 :   startSection(Section, wasm::WASM_SEC_TABLE);
     657             : 
     658           0 :   encodeULEB128(1, getStream());                       // The number of tables.
     659             :                                                        // Fixed to 1 for now.
     660           0 :   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
     661           0 :   encodeULEB128(0, getStream());                       // flags
     662           0 :   encodeULEB128(NumElements, getStream());             // initial
     663             : 
     664           0 :   endSection(Section);
     665           0 : }
     666             : 
     667           0 : void WasmObjectWriter::writeMemorySection(
     668             :     const SmallVector<char, 0> &DataBytes) {
     669             :   // For now, always emit the memory section, since loads and stores are not
     670             :   // valid without it. In the future, we could perhaps be more clever and omit
     671             :   // it if there are no loads or stores.
     672             :   SectionBookkeeping Section;
     673             :   uint32_t NumPages =
     674           0 :       (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
     675             : 
     676           0 :   startSection(Section, wasm::WASM_SEC_MEMORY);
     677           0 :   encodeULEB128(1, getStream()); // number of memory spaces
     678             : 
     679           0 :   encodeULEB128(0, getStream()); // flags
     680           0 :   encodeULEB128(NumPages, getStream()); // initial
     681             : 
     682           0 :   endSection(Section);
     683           0 : }
     684             : 
     685           0 : void WasmObjectWriter::writeGlobalSection(
     686             :     const SmallVector<WasmGlobal, 4> &Globals) {
     687           0 :   if (Globals.empty())
     688           0 :     return;
     689             : 
     690             :   SectionBookkeeping Section;
     691           0 :   startSection(Section, wasm::WASM_SEC_GLOBAL);
     692             : 
     693           0 :   encodeULEB128(Globals.size(), getStream());
     694           0 :   for (const WasmGlobal &Global : Globals) {
     695           0 :     writeValueType(Global.Type);
     696           0 :     write8(Global.IsMutable);
     697             : 
     698           0 :     if (Global.HasImport) {
     699             :       assert(Global.InitialValue == 0);
     700           0 :       write8(wasm::WASM_OPCODE_GET_GLOBAL);
     701           0 :       encodeULEB128(Global.ImportIndex, getStream());
     702             :     } else {
     703             :       assert(Global.ImportIndex == 0);
     704           0 :       write8(wasm::WASM_OPCODE_I32_CONST);
     705           0 :       encodeSLEB128(Global.InitialValue, getStream()); // offset
     706             :     }
     707           0 :     write8(wasm::WASM_OPCODE_END);
     708             :   }
     709             : 
     710           0 :   endSection(Section);
     711             : }
     712             : 
     713           0 : void WasmObjectWriter::writeExportSection(
     714             :     const SmallVector<WasmExport, 4> &Exports) {
     715           0 :   if (Exports.empty())
     716           0 :     return;
     717             : 
     718             :   SectionBookkeeping Section;
     719           0 :   startSection(Section, wasm::WASM_SEC_EXPORT);
     720             : 
     721           0 :   encodeULEB128(Exports.size(), getStream());
     722           0 :   for (const WasmExport &Export : Exports) {
     723           0 :     writeString(Export.FieldName);
     724           0 :     encodeSLEB128(Export.Kind, getStream());
     725           0 :     encodeULEB128(Export.Index, getStream());
     726             :   }
     727             : 
     728           0 :   endSection(Section);
     729             : }
     730             : 
     731           0 : void WasmObjectWriter::writeElemSection(
     732             :     const SmallVector<uint32_t, 4> &TableElems) {
     733           0 :   if (TableElems.empty())
     734           0 :     return;
     735             : 
     736             :   SectionBookkeeping Section;
     737           0 :   startSection(Section, wasm::WASM_SEC_ELEM);
     738             : 
     739           0 :   encodeULEB128(1, getStream()); // number of "segments"
     740           0 :   encodeULEB128(0, getStream()); // the table index
     741             : 
     742             :   // init expr for starting offset
     743           0 :   write8(wasm::WASM_OPCODE_I32_CONST);
     744           0 :   encodeSLEB128(0, getStream());
     745           0 :   write8(wasm::WASM_OPCODE_END);
     746             : 
     747           0 :   encodeULEB128(TableElems.size(), getStream());
     748           0 :   for (uint32_t Elem : TableElems)
     749           0 :     encodeULEB128(Elem, getStream());
     750             : 
     751           0 :   endSection(Section);
     752             : }
     753             : 
     754           0 : void WasmObjectWriter::writeCodeSection(
     755             :     const MCAssembler &Asm, const MCAsmLayout &Layout,
     756             :     const SmallVector<WasmFunction, 4> &Functions) {
     757           0 :   if (Functions.empty())
     758           0 :     return;
     759             : 
     760             :   SectionBookkeeping Section;
     761           0 :   startSection(Section, wasm::WASM_SEC_CODE);
     762             : 
     763           0 :   encodeULEB128(Functions.size(), getStream());
     764             : 
     765           0 :   for (const WasmFunction &Func : Functions) {
     766           0 :     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
     767             : 
     768           0 :     int64_t Size = 0;
     769           0 :     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
     770           0 :       report_fatal_error(".size expression must be evaluatable");
     771             : 
     772           0 :     encodeULEB128(Size, getStream());
     773             : 
     774           0 :     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
     775             : 
     776           0 :     Asm.writeSectionData(&FuncSection, Layout);
     777             :   }
     778             : 
     779             :   // Apply fixups.
     780           0 :   applyRelocations(CodeRelocations, Section.ContentsOffset);
     781             : 
     782           0 :   endSection(Section);
     783             : }
     784             : 
     785           0 : uint64_t WasmObjectWriter::writeDataSection(
     786             :     const SmallVector<char, 0> &DataBytes) {
     787           0 :   if (DataBytes.empty())
     788             :     return 0;
     789             : 
     790             :   SectionBookkeeping Section;
     791           0 :   startSection(Section, wasm::WASM_SEC_DATA);
     792             : 
     793           0 :   encodeULEB128(1, getStream()); // count
     794           0 :   encodeULEB128(0, getStream()); // memory index
     795           0 :   write8(wasm::WASM_OPCODE_I32_CONST);
     796           0 :   encodeSLEB128(0, getStream()); // offset
     797           0 :   write8(wasm::WASM_OPCODE_END);
     798           0 :   encodeULEB128(DataBytes.size(), getStream()); // size
     799           0 :   uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
     800           0 :   writeBytes(DataBytes); // data
     801             : 
     802             :   // Apply fixups.
     803           0 :   applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
     804             : 
     805           0 :   endSection(Section);
     806           0 :   return HeaderSize;
     807             : }
     808             : 
     809           0 : void WasmObjectWriter::writeNameSection(
     810             :     const SmallVector<WasmFunction, 4> &Functions,
     811             :     const SmallVector<WasmImport, 4> &Imports,
     812             :     unsigned NumFuncImports) {
     813           0 :   uint32_t TotalFunctions = NumFuncImports + Functions.size();
     814           0 :   if (TotalFunctions == 0)
     815           0 :     return;
     816             : 
     817             :   SectionBookkeeping Section;
     818           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
     819             :   SectionBookkeeping SubSection;
     820           0 :   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
     821             : 
     822           0 :   encodeULEB128(TotalFunctions, getStream());
     823           0 :   uint32_t Index = 0;
     824           0 :   for (const WasmImport &Import : Imports) {
     825           0 :     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
     826           0 :       encodeULEB128(Index, getStream());
     827           0 :       writeString(Import.FieldName);
     828           0 :       ++Index;
     829             :     }
     830             :   }
     831           0 :   for (const WasmFunction &Func : Functions) {
     832           0 :     encodeULEB128(Index, getStream());
     833           0 :     writeString(Func.Sym->getName());
     834           0 :     ++Index;
     835             :   }
     836             : 
     837           0 :   endSection(SubSection);
     838           0 :   endSection(Section);
     839             : }
     840             : 
     841           0 : void WasmObjectWriter::writeCodeRelocSection() {
     842             :   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
     843             :   // for descriptions of the reloc sections.
     844             : 
     845           0 :   if (CodeRelocations.empty())
     846           0 :     return;
     847             : 
     848             :   SectionBookkeeping Section;
     849           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
     850             : 
     851           0 :   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
     852           0 :   encodeULEB128(CodeRelocations.size(), getStream());
     853             : 
     854           0 :   writeRelocations(CodeRelocations, 0);
     855             : 
     856           0 :   endSection(Section);
     857             : }
     858             : 
     859           0 : void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
     860             :   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
     861             :   // for descriptions of the reloc sections.
     862             : 
     863           0 :   if (DataRelocations.empty())
     864           0 :     return;
     865             : 
     866             :   SectionBookkeeping Section;
     867           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
     868             : 
     869           0 :   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
     870           0 :   encodeULEB128(DataRelocations.size(), getStream());
     871             : 
     872           0 :   writeRelocations(DataRelocations, DataSectionHeaderSize);
     873             : 
     874           0 :   endSection(Section);
     875             : }
     876             : 
     877           0 : void WasmObjectWriter::writeLinkingMetaDataSection(
     878             :     uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
     879             :     bool HasStackPointer, uint32_t StackPointerGlobal) {
     880             :   SectionBookkeeping Section;
     881           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
     882             :   SectionBookkeeping SubSection;
     883             : 
     884           0 :   if (HasStackPointer) {
     885           0 :     startSection(SubSection, wasm::WASM_STACK_POINTER);
     886           0 :     encodeULEB128(StackPointerGlobal, getStream()); // id
     887           0 :     endSection(SubSection);
     888             :   }
     889             : 
     890           0 :   if (WeakSymbols.size() != 0) {
     891           0 :     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
     892           0 :     encodeULEB128(WeakSymbols.size(), getStream());
     893           0 :     for (const StringRef Export: WeakSymbols) {
     894           0 :       writeString(Export);
     895           0 :       encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
     896             :     }
     897           0 :     endSection(SubSection);
     898             :   }
     899             : 
     900           0 :   if (DataSize > 0) {
     901           0 :     startSection(SubSection, wasm::WASM_DATA_SIZE);
     902           0 :     encodeULEB128(DataSize, getStream());
     903           0 :     endSection(SubSection);
     904             : 
     905           0 :     startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
     906           0 :     encodeULEB128(DataAlignment, getStream());
     907           0 :     endSection(SubSection);
     908             :   }
     909             : 
     910           0 :   endSection(Section);
     911           0 : }
     912             : 
     913             : uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
     914             :   assert(Symbol.isFunction());
     915             :   assert(TypeIndices.count(&Symbol));
     916           0 :   return TypeIndices[&Symbol];
     917             : }
     918             : 
     919           0 : uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
     920             :   assert(Symbol.isFunction());
     921             : 
     922           0 :   WasmFunctionType F;
     923           0 :   if (Symbol.isVariable()) {
     924           0 :     const MCExpr *Expr = Symbol.getVariableValue();
     925           0 :     auto *Inner = cast<MCSymbolRefExpr>(Expr);
     926           0 :     const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
     927           0 :     F.Returns = ResolvedSym->getReturns();
     928           0 :     F.Params = ResolvedSym->getParams();
     929             :   } else {
     930           0 :     F.Returns = Symbol.getReturns();
     931           0 :     F.Params = Symbol.getParams();
     932             :   }
     933             : 
     934             :   auto Pair =
     935           0 :       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
     936           0 :   if (Pair.second)
     937           0 :     FunctionTypes.push_back(F);
     938           0 :   TypeIndices[&Symbol] = Pair.first->second;
     939             : 
     940             :   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
     941             :   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
     942           0 :   return Pair.first->second;
     943             : }
     944             : 
     945           0 : void WasmObjectWriter::writeObject(MCAssembler &Asm,
     946             :                                    const MCAsmLayout &Layout) {
     947             :   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
     948           0 :   MCContext &Ctx = Asm.getContext();
     949           0 :   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
     950             : 
     951             :   // Collect information from the available symbols.
     952           0 :   SmallVector<WasmFunction, 4> Functions;
     953           0 :   SmallVector<uint32_t, 4> TableElems;
     954           0 :   SmallVector<WasmGlobal, 4> Globals;
     955           0 :   SmallVector<WasmImport, 4> Imports;
     956           0 :   SmallVector<WasmExport, 4> Exports;
     957           0 :   SmallVector<StringRef, 4> WeakSymbols;
     958           0 :   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
     959           0 :   unsigned NumFuncImports = 0;
     960           0 :   unsigned NumGlobalImports = 0;
     961           0 :   SmallVector<char, 0> DataBytes;
     962           0 :   uint32_t DataAlignment = 1;
     963           0 :   uint32_t StackPointerGlobal = 0;
     964           0 :   bool HasStackPointer = false;
     965             : 
     966             :   // Populate the IsAddressTaken set.
     967           0 :   for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
     968           0 :     switch (RelEntry.Type) {
     969           0 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     970             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     971           0 :       IsAddressTaken.insert(RelEntry.Symbol);
     972           0 :       break;
     973             :     default:
     974             :       break;
     975             :     }
     976             :   }
     977           0 :   for (const WasmRelocationEntry &RelEntry : DataRelocations) {
     978           0 :     switch (RelEntry.Type) {
     979           0 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
     980             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     981           0 :       IsAddressTaken.insert(RelEntry.Symbol);
     982           0 :       break;
     983             :     default:
     984             :       break;
     985             :     }
     986             :   }
     987             : 
     988             :   // Populate the Imports set.
     989           0 :   for (const MCSymbol &S : Asm.symbols()) {
     990           0 :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
     991             : 
     992           0 :     if (WS.isTemporary())
     993           0 :       continue;
     994             : 
     995           0 :     if (WS.isFunction())
     996           0 :       registerFunctionType(WS);
     997             : 
     998             :     // If the symbol is not defined in this translation unit, import it.
     999           0 :     if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
    1000           0 :       WasmImport Import;
    1001           0 :       Import.ModuleName = WS.getModuleName();
    1002           0 :       Import.FieldName = WS.getName();
    1003             : 
    1004           0 :       if (WS.isFunction()) {
    1005           0 :         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
    1006           0 :         Import.Type = getFunctionType(WS);
    1007           0 :         SymbolIndices[&WS] = NumFuncImports;
    1008           0 :         ++NumFuncImports;
    1009             :       } else {
    1010           0 :         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1011           0 :         Import.Type = int32_t(PtrType);
    1012           0 :         SymbolIndices[&WS] = NumGlobalImports;
    1013           0 :         ++NumGlobalImports;
    1014             :       }
    1015             : 
    1016           0 :       Imports.push_back(Import);
    1017             :     }
    1018             :   }
    1019             : 
    1020             :   // In the special .global_variables section, we've encoded global
    1021             :   // variables used by the function. Translate them into the Globals
    1022             :   // list.
    1023           0 :   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
    1024           0 :   if (!GlobalVars->getFragmentList().empty()) {
    1025           0 :     if (GlobalVars->getFragmentList().size() != 1)
    1026           0 :       report_fatal_error("only one .global_variables fragment supported");
    1027           0 :     const MCFragment &Frag = *GlobalVars->begin();
    1028           0 :     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
    1029           0 :       report_fatal_error("only data supported in .global_variables");
    1030           0 :     const auto &DataFrag = cast<MCDataFragment>(Frag);
    1031           0 :     if (!DataFrag.getFixups().empty())
    1032           0 :       report_fatal_error("fixups not supported in .global_variables");
    1033           0 :     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
    1034           0 :     for (const uint8_t *p = (const uint8_t *)Contents.data(),
    1035           0 :                      *end = (const uint8_t *)Contents.data() + Contents.size();
    1036           0 :          p != end; ) {
    1037             :       WasmGlobal G;
    1038           0 :       if (end - p < 3)
    1039           0 :         report_fatal_error("truncated global variable encoding");
    1040           0 :       G.Type = wasm::ValType(int8_t(*p++));
    1041           0 :       G.IsMutable = bool(*p++);
    1042           0 :       G.HasImport = bool(*p++);
    1043           0 :       if (G.HasImport) {
    1044           0 :         G.InitialValue = 0;
    1045             : 
    1046           0 :         WasmImport Import;
    1047           0 :         Import.ModuleName = (const char *)p;
    1048           0 :         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
    1049           0 :         if (!nul)
    1050           0 :           report_fatal_error("global module name must be nul-terminated");
    1051           0 :         p = nul + 1;
    1052           0 :         nul = (const uint8_t *)memchr(p, '\0', end - p);
    1053           0 :         if (!nul)
    1054           0 :           report_fatal_error("global base name must be nul-terminated");
    1055           0 :         Import.FieldName = (const char *)p;
    1056           0 :         p = nul + 1;
    1057             : 
    1058           0 :         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1059           0 :         Import.Type = int32_t(G.Type);
    1060             : 
    1061           0 :         G.ImportIndex = NumGlobalImports;
    1062           0 :         ++NumGlobalImports;
    1063             : 
    1064           0 :         Imports.push_back(Import);
    1065             :       } else {
    1066             :         unsigned n;
    1067           0 :         G.InitialValue = decodeSLEB128(p, &n);
    1068           0 :         G.ImportIndex = 0;
    1069           0 :         if ((ptrdiff_t)n > end - p)
    1070           0 :           report_fatal_error("global initial value must be valid SLEB128");
    1071           0 :         p += n;
    1072             :       }
    1073           0 :       Globals.push_back(G);
    1074             :     }
    1075             :   }
    1076             : 
    1077             :   // In the special .stack_pointer section, we've encoded the stack pointer
    1078             :   // index.
    1079           0 :   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
    1080           0 :   if (!StackPtr->getFragmentList().empty()) {
    1081           0 :     if (StackPtr->getFragmentList().size() != 1)
    1082           0 :       report_fatal_error("only one .stack_pointer fragment supported");
    1083           0 :     const MCFragment &Frag = *StackPtr->begin();
    1084           0 :     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
    1085           0 :       report_fatal_error("only data supported in .stack_pointer");
    1086           0 :     const auto &DataFrag = cast<MCDataFragment>(Frag);
    1087           0 :     if (!DataFrag.getFixups().empty())
    1088           0 :       report_fatal_error("fixups not supported in .stack_pointer");
    1089           0 :     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
    1090           0 :     if (Contents.size() != 4)
    1091           0 :       report_fatal_error("only one entry supported in .stack_pointer");
    1092           0 :     HasStackPointer = true;
    1093           0 :     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
    1094             :   }
    1095             : 
    1096             :   // Handle regular defined and undefined symbols.
    1097           0 :   for (const MCSymbol &S : Asm.symbols()) {
    1098             :     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
    1099             :     // or used in relocations.
    1100           0 :     if (S.isTemporary() && S.getName().empty())
    1101           0 :       continue;
    1102             : 
    1103           0 :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1104             :     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
    1105             :                  << " isDefined=" << S.isDefined() << " isExternal="
    1106             :                  << S.isExternal() << " isTemporary=" << S.isTemporary()
    1107             :                  << " isFunction=" << WS.isFunction()
    1108             :                  << " isWeak=" << WS.isWeak()
    1109             :                  << " isVariable=" << WS.isVariable() << "\n");
    1110             : 
    1111           0 :     if (WS.isWeak())
    1112           0 :       WeakSymbols.push_back(WS.getName());
    1113             : 
    1114           0 :     if (WS.isVariable())
    1115           0 :       continue;
    1116             : 
    1117             :     unsigned Index;
    1118             : 
    1119           0 :     if (WS.isFunction()) {
    1120           0 :       if (WS.isDefined(/*SetUsed=*/false)) {
    1121           0 :         if (WS.getOffset() != 0)
    1122           0 :           report_fatal_error(
    1123             :               "function sections must contain one function each");
    1124             : 
    1125           0 :         if (WS.getSize() == 0)
    1126           0 :           report_fatal_error(
    1127             :               "function symbols must have a size set with .size");
    1128             : 
    1129             :         // A definition. Take the next available index.
    1130           0 :         Index = NumFuncImports + Functions.size();
    1131             : 
    1132             :         // Prepare the function.
    1133             :         WasmFunction Func;
    1134           0 :         Func.Type = getFunctionType(WS);
    1135           0 :         Func.Sym = &WS;
    1136           0 :         SymbolIndices[&WS] = Index;
    1137           0 :         Functions.push_back(Func);
    1138             :       } else {
    1139             :         // An import; the index was assigned above.
    1140           0 :         Index = SymbolIndices.find(&WS)->second;
    1141             :       }
    1142             : 
    1143             :       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
    1144             : 
    1145             :       // If needed, prepare the function to be called indirectly.
    1146           0 :       if (IsAddressTaken.count(&WS) != 0) {
    1147           0 :         IndirectSymbolIndices[&WS] = TableElems.size();
    1148             :         DEBUG(dbgs() << "  -> adding to table: " << TableElems.size() << "\n");
    1149           0 :         TableElems.push_back(Index);
    1150             :       }
    1151             :     } else {
    1152           0 :       if (WS.isTemporary() && !WS.getSize())
    1153           0 :         continue;
    1154             : 
    1155           0 :       if (!WS.isDefined(/*SetUsed=*/false))
    1156           0 :         continue;
    1157             : 
    1158           0 :       if (WS.getOffset() != 0)
    1159           0 :         report_fatal_error("data sections must contain one variable each: " +
    1160           0 :                            WS.getName());
    1161           0 :       if (!WS.getSize())
    1162           0 :         report_fatal_error("data symbols must have a size set with .size: " +
    1163           0 :                            WS.getName());
    1164             : 
    1165           0 :       int64_t Size = 0;
    1166           0 :       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
    1167           0 :         report_fatal_error(".size expression must be evaluatable");
    1168             : 
    1169           0 :       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
    1170             : 
    1171           0 :       if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
    1172           0 :         report_fatal_error("data sections must contain at most one variable");
    1173             : 
    1174           0 :       DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
    1175           0 :       DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
    1176             : 
    1177           0 :       DataSection.setSectionOffset(DataBytes.size());
    1178             : 
    1179           0 :       for (const MCFragment &Frag : DataSection) {
    1180           0 :         if (Frag.hasInstructions())
    1181           0 :           report_fatal_error("only data supported in data sections");
    1182             : 
    1183           0 :         if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
    1184           0 :           if (Align->getValueSize() != 1)
    1185           0 :             report_fatal_error("only byte values supported for alignment");
    1186             :           // If nops are requested, use zeros, as this is the data section.
    1187           0 :           uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
    1188           0 :           uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
    1189             :                                                      Align->getAlignment()),
    1190           0 :                                              DataBytes.size() +
    1191           0 :                                                  Align->getMaxBytesToEmit());
    1192           0 :           DataBytes.resize(Size, Value);
    1193           0 :         } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
    1194           0 :           DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
    1195             :         } else {
    1196           0 :           const auto &DataFrag = cast<MCDataFragment>(Frag);
    1197           0 :           const SmallVectorImpl<char> &Contents = DataFrag.getContents();
    1198             : 
    1199           0 :           DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
    1200             :         }
    1201             :       }
    1202             : 
    1203             :       // For each global, prepare a corresponding wasm global holding its
    1204             :       // address.  For externals these will also be named exports.
    1205           0 :       Index = NumGlobalImports + Globals.size();
    1206             : 
    1207             :       WasmGlobal Global;
    1208           0 :       Global.Type = PtrType;
    1209           0 :       Global.IsMutable = false;
    1210           0 :       Global.HasImport = false;
    1211           0 :       Global.InitialValue = DataSection.getSectionOffset();
    1212           0 :       Global.ImportIndex = 0;
    1213           0 :       SymbolIndices[&WS] = Index;
    1214             :       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
    1215           0 :       Globals.push_back(Global);
    1216             :     }
    1217             : 
    1218             :     // If the symbol is visible outside this translation unit, export it.
    1219           0 :     if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
    1220           0 :       WasmExport Export;
    1221           0 :       Export.FieldName = WS.getName();
    1222           0 :       Export.Index = Index;
    1223           0 :       if (WS.isFunction())
    1224           0 :         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
    1225             :       else
    1226           0 :         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1227             :       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
    1228           0 :       Exports.push_back(Export);
    1229             :     }
    1230             :   }
    1231             : 
    1232             :   // Handle weak aliases. We need to process these in a separate pass because
    1233             :   // we need to have processed the target of the alias before the alias itself
    1234             :   // and the symbols are not necessarily ordered in this way.
    1235           0 :   for (const MCSymbol &S : Asm.symbols()) {
    1236           0 :     if (!S.isVariable())
    1237           0 :       continue;
    1238             :     assert(S.isDefined(/*SetUsed=*/false));
    1239             : 
    1240           0 :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1241             :     // Find the target symbol of this weak alias and export that index
    1242           0 :     const MCExpr *Expr = WS.getVariableValue();
    1243           0 :     auto *Inner = cast<MCSymbolRefExpr>(Expr);
    1244           0 :     const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
    1245             :     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
    1246             :     assert(SymbolIndices.count(ResolvedSym) > 0);
    1247           0 :     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
    1248             :     DEBUG(dbgs() << "  -> index:" << Index << "\n");
    1249             : 
    1250           0 :     WasmExport Export;
    1251           0 :     Export.FieldName = WS.getName();
    1252           0 :     Export.Index = Index;
    1253           0 :     if (WS.isFunction())
    1254           0 :       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
    1255             :     else
    1256           0 :       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1257             :     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
    1258           0 :     Exports.push_back(Export);
    1259             :   }
    1260             : 
    1261             :   // Add types for indirect function calls.
    1262           0 :   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
    1263           0 :     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
    1264           0 :       continue;
    1265             : 
    1266           0 :     registerFunctionType(*Fixup.Symbol);
    1267             :   }
    1268             : 
    1269             :   // Write out the Wasm header.
    1270           0 :   writeHeader(Asm);
    1271             : 
    1272           0 :   writeTypeSection(FunctionTypes);
    1273           0 :   writeImportSection(Imports);
    1274           0 :   writeFunctionSection(Functions);
    1275           0 :   writeTableSection(TableElems.size());
    1276           0 :   writeMemorySection(DataBytes);
    1277           0 :   writeGlobalSection(Globals);
    1278           0 :   writeExportSection(Exports);
    1279             :   // TODO: Start Section
    1280           0 :   writeElemSection(TableElems);
    1281           0 :   writeCodeSection(Asm, Layout, Functions);
    1282           0 :   uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
    1283           0 :   writeNameSection(Functions, Imports, NumFuncImports);
    1284           0 :   writeCodeRelocSection();
    1285           0 :   writeDataRelocSection(DataSectionHeaderSize);
    1286           0 :   writeLinkingMetaDataSection(DataBytes.size(), DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
    1287             : 
    1288             :   // TODO: Translate the .comment section to the output.
    1289             :   // TODO: Translate debug sections to the output.
    1290           0 : }
    1291             : 
    1292           0 : MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
    1293             :                                              raw_pwrite_stream &OS) {
    1294           0 :   return new WasmObjectWriter(MOTW, OS);
    1295             : }

Generated by: LCOV version 1.13