xref: /openbsd-src/gnu/llvm/lld/wasm/InputFiles.cpp (revision 824adb5411e4389b29bae28eba5c2c2bbd147f34)
1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputFiles.h"
10 #include "Config.h"
11 #include "InputChunks.h"
12 #include "InputEvent.h"
13 #include "InputGlobal.h"
14 #include "SymbolTable.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Reproduce.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/Wasm.h"
20 #include "llvm/Support/TarWriter.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 #define DEBUG_TYPE "lld"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::wasm;
28 
29 namespace lld {
30 
31 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
32 std::string toString(const wasm::InputFile *file) {
33   if (!file)
34     return "<internal>";
35 
36   if (file->archiveName.empty())
37     return std::string(file->getName());
38 
39   return (file->archiveName + "(" + file->getName() + ")").str();
40 }
41 
42 namespace wasm {
43 std::unique_ptr<llvm::TarWriter> tar;
44 
45 Optional<MemoryBufferRef> readFile(StringRef path) {
46   log("Loading: " + path);
47 
48   auto mbOrErr = MemoryBuffer::getFile(path);
49   if (auto ec = mbOrErr.getError()) {
50     error("cannot open " + path + ": " + ec.message());
51     return None;
52   }
53   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
54   MemoryBufferRef mbref = mb->getMemBufferRef();
55   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
56 
57   if (tar)
58     tar->append(relativeToRoot(path), mbref.getBuffer());
59   return mbref;
60 }
61 
62 InputFile *createObjectFile(MemoryBufferRef mb,
63                                        StringRef archiveName) {
64   file_magic magic = identify_magic(mb.getBuffer());
65   if (magic == file_magic::wasm_object) {
66     std::unique_ptr<Binary> bin =
67         CHECK(createBinary(mb), mb.getBufferIdentifier());
68     auto *obj = cast<WasmObjectFile>(bin.get());
69     if (obj->isSharedObject())
70       return make<SharedFile>(mb);
71     return make<ObjFile>(mb, archiveName);
72   }
73 
74   if (magic == file_magic::bitcode)
75     return make<BitcodeFile>(mb, archiveName);
76 
77   fatal("unknown file type: " + mb.getBufferIdentifier());
78 }
79 
80 void ObjFile::dumpInfo() const {
81   log("info for: " + toString(this) +
82       "\n              Symbols : " + Twine(symbols.size()) +
83       "\n     Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) +
84       "\n       Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) +
85       "\n        Event Imports : " + Twine(wasmObj->getNumImportedEvents()));
86 }
87 
88 // Relocations contain either symbol or type indices.  This function takes a
89 // relocation and returns relocated index (i.e. translates from the input
90 // symbol/type space to the output symbol/type space).
91 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
92   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
93     assert(typeIsUsed[reloc.Index]);
94     return typeMap[reloc.Index];
95   }
96   const Symbol *sym = symbols[reloc.Index];
97   if (auto *ss = dyn_cast<SectionSymbol>(sym))
98     sym = ss->getOutputSectionSymbol();
99   return sym->getOutputSymbolIndex();
100 }
101 
102 // Relocations can contain addend for combined sections. This function takes a
103 // relocation and returns updated addend by offset in the output section.
104 uint64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
105   switch (reloc.Type) {
106   case R_WASM_MEMORY_ADDR_LEB:
107   case R_WASM_MEMORY_ADDR_LEB64:
108   case R_WASM_MEMORY_ADDR_SLEB64:
109   case R_WASM_MEMORY_ADDR_SLEB:
110   case R_WASM_MEMORY_ADDR_REL_SLEB:
111   case R_WASM_MEMORY_ADDR_REL_SLEB64:
112   case R_WASM_MEMORY_ADDR_I32:
113   case R_WASM_MEMORY_ADDR_I64:
114   case R_WASM_FUNCTION_OFFSET_I32:
115     return reloc.Addend;
116   case R_WASM_SECTION_OFFSET_I32:
117     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
118   default:
119     llvm_unreachable("unexpected relocation type");
120   }
121 }
122 
123 // Calculate the value we expect to find at the relocation location.
124 // This is used as a sanity check before applying a relocation to a given
125 // location.  It is useful for catching bugs in the compiler and linker.
126 uint64_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const {
127   switch (reloc.Type) {
128   case R_WASM_TABLE_INDEX_I32:
129   case R_WASM_TABLE_INDEX_SLEB: {
130     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
131     return tableEntries[sym.Info.ElementIndex];
132   }
133   case R_WASM_TABLE_INDEX_REL_SLEB: {
134     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
135     return tableEntriesRel[sym.Info.ElementIndex];
136   }
137   case R_WASM_MEMORY_ADDR_LEB:
138   case R_WASM_MEMORY_ADDR_LEB64:
139   case R_WASM_MEMORY_ADDR_SLEB:
140   case R_WASM_MEMORY_ADDR_SLEB64:
141   case R_WASM_MEMORY_ADDR_REL_SLEB:
142   case R_WASM_MEMORY_ADDR_REL_SLEB64:
143   case R_WASM_MEMORY_ADDR_I32:
144   case R_WASM_MEMORY_ADDR_I64: {
145     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
146     if (sym.isUndefined())
147       return 0;
148     const WasmSegment &segment =
149         wasmObj->dataSegments()[sym.Info.DataRef.Segment];
150     if (segment.Data.Offset.Opcode == WASM_OPCODE_I32_CONST)
151       return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset +
152              reloc.Addend;
153     else if (segment.Data.Offset.Opcode == WASM_OPCODE_I64_CONST)
154       return segment.Data.Offset.Value.Int64 + sym.Info.DataRef.Offset +
155              reloc.Addend;
156     else
157       llvm_unreachable("unknown init expr opcode");
158   }
159   case R_WASM_FUNCTION_OFFSET_I32: {
160     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
161     InputFunction *f =
162         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
163     return f->getFunctionInputOffset() + f->getFunctionCodeOffset() +
164            reloc.Addend;
165   }
166   case R_WASM_SECTION_OFFSET_I32:
167     return reloc.Addend;
168   case R_WASM_TYPE_INDEX_LEB:
169     return reloc.Index;
170   case R_WASM_FUNCTION_INDEX_LEB:
171   case R_WASM_GLOBAL_INDEX_LEB:
172   case R_WASM_GLOBAL_INDEX_I32:
173   case R_WASM_EVENT_INDEX_LEB: {
174     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
175     return sym.Info.ElementIndex;
176   }
177   default:
178     llvm_unreachable("unknown relocation type");
179   }
180 }
181 
182 // Translate from the relocation's index into the final linked output value.
183 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc) const {
184   const Symbol* sym = nullptr;
185   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
186     sym = symbols[reloc.Index];
187 
188     // We can end up with relocations against non-live symbols.  For example
189     // in debug sections. We return reloc.Addend because always returning zero
190     // causes the generation of spurious range-list terminators in the
191     // .debug_ranges section.
192     if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive())
193       return reloc.Addend;
194   }
195 
196   switch (reloc.Type) {
197   case R_WASM_TABLE_INDEX_I32:
198   case R_WASM_TABLE_INDEX_SLEB:
199   case R_WASM_TABLE_INDEX_REL_SLEB: {
200     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
201       return 0;
202     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
203     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB)
204       index -= config->tableBase;
205     return index;
206 
207   }
208   case R_WASM_MEMORY_ADDR_LEB:
209   case R_WASM_MEMORY_ADDR_LEB64:
210   case R_WASM_MEMORY_ADDR_SLEB:
211   case R_WASM_MEMORY_ADDR_SLEB64:
212   case R_WASM_MEMORY_ADDR_REL_SLEB:
213   case R_WASM_MEMORY_ADDR_REL_SLEB64:
214   case R_WASM_MEMORY_ADDR_I32:
215   case R_WASM_MEMORY_ADDR_I64:
216     if (isa<UndefinedData>(sym) || sym->isUndefWeak())
217       return 0;
218     return cast<DefinedData>(sym)->getVirtualAddress() + reloc.Addend;
219   case R_WASM_TYPE_INDEX_LEB:
220     return typeMap[reloc.Index];
221   case R_WASM_FUNCTION_INDEX_LEB:
222     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
223   case R_WASM_GLOBAL_INDEX_LEB:
224   case R_WASM_GLOBAL_INDEX_I32:
225     if (auto gs = dyn_cast<GlobalSymbol>(sym))
226       return gs->getGlobalIndex();
227     return sym->getGOTIndex();
228   case R_WASM_EVENT_INDEX_LEB:
229     return getEventSymbol(reloc.Index)->getEventIndex();
230   case R_WASM_FUNCTION_OFFSET_I32: {
231     auto *f = cast<DefinedFunction>(sym);
232     return f->function->outputOffset +
233            (f->function->getFunctionCodeOffset() + reloc.Addend);
234   }
235   case R_WASM_SECTION_OFFSET_I32:
236     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
237   default:
238     llvm_unreachable("unknown relocation type");
239   }
240 }
241 
242 template <class T>
243 static void setRelocs(const std::vector<T *> &chunks,
244                       const WasmSection *section) {
245   if (!section)
246     return;
247 
248   ArrayRef<WasmRelocation> relocs = section->Relocations;
249   assert(llvm::is_sorted(
250       relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
251         return r1.Offset < r2.Offset;
252       }));
253   assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
254     return c1->getInputSectionOffset() < c2->getInputSectionOffset();
255   }));
256 
257   auto relocsNext = relocs.begin();
258   auto relocsEnd = relocs.end();
259   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
260     return r.Offset < val;
261   };
262   for (InputChunk *c : chunks) {
263     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
264                                         c->getInputSectionOffset(), relocLess);
265     relocsNext = std::lower_bound(
266         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
267         relocLess);
268     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
269   }
270 }
271 
272 void ObjFile::parse(bool ignoreComdats) {
273   // Parse a memory buffer as a wasm file.
274   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
275   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
276 
277   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
278   if (!obj)
279     fatal(toString(this) + ": not a wasm file");
280   if (!obj->isRelocatableObject())
281     fatal(toString(this) + ": not a relocatable wasm file");
282 
283   bin.release();
284   wasmObj.reset(obj);
285 
286   // Build up a map of function indices to table indices for use when
287   // verifying the existing table index relocations
288   uint32_t totalFunctions =
289       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
290   tableEntriesRel.resize(totalFunctions);
291   tableEntries.resize(totalFunctions);
292   for (const WasmElemSegment &seg : wasmObj->elements()) {
293     int64_t offset;
294     if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST)
295       offset = seg.Offset.Value.Int32;
296     else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST)
297       offset = seg.Offset.Value.Int64;
298     else
299       fatal(toString(this) + ": invalid table elements");
300     for (size_t index = 0; index < seg.Functions.size(); index++) {
301       auto functionIndex = seg.Functions[index];
302       tableEntriesRel[functionIndex] = index;
303       tableEntries[functionIndex] = offset + index;
304     }
305   }
306 
307   uint32_t sectionIndex = 0;
308 
309   // Bool for each symbol, true if called directly.  This allows us to implement
310   // a weaker form of signature checking where undefined functions that are not
311   // called directly (i.e. only address taken) don't have to match the defined
312   // function's signature.  We cannot do this for directly called functions
313   // because those signatures are checked at validation times.
314   // See https://bugs.llvm.org/show_bug.cgi?id=40412
315   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
316   for (const SectionRef &sec : wasmObj->sections()) {
317     const WasmSection &section = wasmObj->getWasmSection(sec);
318     // Wasm objects can have at most one code and one data section.
319     if (section.Type == WASM_SEC_CODE) {
320       assert(!codeSection);
321       codeSection = &section;
322     } else if (section.Type == WASM_SEC_DATA) {
323       assert(!dataSection);
324       dataSection = &section;
325     } else if (section.Type == WASM_SEC_CUSTOM) {
326       customSections.emplace_back(make<InputSection>(section, this));
327       customSections.back()->setRelocations(section.Relocations);
328       customSectionsByIndex[sectionIndex] = customSections.back();
329     }
330     sectionIndex++;
331     // Scans relocations to determine if a function symbol is called directly.
332     for (const WasmRelocation &reloc : section.Relocations)
333       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
334         isCalledDirectly[reloc.Index] = true;
335   }
336 
337   typeMap.resize(getWasmObj()->types().size());
338   typeIsUsed.resize(getWasmObj()->types().size(), false);
339 
340   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
341   for (StringRef comdat : comdats) {
342     bool isNew = ignoreComdats || symtab->addComdat(comdat);
343     keptComdats.push_back(isNew);
344   }
345 
346   // Populate `Segments`.
347   for (const WasmSegment &s : wasmObj->dataSegments()) {
348     auto* seg = make<InputSegment>(s, this);
349     seg->discarded = isExcludedByComdat(seg);
350     segments.emplace_back(seg);
351   }
352   setRelocs(segments, dataSection);
353 
354   // Populate `Functions`.
355   ArrayRef<WasmFunction> funcs = wasmObj->functions();
356   ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
357   ArrayRef<WasmSignature> types = wasmObj->types();
358   functions.reserve(funcs.size());
359 
360   for (size_t i = 0, e = funcs.size(); i != e; ++i) {
361     auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
362     func->discarded = isExcludedByComdat(func);
363     functions.emplace_back(func);
364   }
365   setRelocs(functions, codeSection);
366 
367   // Populate `Globals`.
368   for (const WasmGlobal &g : wasmObj->globals())
369     globals.emplace_back(make<InputGlobal>(g, this));
370 
371   // Populate `Events`.
372   for (const WasmEvent &e : wasmObj->events())
373     events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this));
374 
375   // Populate `Symbols` based on the symbols in the object.
376   symbols.reserve(wasmObj->getNumberOfSymbols());
377   for (const SymbolRef &sym : wasmObj->symbols()) {
378     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
379     if (wasmSym.isDefined()) {
380       // createDefined may fail if the symbol is comdat excluded in which case
381       // we fall back to creating an undefined symbol
382       if (Symbol *d = createDefined(wasmSym)) {
383         symbols.push_back(d);
384         continue;
385       }
386     }
387     size_t idx = symbols.size();
388     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
389   }
390 }
391 
392 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
393   uint32_t c = chunk->getComdat();
394   if (c == UINT32_MAX)
395     return false;
396   return !keptComdats[c];
397 }
398 
399 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
400   return cast<FunctionSymbol>(symbols[index]);
401 }
402 
403 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
404   return cast<GlobalSymbol>(symbols[index]);
405 }
406 
407 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const {
408   return cast<EventSymbol>(symbols[index]);
409 }
410 
411 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
412   return cast<SectionSymbol>(symbols[index]);
413 }
414 
415 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
416   return cast<DataSymbol>(symbols[index]);
417 }
418 
419 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
420   StringRef name = sym.Info.Name;
421   uint32_t flags = sym.Info.Flags;
422 
423   switch (sym.Info.Kind) {
424   case WASM_SYMBOL_TYPE_FUNCTION: {
425     InputFunction *func =
426         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
427     if (sym.isBindingLocal())
428       return make<DefinedFunction>(name, flags, this, func);
429     if (func->discarded)
430       return nullptr;
431     return symtab->addDefinedFunction(name, flags, this, func);
432   }
433   case WASM_SYMBOL_TYPE_DATA: {
434     InputSegment *seg = segments[sym.Info.DataRef.Segment];
435     auto offset = sym.Info.DataRef.Offset;
436     auto size = sym.Info.DataRef.Size;
437     if (sym.isBindingLocal())
438       return make<DefinedData>(name, flags, this, seg, offset, size);
439     if (seg->discarded)
440       return nullptr;
441     return symtab->addDefinedData(name, flags, this, seg, offset, size);
442   }
443   case WASM_SYMBOL_TYPE_GLOBAL: {
444     InputGlobal *global =
445         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
446     if (sym.isBindingLocal())
447       return make<DefinedGlobal>(name, flags, this, global);
448     return symtab->addDefinedGlobal(name, flags, this, global);
449   }
450   case WASM_SYMBOL_TYPE_SECTION: {
451     InputSection *section = customSectionsByIndex[sym.Info.ElementIndex];
452     assert(sym.isBindingLocal());
453     return make<SectionSymbol>(flags, section, this);
454   }
455   case WASM_SYMBOL_TYPE_EVENT: {
456     InputEvent *event =
457         events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()];
458     if (sym.isBindingLocal())
459       return make<DefinedEvent>(name, flags, this, event);
460     return symtab->addDefinedEvent(name, flags, this, event);
461   }
462   }
463   llvm_unreachable("unknown symbol kind");
464 }
465 
466 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
467   StringRef name = sym.Info.Name;
468   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
469 
470   switch (sym.Info.Kind) {
471   case WASM_SYMBOL_TYPE_FUNCTION:
472     if (sym.isBindingLocal())
473       return make<UndefinedFunction>(name, sym.Info.ImportName,
474                                      sym.Info.ImportModule, flags, this,
475                                      sym.Signature, isCalledDirectly);
476     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
477                                         sym.Info.ImportModule, flags, this,
478                                         sym.Signature, isCalledDirectly);
479   case WASM_SYMBOL_TYPE_DATA:
480     if (sym.isBindingLocal())
481       return make<UndefinedData>(name, flags, this);
482     return symtab->addUndefinedData(name, flags, this);
483   case WASM_SYMBOL_TYPE_GLOBAL:
484     if (sym.isBindingLocal())
485       return make<UndefinedGlobal>(name, sym.Info.ImportName,
486                                    sym.Info.ImportModule, flags, this,
487                                    sym.GlobalType);
488     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
489                                       sym.Info.ImportModule, flags, this,
490                                       sym.GlobalType);
491   case WASM_SYMBOL_TYPE_SECTION:
492     llvm_unreachable("section symbols cannot be undefined");
493   }
494   llvm_unreachable("unknown symbol kind");
495 }
496 
497 void ArchiveFile::parse() {
498   // Parse a MemoryBufferRef as an archive file.
499   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
500   file = CHECK(Archive::create(mb), toString(this));
501 
502   // Read the symbol table to construct Lazy symbols.
503   int count = 0;
504   for (const Archive::Symbol &sym : file->symbols()) {
505     symtab->addLazy(this, &sym);
506     ++count;
507   }
508   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
509 }
510 
511 void ArchiveFile::addMember(const Archive::Symbol *sym) {
512   const Archive::Child &c =
513       CHECK(sym->getMember(),
514             "could not get the member for symbol " + sym->getName());
515 
516   // Don't try to load the same member twice (this can happen when members
517   // mutually reference each other).
518   if (!seen.insert(c.getChildOffset()).second)
519     return;
520 
521   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
522   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
523 
524   MemoryBufferRef mb =
525       CHECK(c.getMemoryBufferRef(),
526             "could not get the buffer for the member defining symbol " +
527                 sym->getName());
528 
529   InputFile *obj = createObjectFile(mb, getName());
530   symtab->addFile(obj);
531 }
532 
533 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
534   switch (gvVisibility) {
535   case GlobalValue::DefaultVisibility:
536     return WASM_SYMBOL_VISIBILITY_DEFAULT;
537   case GlobalValue::HiddenVisibility:
538   case GlobalValue::ProtectedVisibility:
539     return WASM_SYMBOL_VISIBILITY_HIDDEN;
540   }
541   llvm_unreachable("unknown visibility");
542 }
543 
544 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
545                                    const lto::InputFile::Symbol &objSym,
546                                    BitcodeFile &f) {
547   StringRef name = saver.save(objSym.getName());
548 
549   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
550   flags |= mapVisibility(objSym.getVisibility());
551 
552   int c = objSym.getComdatIndex();
553   bool excludedByComdat = c != -1 && !keptComdats[c];
554 
555   if (objSym.isUndefined() || excludedByComdat) {
556     flags |= WASM_SYMBOL_UNDEFINED;
557     if (objSym.isExecutable())
558       return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
559                                           true);
560     return symtab->addUndefinedData(name, flags, &f);
561   }
562 
563   if (objSym.isExecutable())
564     return symtab->addDefinedFunction(name, flags, &f, nullptr);
565   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
566 }
567 
568 bool BitcodeFile::doneLTO = false;
569 
570 void BitcodeFile::parse() {
571   if (doneLTO) {
572     error(toString(this) + ": attempt to add bitcode file after LTO.");
573     return;
574   }
575 
576   obj = check(lto::InputFile::create(MemoryBufferRef(
577       mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
578   Triple t(obj->getTargetTriple());
579   if (t.getArch() != Triple::wasm32) {
580     error(toString(this) + ": machine type must be wasm32");
581     return;
582   }
583   std::vector<bool> keptComdats;
584   for (StringRef s : obj->getComdatTable())
585     keptComdats.push_back(symtab->addComdat(s));
586 
587   for (const lto::InputFile::Symbol &objSym : obj->symbols())
588     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
589 }
590 
591 } // namespace wasm
592 } // namespace lld
593