blob: 366ca01502e39c8b3e355d6363478aa2bed829c2 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Cleggc94d3932017-11-17 18:14:09 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000010#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000011#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000012#include "InputEvent.h"
Sam Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "OutputSections.h"
15#include "OutputSegment.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000016#include "Relocations.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "SymbolTable.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000018#include "SyntheticSections.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "WriterUtils.h"
20#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000021#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000022#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000024#include "llvm/ADT/DenseSet.h"
Thomas Livelyf6f4f842019-03-20 20:26:45 +000025#include "llvm/ADT/SmallSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000026#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000027#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000028#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000029#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000030#include "llvm/Support/FileOutputBuffer.h"
31#include "llvm/Support/Format.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/LEB128.h"
34
35#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000036#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000037
38#define DEBUG_TYPE "lld"
39
40using namespace llvm;
41using namespace llvm::wasm;
Sam Cleggc94d3932017-11-17 18:14:09 +000042
Fangrui Song33c59ab2019-10-10 05:25:39 +000043namespace lld {
44namespace wasm {
Rui Ueyama136d27a2019-07-11 05:40:30 +000045static constexpr int stackAlignment = 16;
Sam Cleggc94d3932017-11-17 18:14:09 +000046
47namespace {
48
Sam Cleggc94d3932017-11-17 18:14:09 +000049// The writer writes a SymbolTable result to a file.
50class Writer {
51public:
52 void run();
53
54private:
55 void openFile();
56
Thomas Lively6004d9a2019-07-03 22:04:54 +000057 void createInitMemoryFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000058 void createApplyRelocationsFunction();
59 void createCallCtorsFunction();
Guanzhong Chen42bba4b2019-07-16 22:00:45 +000060 void createInitTLSFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000061
Sam Clegg8d146bb2018-01-09 23:56:44 +000062 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000063 void populateSymtab();
64 void populateProducers();
65 void populateTargetFeatures();
66 void calculateInitFunctions();
Sam Cleggc94d3932017-11-17 18:14:09 +000067 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000068 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000069 void calculateCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000070 void calculateTypes();
71 void createOutputSegments();
72 void layoutMemory();
73 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000074
Rui Ueyama136d27a2019-07-11 05:40:30 +000075 void addSection(OutputSection *sec);
Sam Clegg8fcf0122019-05-21 09:13:09 +000076
77 void addSections();
Sam Clegg4bce63a2019-05-23 10:06:03 +000078
Sam Clegg80ba4382018-04-10 16:12:49 +000079 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000080 void createSyntheticSections();
81 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000082
83 // Custom sections
84 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000085
86 void writeHeader();
87 void writeSections();
88
Rui Ueyama136d27a2019-07-11 05:40:30 +000089 uint64_t fileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000090
Rui Ueyama136d27a2019-07-11 05:40:30 +000091 std::vector<WasmInitEntry> initFunctions;
92 llvm::StringMap<std::vector<InputSection *>> customSectionMapping;
Sam Clegg80ba4382018-04-10 16:12:49 +000093
Sam Cleggc94d3932017-11-17 18:14:09 +000094 // Elements that are used to construct the final output
Rui Ueyama136d27a2019-07-11 05:40:30 +000095 std::string header;
96 std::vector<OutputSection *> outputSections;
Sam Cleggc94d3932017-11-17 18:14:09 +000097
Rui Ueyama136d27a2019-07-11 05:40:30 +000098 std::unique_ptr<FileOutputBuffer> buffer;
Sam Cleggc94d3932017-11-17 18:14:09 +000099
Rui Ueyama136d27a2019-07-11 05:40:30 +0000100 std::vector<OutputSegment *> segments;
101 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102};
103
104} // anonymous namespace
105
Sam Cleggd177ab22018-05-04 23:14:42 +0000106void Writer::calculateCustomSections() {
107 log("calculateCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000108 bool stripDebug = config->stripDebug || config->stripAll;
109 for (ObjFile *file : symtab->objectFiles) {
110 for (InputSection *section : file->customSections) {
111 StringRef name = section->getName();
Sam Cleggd177ab22018-05-04 23:14:42 +0000112 // These custom sections are known the linker and synthesized rather than
113 // blindly copied
Rui Ueyama136d27a2019-07-11 05:40:30 +0000114 if (name == "linking" || name == "name" || name == "producers" ||
115 name == "target_features" || name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000116 continue;
117 // .. or it is a debug section
Rui Ueyama136d27a2019-07-11 05:40:30 +0000118 if (stripDebug && name.startswith(".debug_"))
Sam Cleggd177ab22018-05-04 23:14:42 +0000119 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000120 customSectionMapping[name].push_back(section);
Sam Cleggd177ab22018-05-04 23:14:42 +0000121 }
122 }
123}
124
Sam Clegg80ba4382018-04-10 16:12:49 +0000125void Writer::createCustomSections() {
126 log("createCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000127 for (auto &pair : customSectionMapping) {
128 StringRef name = pair.first();
129 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000130
Benjamin Krameradcd0262020-01-28 20:23:46 +0100131 OutputSection *sec = make<CustomSection>(std::string(name), pair.second);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000132 if (config->relocatable || config->emitRelocs) {
133 auto *sym = make<OutputSectionSymbol>(sec);
134 out.linkingSec->addToSymtab(sym);
135 sec->sectionSym = sym;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000136 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000137 addSection(sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000138 }
139}
140
Sam Cleggd451da12017-12-19 19:56:27 +0000141// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000142// These are only created when relocatable output is requested.
143void Writer::createRelocSections() {
144 log("createRelocSections");
145 // Don't use iterator here since we are adding to OutputSection
Rui Ueyama136d27a2019-07-11 05:40:30 +0000146 size_t origSize = outputSections.size();
147 for (size_t i = 0; i < origSize; i++) {
148 LLVM_DEBUG(dbgs() << "check section " << i << "\n");
149 OutputSection *sec = outputSections[i];
Sam Clegg8fcf0122019-05-21 09:13:09 +0000150
151 // Count the number of needed sections.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000152 uint32_t count = sec->getNumRelocations();
153 if (!count)
Sam Cleggc94d3932017-11-17 18:14:09 +0000154 continue;
155
Rui Ueyama136d27a2019-07-11 05:40:30 +0000156 StringRef name;
157 if (sec->type == WASM_SEC_DATA)
158 name = "reloc.DATA";
159 else if (sec->type == WASM_SEC_CODE)
160 name = "reloc.CODE";
161 else if (sec->type == WASM_SEC_CUSTOM)
162 name = saver.save("reloc." + sec->name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000163 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000164 llvm_unreachable(
165 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000166
Rui Ueyama136d27a2019-07-11 05:40:30 +0000167 addSection(make<RelocSection>(name, sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 }
169}
170
Sam Clegg8fcf0122019-05-21 09:13:09 +0000171void Writer::populateProducers() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000172 for (ObjFile *file : symtab->objectFiles) {
173 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
174 out.producersSec->addInfo(info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000175 }
176}
177
Sam Cleggc94d3932017-11-17 18:14:09 +0000178void Writer::writeHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000179 memcpy(buffer->getBufferStart(), header.data(), header.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000180}
181
182void Writer::writeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000183 uint8_t *buf = buffer->getBufferStart();
184 parallelForEach(outputSections, [buf](OutputSection *s) {
185 assert(s->isNeeded());
186 s->writeTo(buf);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000187 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000188}
189
190// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000191// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000192// The default memory layout is as follows, from low to high.
193//
Fangrui Song33fdf822019-07-16 08:08:17 +0000194// - initialized data (starting at Config->globalBase)
Sam Cleggf0d433d2018-02-02 22:59:56 +0000195// - BSS data (not currently implemented in llvm)
196// - explicit stack (Config->ZStackSize)
197// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000198//
199// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000200// This can be useful since it means that stack overflow traps immediately
201// rather than overwriting global data, but also increases code size since all
202// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000203void Writer::layoutMemory() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000204 uint32_t memoryPtr = 0;
Sam Clegga0f095e2018-05-03 17:21:53 +0000205
Rui Ueyama136d27a2019-07-11 05:40:30 +0000206 auto placeStack = [&]() {
Sam Cleggfd11ce32019-07-11 13:13:25 +0000207 if (config->relocatable || config->isPic)
Sam Clegga0f095e2018-05-03 17:21:53 +0000208 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000209 memoryPtr = alignTo(memoryPtr, stackAlignment);
210 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
211 error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
212 log("mem: stack size = " + Twine(config->zStackSize));
213 log("mem: stack base = " + Twine(memoryPtr));
214 memoryPtr += config->zStackSize;
215 auto *sp = cast<DefinedGlobal>(WasmSym::stackPointer);
216 sp->global->global.InitExpr.Value.Int32 = memoryPtr;
217 log("mem: stack top = " + Twine(memoryPtr));
Sam Clegga0f095e2018-05-03 17:21:53 +0000218 };
219
Rui Ueyama136d27a2019-07-11 05:40:30 +0000220 if (config->stackFirst) {
221 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000222 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000223 memoryPtr = config->globalBase;
224 log("mem: global base = " + Twine(config->globalBase));
Sam Clegga0f095e2018-05-03 17:21:53 +0000225 }
226
Rui Ueyama136d27a2019-07-11 05:40:30 +0000227 if (WasmSym::globalBase)
Sam Clegg7185a732019-08-13 17:02:02 +0000228 WasmSym::globalBase->setVirtualAddress(memoryPtr);
Guanzhong Chene15dc952019-06-26 20:12:33 +0000229
Rui Ueyama136d27a2019-07-11 05:40:30 +0000230 uint32_t dataStart = memoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000231
Sam Cleggf0d433d2018-02-02 22:59:56 +0000232 // Arbitrarily set __dso_handle handle to point to the start of the data
233 // segments.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000234 if (WasmSym::dsoHandle)
235 WasmSym::dsoHandle->setVirtualAddress(dataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000236
Rui Ueyama136d27a2019-07-11 05:40:30 +0000237 out.dylinkSec->memAlign = 0;
238 for (OutputSegment *seg : segments) {
239 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
240 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
241 seg->startVA = memoryPtr;
242 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
243 memoryPtr, seg->size, seg->alignment));
244 memoryPtr += seg->size;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000245
246 if (WasmSym::tlsSize && seg->name == ".tdata") {
247 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
248 tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
Guanzhong Chen5204f762019-07-19 23:34:16 +0000249
250 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
251 tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000252 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000253 }
254
Thomas Lively09768c52019-09-04 19:50:39 +0000255 // Make space for the memory initialization flag
256 if (WasmSym::initMemoryFlag) {
257 memoryPtr = alignTo(memoryPtr, 4);
258 WasmSym::initMemoryFlag->setVirtualAddress(memoryPtr);
259 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
260 "__wasm_init_memory_flag", memoryPtr, 4, 4));
261 memoryPtr += 4;
262 }
263
Rui Ueyama136d27a2019-07-11 05:40:30 +0000264 if (WasmSym::dataEnd)
265 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000266
Rui Ueyama136d27a2019-07-11 05:40:30 +0000267 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000268
Rui Ueyama136d27a2019-07-11 05:40:30 +0000269 if (config->shared) {
270 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000271 return;
272 }
273
Rui Ueyama136d27a2019-07-11 05:40:30 +0000274 if (!config->stackFirst)
275 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000276
277 // Set `__heap_base` to directly follow the end of the stack or global data.
278 // The fact that this comes last means that a malloc/brk implementation
279 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000280 log("mem: heap base = " + Twine(memoryPtr));
281 if (WasmSym::heapBase)
282 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000283
Rui Ueyama136d27a2019-07-11 05:40:30 +0000284 if (config->initialMemory != 0) {
285 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000286 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000287 if (memoryPtr > config->initialMemory)
288 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000290 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000291 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000292 out.dylinkSec->memSize = memoryPtr;
293 out.memorySec->numMemoryPages =
294 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
295 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000296
Thomas Lively06391f32019-03-29 20:43:49 +0000297 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000298 if (config->maxMemory != 0 || config->sharedMemory) {
299 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000300 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000301 if (memoryPtr > config->maxMemory)
302 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
303 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
304 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000305 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000306}
307
Rui Ueyama136d27a2019-07-11 05:40:30 +0000308void Writer::addSection(OutputSection *sec) {
309 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000310 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000311 log("addSection: " + toString(*sec));
312 sec->sectionIndex = outputSections.size();
313 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000314}
315
Sam Clegg4bce63a2019-05-23 10:06:03 +0000316// If a section name is valid as a C identifier (which is rare because of
317// the leading '.'), linkers are expected to define __start_<secname> and
318// __stop_<secname> symbols. They are at beginning and end of the section,
319// respectively. This is not requested by the ELF standard, but GNU ld and
320// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000321static void addStartStopSymbols(const OutputSegment *seg) {
322 StringRef name = seg->name;
323 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000324 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000325 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
326 uint32_t start = seg->startVA;
327 uint32_t stop = start + seg->size;
328 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
329 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000330}
331
Sam Clegg8fcf0122019-05-21 09:13:09 +0000332void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000333 addSection(out.dylinkSec);
334 addSection(out.typeSec);
335 addSection(out.importSec);
336 addSection(out.functionSec);
337 addSection(out.tableSec);
338 addSection(out.memorySec);
339 addSection(out.globalSec);
340 addSection(out.eventSec);
341 addSection(out.exportSec);
Thomas Lively09768c52019-09-04 19:50:39 +0000342 addSection(out.startSec);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000343 addSection(out.elemSec);
344 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000345
Rui Ueyama136d27a2019-07-11 05:40:30 +0000346 addSection(make<CodeSection>(out.functionSec->inputFunctions));
347 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000348
Sam Clegg80ba4382018-04-10 16:12:49 +0000349 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000350
Rui Ueyama136d27a2019-07-11 05:40:30 +0000351 addSection(out.linkingSec);
352 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000353 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000354 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000355
Rui Ueyama136d27a2019-07-11 05:40:30 +0000356 addSection(out.nameSec);
357 addSection(out.producersSec);
358 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000359}
Sam Cleggc94d3932017-11-17 18:14:09 +0000360
Sam Clegg8fcf0122019-05-21 09:13:09 +0000361void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000362 for (OutputSection *s : outputSections) {
363 s->setOffset(fileSize);
364 s->finalizeContents();
365 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000366 }
367}
368
Sam Clegg8fcf0122019-05-21 09:13:09 +0000369void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000370 StringMap<std::string> used;
371 StringMap<std::string> required;
372 StringMap<std::string> disallowed;
Thomas Lively09768c52019-09-04 19:50:39 +0000373 SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000374 bool tlsUsed = false;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000375
Thomas Lively82de51a2019-03-26 04:11:05 +0000376 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000377 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000378
Rui Ueyama136d27a2019-07-11 05:40:30 +0000379 if (!inferFeatures) {
Thomas Lively09768c52019-09-04 19:50:39 +0000380 auto &explicitFeatures = config->features.getValue();
381 allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
Rui Ueyama136d27a2019-07-11 05:40:30 +0000382 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000383 return;
384 }
385
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000386 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000387 for (ObjFile *file : symtab->objectFiles) {
388 StringRef fileName(file->getName());
389 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
390 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000391 case WASM_FEATURE_PREFIX_USED:
Benjamin Krameradcd0262020-01-28 20:23:46 +0100392 used.insert({feature.Name, std::string(fileName)});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000393 break;
394 case WASM_FEATURE_PREFIX_REQUIRED:
Benjamin Krameradcd0262020-01-28 20:23:46 +0100395 used.insert({feature.Name, std::string(fileName)});
396 required.insert({feature.Name, std::string(fileName)});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000397 break;
398 case WASM_FEATURE_PREFIX_DISALLOWED:
Benjamin Krameradcd0262020-01-28 20:23:46 +0100399 disallowed.insert({feature.Name, std::string(fileName)});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000400 break;
401 default:
402 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000403 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000404 }
405 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000406
Thomas Lively09768c52019-09-04 19:50:39 +0000407 // Find TLS data segments
408 auto isTLS = [](InputSegment *segment) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000409 StringRef name = segment->getName();
Thomas Lively09768c52019-09-04 19:50:39 +0000410 return segment->live &&
411 (name.startswith(".tdata") || name.startswith(".tbss"));
412 };
413 tlsUsed = tlsUsed ||
414 std::any_of(file->segments.begin(), file->segments.end(), isTLS);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000415 }
416
Rui Ueyama136d27a2019-07-11 05:40:30 +0000417 if (inferFeatures)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100418 for (const auto &key : used.keys())
419 allowed.insert(std::string(key));
Thomas Lively82de51a2019-03-26 04:11:05 +0000420
Thomas Lively09768c52019-09-04 19:50:39 +0000421 if (allowed.count("atomics") && !config->sharedMemory) {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000422 if (inferFeatures)
423 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000424 ", so --shared-memory must be used");
425 else
426 error("'atomics' feature is used, so --shared-memory must be used");
427 }
Thomas Lively06391f32019-03-29 20:43:49 +0000428
Rui Ueyama136d27a2019-07-11 05:40:30 +0000429 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000430 return;
431
Rui Ueyama136d27a2019-07-11 05:40:30 +0000432 if (disallowed.count("atomics") && config->sharedMemory)
433 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000434 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000435
Thomas Lively09768c52019-09-04 19:50:39 +0000436 if (!allowed.count("atomics") && config->sharedMemory)
437 error("'atomics' feature must be used in order to use shared "
438 "memory");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000439
Thomas Lively09768c52019-09-04 19:50:39 +0000440 if (!allowed.count("bulk-memory") && config->sharedMemory)
441 error("'bulk-memory' feature must be used in order to use shared "
442 "memory");
443
444 if (!allowed.count("bulk-memory") && tlsUsed)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000445 error("'bulk-memory' feature must be used in order to use thread-local "
446 "storage");
447
Thomas Lively82de51a2019-03-26 04:11:05 +0000448 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000449 if (!inferFeatures) {
450 for (auto &feature : used.keys()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100451 if (!allowed.count(std::string(feature)))
Rui Ueyama136d27a2019-07-11 05:40:30 +0000452 error(Twine("Target feature '") + feature + "' used by " +
453 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000454 }
455 }
456
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000457 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000458 for (ObjFile *file : symtab->objectFiles) {
459 StringRef fileName(file->getName());
460 SmallSet<std::string, 8> objectFeatures;
461 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
462 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000463 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000464 objectFeatures.insert(feature.Name);
465 if (disallowed.count(feature.Name))
466 error(Twine("Target feature '") + feature.Name + "' used in " +
467 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000468 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000469 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000470 for (auto &feature : required.keys()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100471 if (!objectFeatures.count(std::string(feature)))
Rui Ueyama136d27a2019-07-11 05:40:30 +0000472 error(Twine("Missing target feature '") + feature + "' in " + fileName +
473 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000474 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000475 }
476 }
477}
478
Sam Cleggc94d3932017-11-17 18:14:09 +0000479void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000480 for (Symbol *sym : symtab->getSymbols()) {
481 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000482 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000483 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000484 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000485 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000486 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000487 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000488 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000489 // We don't generate imports for data symbols. They however can be imported
490 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000491 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000492 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000493
Rui Ueyama136d27a2019-07-11 05:40:30 +0000494 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
495 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000496 }
497}
498
Sam Cleggd3052d52018-01-18 23:40:49 +0000499void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000500 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000501 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000502
Rui Ueyama136d27a2019-07-11 05:40:30 +0000503 if (!config->relocatable && !config->importMemory)
504 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000505 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000506
Rui Ueyama136d27a2019-07-11 05:40:30 +0000507 if (!config->relocatable && config->exportTable)
508 out.exportSec->exports.push_back(
509 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000510
Sam Clegg937b9552019-09-24 20:52:12 +0000511 unsigned globalIndex =
512 out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
Sam Cleggd6beb322018-05-10 18:10:34 +0000513
Rui Ueyama136d27a2019-07-11 05:40:30 +0000514 for (Symbol *sym : symtab->getSymbols()) {
515 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000516 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000517 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000518 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000519
Rui Ueyama136d27a2019-07-11 05:40:30 +0000520 StringRef name = sym->getName();
521 WasmExport export_;
522 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
Sam Clegg881d8772019-11-05 10:15:56 -0800523 StringRef exportName = f->function->getExportName();
524 if (!exportName.empty()) {
525 name = exportName;
526 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000527 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
528 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000529 // TODO(sbc): Remove this check once to mutable global proposal is
530 // implement in all major browsers.
531 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000532 if (g->getGlobalType()->Mutable) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000533 // Only __stack_pointer and __tls_base should ever be create as mutable.
534 assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
Sam Clegg177b4582018-06-07 01:27:07 +0000535 continue;
536 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000537 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
538 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
539 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000540 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000541 auto *d = cast<DefinedData>(sym);
Sam Clegg937b9552019-09-24 20:52:12 +0000542 out.globalSec->dataAddressGlobals.push_back(d);
543 export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000544 }
545
Rui Ueyama136d27a2019-07-11 05:40:30 +0000546 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
547 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000548 }
Sam Clegg93102972018-02-23 05:08:53 +0000549}
550
Sam Clegg8fcf0122019-05-21 09:13:09 +0000551void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000552 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000553 return;
554
Rui Ueyama136d27a2019-07-11 05:40:30 +0000555 for (Symbol *sym : symtab->getSymbols())
556 if (sym->isUsedInRegularObj && sym->isLive())
557 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000558
Rui Ueyama136d27a2019-07-11 05:40:30 +0000559 for (ObjFile *file : symtab->objectFiles) {
560 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
561 for (Symbol *sym : file->getSymbols())
562 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
563 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000564 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000565}
566
Sam Cleggc94d3932017-11-17 18:14:09 +0000567void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000568 // The output type section is the union of the following sets:
569 // 1. Any signature used in the TYPE relocation
570 // 2. The signatures of all imported functions
571 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000572 // 4. The signatures of all imported events
573 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000574
Rui Ueyama136d27a2019-07-11 05:40:30 +0000575 for (ObjFile *file : symtab->objectFiles) {
576 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
577 for (uint32_t i = 0; i < types.size(); i++)
578 if (file->typeIsUsed[i])
579 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 }
Sam Clegg50686852018-01-12 18:35:13 +0000581
Rui Ueyama136d27a2019-07-11 05:40:30 +0000582 for (const Symbol *sym : out.importSec->importedSymbols) {
583 if (auto *f = dyn_cast<FunctionSymbol>(sym))
584 out.typeSec->registerType(*f->signature);
585 else if (auto *e = dyn_cast<EventSymbol>(sym))
586 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000587 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000588
Rui Ueyama136d27a2019-07-11 05:40:30 +0000589 for (const InputFunction *f : out.functionSec->inputFunctions)
590 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000591
Rui Ueyama136d27a2019-07-11 05:40:30 +0000592 for (const InputEvent *e : out.eventSec->inputEvents)
593 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000594}
595
Sam Clegg8fcf0122019-05-21 09:13:09 +0000596static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000597 for (ObjFile *file : symtab->objectFiles) {
598 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
599 for (InputChunk *chunk : file->functions)
600 scanRelocations(chunk);
601 for (InputChunk *chunk : file->segments)
602 scanRelocations(chunk);
603 for (auto &p : file->customSections)
604 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000605 }
606}
607
Sam Clegg8d146bb2018-01-09 23:56:44 +0000608void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000609 // Seal the import section, since other index spaces such as function and
610 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000611 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000612
Rui Ueyama136d27a2019-07-11 05:40:30 +0000613 for (InputFunction *func : symtab->syntheticFunctions)
614 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000615
Rui Ueyama136d27a2019-07-11 05:40:30 +0000616 for (ObjFile *file : symtab->objectFiles) {
617 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
618 for (InputFunction *func : file->functions)
619 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000620 }
621
Rui Ueyama136d27a2019-07-11 05:40:30 +0000622 for (InputGlobal *global : symtab->syntheticGlobals)
623 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000624
Rui Ueyama136d27a2019-07-11 05:40:30 +0000625 for (ObjFile *file : symtab->objectFiles) {
626 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
627 for (InputGlobal *global : file->globals)
628 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000629 }
Heejin Ahne915a712018-12-08 06:17:43 +0000630
Rui Ueyama136d27a2019-07-11 05:40:30 +0000631 for (ObjFile *file : symtab->objectFiles) {
632 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
633 for (InputEvent *event : file->events)
634 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000635 }
Sam Clegg7185a732019-08-13 17:02:02 +0000636
637 out.globalSec->assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000638}
639
Rui Ueyama136d27a2019-07-11 05:40:30 +0000640static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000641 // With PIC code we currently only support a single data segment since
642 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000643 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000644 return ".data";
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000645 // We only support one thread-local segment, so we must merge the segments
646 // despite --no-merge-data-segments.
647 // We also need to merge .tbss into .tdata so they share the same offsets.
648 if (name.startswith(".tdata") || name.startswith(".tbss"))
649 return ".tdata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000650 if (!config->mergeDataSegments)
651 return name;
652 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000653 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000654 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000655 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000656 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000657 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000658 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000659 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000660 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000661}
662
663void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000664 for (ObjFile *file : symtab->objectFiles) {
665 for (InputSegment *segment : file->segments) {
666 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000667 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000668 StringRef name = getOutputDataSegmentName(segment->getName());
669 OutputSegment *&s = segmentMap[name];
670 if (s == nullptr) {
671 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
Thomas Lively21143b92019-09-19 01:14:59 +0000672 s = make<OutputSegment>(name);
Thomas Lively09768c52019-09-04 19:50:39 +0000673 if (config->sharedMemory || name == ".tdata")
Rui Ueyama136d27a2019-07-11 05:40:30 +0000674 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
Thomas Lively190dacc2019-10-15 19:05:11 +0000675 // Exported memories are guaranteed to be zero-initialized, so no need
676 // to emit data segments for bss sections.
677 // TODO: consider initializing bss sections with memory.fill
678 // instructions when memory is imported and bulk-memory is available.
679 if (!config->importMemory && !config->relocatable &&
680 name.startswith(".bss"))
681 s->isBss = true;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000682 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000683 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000684 s->addInputSegment(segment);
685 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000686 }
687 }
Thomas Lively21143b92019-09-19 01:14:59 +0000688
689 // Sort segments by type, placing .bss last
690 std::stable_sort(segments.begin(), segments.end(),
691 [](const OutputSegment *a, const OutputSegment *b) {
692 auto order = [](StringRef name) {
693 return StringSwitch<int>(name)
694 .StartsWith(".rodata", 0)
695 .StartsWith(".data", 1)
696 .StartsWith(".tdata", 2)
697 .StartsWith(".bss", 4)
698 .Default(3);
699 };
700 return order(a->name) < order(b->name);
701 });
702
Thomas Lively0c3d4cf2019-09-19 21:51:52 +0000703 for (size_t i = 0; i < segments.size(); ++i)
Thomas Lively21143b92019-09-19 01:14:59 +0000704 segments[i]->index = i;
Sam Cleggc94d3932017-11-17 18:14:09 +0000705}
706
Rui Ueyama136d27a2019-07-11 05:40:30 +0000707static void createFunction(DefinedFunction *func, StringRef bodyContent) {
708 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000709 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000710 raw_string_ostream os(functionBody);
711 writeUleb128(os, bodyContent.size(), "function size");
712 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000713 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000714 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
715 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000716}
717
718void Writer::createInitMemoryFunction() {
719 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Thomas Lively09768c52019-09-04 19:50:39 +0000720 assert(WasmSym::initMemoryFlag);
721 uint32_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000722 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000723 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000724 raw_string_ostream os(bodyContent);
725 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000726
Thomas Lively09768c52019-09-04 19:50:39 +0000727 if (segments.size()) {
728 // Initialize memory in a thread-safe manner. The thread that successfully
729 // increments the flag from 0 to 1 is is responsible for performing the
730 // memory initialization. Other threads go sleep on the flag until the
731 // first thread finishing initializing memory, increments the flag to 2,
732 // and wakes all the other threads. Once the flag has been set to 2,
733 // subsequently started threads will skip the sleep. All threads
734 // unconditionally drop their passive data segments once memory has been
735 // initialized. The generated code is as follows:
736 //
737 // (func $__wasm_init_memory
738 // (if
739 // (i32.atomic.rmw.cmpxchg align=2 offset=0
740 // (i32.const $__init_memory_flag)
741 // (i32.const 0)
742 // (i32.const 1)
743 // )
744 // (then
745 // (drop
746 // (i32.atomic.wait align=2 offset=0
747 // (i32.const $__init_memory_flag)
748 // (i32.const 1)
749 // (i32.const -1)
750 // )
751 // )
752 // )
753 // (else
754 // ( ... initialize data segments ... )
755 // (i32.atomic.store align=2 offset=0
756 // (i32.const $__init_memory_flag)
757 // (i32.const 2)
758 // )
759 // (drop
760 // (i32.atomic.notify align=2 offset=0
761 // (i32.const $__init_memory_flag)
762 // (i32.const -1u)
763 // )
764 // )
765 // )
766 // )
767 // ( ... drop data segments ... )
768 // )
769
770 // Atomically check whether this is the main thread.
771 writeI32Const(os, flagAddress, "flag address");
772 writeI32Const(os, 0, "expected flag value");
773 writeI32Const(os, 1, "flag value");
774 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
775 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
776 writeMemArg(os, 2, 0);
777 writeU8(os, WASM_OPCODE_IF, "IF");
778 writeU8(os, WASM_TYPE_NORESULT, "blocktype");
779
780 // Did not increment 0, so wait for main thread to initialize memory
781 writeI32Const(os, flagAddress, "flag address");
782 writeI32Const(os, 1, "expected flag value");
783 writeI64Const(os, -1, "timeout");
784 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
785 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
786 writeMemArg(os, 2, 0);
787 writeU8(os, WASM_OPCODE_DROP, "drop");
788
789 writeU8(os, WASM_OPCODE_ELSE, "ELSE");
790
791 // Did increment 0, so conditionally initialize passive data segments
792 for (const OutputSegment *s : segments) {
793 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
794 // destination address
795 writeI32Const(os, s->startVA, "destination address");
796 // source segment offset
797 writeI32Const(os, 0, "segment offset");
798 // memory region size
799 writeI32Const(os, s->size, "memory region size");
800 // memory.init instruction
801 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
802 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
803 writeUleb128(os, s->index, "segment index immediate");
804 writeU8(os, 0, "memory index immediate");
805 }
806 }
807
808 // Set flag to 2 to mark end of initialization
809 writeI32Const(os, flagAddress, "flag address");
810 writeI32Const(os, 2, "flag value");
811 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
812 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
813 writeMemArg(os, 2, 0);
814
815 // Notify any waiters that memory initialization is complete
816 writeI32Const(os, flagAddress, "flag address");
817 writeI32Const(os, -1, "number of waiters");
818 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
819 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
820 writeMemArg(os, 2, 0);
821 writeU8(os, WASM_OPCODE_DROP, "drop");
822
823 writeU8(os, WASM_OPCODE_END, "END");
824
825 // Unconditionally drop passive data segments
826 for (const OutputSegment *s : segments) {
827 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
828 // data.drop instruction
829 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
830 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
831 writeUleb128(os, s->index, "segment index immediate");
832 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000833 }
834 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000835 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000836 }
837
Rui Ueyama136d27a2019-07-11 05:40:30 +0000838 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000839}
840
Sam Clegg09137be2019-04-04 18:40:51 +0000841// For -shared (PIC) output, we create create a synthetic function which will
842// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000843// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
844// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000845void Writer::createApplyRelocationsFunction() {
846 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
847 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000848 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000849 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000850 raw_string_ostream os(bodyContent);
851 writeUleb128(os, 0, "num locals");
852 for (const OutputSegment *seg : segments)
853 for (const InputSegment *inSeg : seg->inputSegments)
854 inSeg->generateRelocationCode(os);
855 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000856 }
857
Rui Ueyama136d27a2019-07-11 05:40:30 +0000858 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000859}
Sam Clegg50686852018-01-12 18:35:13 +0000860
861// Create synthetic "__wasm_call_ctors" function based on ctor functions
862// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000863void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000864 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000865 return;
866
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000867 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000868 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000869 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000870 raw_string_ostream os(bodyContent);
871 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000872
Rui Ueyama136d27a2019-07-11 05:40:30 +0000873 if (config->isPic) {
874 writeU8(os, WASM_OPCODE_CALL, "CALL");
875 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000876 "function index");
877 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000878
879 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000880 for (const WasmInitEntry &f : initFunctions) {
881 writeU8(os, WASM_OPCODE_CALL, "CALL");
882 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000883 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000884 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000885 }
886
Rui Ueyama136d27a2019-07-11 05:40:30 +0000887 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000888}
889
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000890void Writer::createInitTLSFunction() {
891 if (!WasmSym::initTLS->isLive())
892 return;
893
894 std::string bodyContent;
895 {
896 raw_string_ostream os(bodyContent);
897
898 OutputSegment *tlsSeg = nullptr;
899 for (auto *seg : segments) {
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000900 if (seg->name == ".tdata") {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000901 tlsSeg = seg;
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000902 break;
903 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000904 }
905
906 writeUleb128(os, 0, "num locals");
907 if (tlsSeg) {
908 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
909 writeUleb128(os, 0, "local index");
910
911 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
912 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
913
914 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
915 writeUleb128(os, 0, "local index");
916
Thomas Lively09768c52019-09-04 19:50:39 +0000917 writeI32Const(os, 0, "segment offset");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000918
Thomas Lively09768c52019-09-04 19:50:39 +0000919 writeI32Const(os, tlsSeg->size, "memory region size");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000920
921 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
922 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
923 writeUleb128(os, tlsSeg->index, "segment index immediate");
924 writeU8(os, 0, "memory index immediate");
925 }
926 writeU8(os, WASM_OPCODE_END, "end function");
927 }
928
929 createFunction(WasmSym::initTLS, bodyContent);
930}
931
Sam Clegg50686852018-01-12 18:35:13 +0000932// Populate InitFunctions vector with init functions from all input objects.
933// This is then used either when creating the output linking section or to
934// synthesize the "__wasm_call_ctors" function.
935void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000936 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000937 return;
938
Rui Ueyama136d27a2019-07-11 05:40:30 +0000939 for (ObjFile *file : symtab->objectFiles) {
940 const WasmLinkingData &l = file->getWasmObj()->linkingData();
941 for (const WasmInitFunc &f : l.InitFunctions) {
942 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000943 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000944 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000945 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000946 assert(sym->isLive());
947 if (*sym->signature != WasmSignature{{}, {}})
948 error("invalid signature for init func: " + toString(*sym));
Sam Cleggaccad762019-07-17 18:43:36 +0000949 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000950 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000951 }
Sam Clegg50686852018-01-12 18:35:13 +0000952 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000953
Sam Clegg50686852018-01-12 18:35:13 +0000954 // Sort in order of priority (lowest first) so that they are called
955 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000956 llvm::stable_sort(initFunctions,
957 [](const WasmInitEntry &l, const WasmInitEntry &r) {
958 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000959 });
Sam Clegg50686852018-01-12 18:35:13 +0000960}
961
Sam Clegg8fcf0122019-05-21 09:13:09 +0000962void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000963 out.dylinkSec = make<DylinkSection>();
964 out.typeSec = make<TypeSection>();
965 out.importSec = make<ImportSection>();
966 out.functionSec = make<FunctionSection>();
967 out.tableSec = make<TableSection>();
968 out.memorySec = make<MemorySection>();
969 out.globalSec = make<GlobalSection>();
970 out.eventSec = make<EventSection>();
971 out.exportSec = make<ExportSection>();
Thomas Lively09768c52019-09-04 19:50:39 +0000972 out.startSec = make<StartSection>(segments.size());
Sam Clegg1a1df722019-08-27 04:19:34 +0000973 out.elemSec = make<ElemSection>();
Thomas Lively190dacc2019-10-15 19:05:11 +0000974 out.dataCountSec = make<DataCountSection>(segments);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000975 out.linkingSec = make<LinkingSection>(initFunctions, segments);
976 out.nameSec = make<NameSection>();
977 out.producersSec = make<ProducersSection>();
978 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000979}
980
Sam Cleggc94d3932017-11-17 18:14:09 +0000981void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000982 if (config->relocatable || config->isPic)
983 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000984
Sam Cleggbfb75342018-11-15 00:37:21 +0000985 // For PIC code the table base is assigned dynamically by the loader.
986 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Sam Clegg7185a732019-08-13 17:02:02 +0000987 if (!config->isPic) {
Sam Clegg1a1df722019-08-27 04:19:34 +0000988 config->tableBase = 1;
Sam Clegg7185a732019-08-13 17:02:02 +0000989 if (WasmSym::definedTableBase)
Sam Clegg1a1df722019-08-27 04:19:34 +0000990 WasmSym::definedTableBase->setVirtualAddress(config->tableBase);
Sam Clegg7185a732019-08-13 17:02:02 +0000991 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000992
Sam Clegg8fcf0122019-05-21 09:13:09 +0000993 log("-- createOutputSegments");
994 createOutputSegments();
995 log("-- createSyntheticSections");
996 createSyntheticSections();
997 log("-- populateProducers");
998 populateProducers();
999 log("-- populateTargetFeatures");
1000 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +00001001 log("-- calculateImports");
1002 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +00001003 log("-- layoutMemory");
1004 layoutMemory();
1005
Rui Ueyama136d27a2019-07-11 05:40:30 +00001006 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +00001007 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1008 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +00001009 for (const OutputSegment *seg : segments)
1010 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +00001011 }
1012
Sam Cleggb9889bb2019-05-23 09:41:03 +00001013 log("-- scanRelocations");
1014 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +00001015 log("-- assignIndexes");
1016 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +00001017 log("-- calculateInitFunctions");
1018 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +00001019
Rui Ueyama136d27a2019-07-11 05:40:30 +00001020 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +00001021 // Create linker synthesized functions
Thomas Lively09768c52019-09-04 19:50:39 +00001022 if (config->sharedMemory)
Thomas Lively6004d9a2019-07-03 22:04:54 +00001023 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +00001024 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +00001025 createApplyRelocationsFunction();
1026 createCallCtorsFunction();
1027 }
Sam Clegg4bce63a2019-05-23 10:06:03 +00001028
Guanzhong Chen0cb776e2019-08-06 20:09:04 +00001029 if (!config->relocatable && config->sharedMemory && !config->shared)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +00001030 createInitTLSFunction();
1031
1032 if (errorCount())
1033 return;
1034
Sam Clegg4bce63a2019-05-23 10:06:03 +00001035 log("-- calculateTypes");
1036 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001037 log("-- calculateExports");
1038 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001039 log("-- calculateCustomSections");
1040 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001041 log("-- populateSymtab");
1042 populateSymtab();
1043 log("-- addSections");
1044 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001045
Rui Ueyama136d27a2019-07-11 05:40:30 +00001046 if (errorHandler().verbose) {
1047 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
Sam Clegg937b9552019-09-24 20:52:12 +00001048 log("Defined Globals : " + Twine(out.globalSec->numGlobals()));
Rui Ueyama136d27a2019-07-11 05:40:30 +00001049 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +00001050 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +00001051 Twine(out.importSec->getNumImportedFunctions()));
1052 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
1053 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
1054 for (ObjFile *file : symtab->objectFiles)
1055 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +00001056 }
1057
Sam Cleggc94d3932017-11-17 18:14:09 +00001058 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001059 log("-- finalizeSections");
1060 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001061
1062 log("-- openFile");
1063 openFile();
1064 if (errorCount())
1065 return;
1066
1067 writeHeader();
1068
1069 log("-- writeSections");
1070 writeSections();
1071 if (errorCount())
1072 return;
1073
Rui Ueyama136d27a2019-07-11 05:40:30 +00001074 if (Error e = buffer->commit())
1075 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +00001076}
1077
1078// Open a result file.
1079void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001080 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001081
Rui Ueyama136d27a2019-07-11 05:40:30 +00001082 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1083 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +00001084 FileOutputBuffer::F_executable);
1085
Rui Ueyama136d27a2019-07-11 05:40:30 +00001086 if (!bufferOrErr)
1087 error("failed to open " + config->outputFile + ": " +
1088 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +00001089 else
Rui Ueyama136d27a2019-07-11 05:40:30 +00001090 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +00001091}
1092
1093void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001094 raw_string_ostream os(header);
1095 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1096 writeU32(os, WasmVersion, "wasm version");
1097 os.flush();
1098 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +00001099}
1100
Fangrui Song33c59ab2019-10-10 05:25:39 +00001101void writeResult() { Writer().run(); }
1102
1103} // namespace wasm
1104} // namespace lld