xref: /freebsd/contrib/llvm-project/lld/ELF/Driver.cpp (revision 74626c16ff489c0d64cf2843dfd522e7c544f3ce)
10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // The driver drives the entire linking process. It is responsible for
100b57cec5SDimitry Andric // parsing command line options and doing whatever it is instructed to do.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // One notable thing in the LLD's driver when compared to other linkers is
130b57cec5SDimitry Andric // that the LLD's driver is agnostic on the host operating system.
140b57cec5SDimitry Andric // Other linkers usually have implicit default values (such as a dynamic
150b57cec5SDimitry Andric // linker path or library paths) for each host OS.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric // I don't think implicit default values are useful because they are
18bdd1243dSDimitry Andric // usually explicitly specified by the compiler ctx.driver. They can even
190b57cec5SDimitry Andric // be harmful when you are doing cross-linking. Therefore, in LLD, we
200b57cec5SDimitry Andric // simply trust the compiler driver to pass all required options and
210b57cec5SDimitry Andric // don't try to make effort on our side.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric #include "Driver.h"
260b57cec5SDimitry Andric #include "Config.h"
270b57cec5SDimitry Andric #include "ICF.h"
280b57cec5SDimitry Andric #include "InputFiles.h"
290b57cec5SDimitry Andric #include "InputSection.h"
30bdd1243dSDimitry Andric #include "LTO.h"
310b57cec5SDimitry Andric #include "LinkerScript.h"
320b57cec5SDimitry Andric #include "MarkLive.h"
330b57cec5SDimitry Andric #include "OutputSections.h"
340b57cec5SDimitry Andric #include "ScriptParser.h"
350b57cec5SDimitry Andric #include "SymbolTable.h"
360b57cec5SDimitry Andric #include "Symbols.h"
370b57cec5SDimitry Andric #include "SyntheticSections.h"
380b57cec5SDimitry Andric #include "Target.h"
390b57cec5SDimitry Andric #include "Writer.h"
400b57cec5SDimitry Andric #include "lld/Common/Args.h"
41bdd1243dSDimitry Andric #include "lld/Common/CommonLinkerContext.h"
420b57cec5SDimitry Andric #include "lld/Common/Driver.h"
430b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
440b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
450b57cec5SDimitry Andric #include "lld/Common/Memory.h"
460b57cec5SDimitry Andric #include "lld/Common/Strings.h"
470b57cec5SDimitry Andric #include "lld/Common/TargetOptionsCommandFlags.h"
480b57cec5SDimitry Andric #include "lld/Common/Version.h"
490b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
500b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
510b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
52e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
5385868e8aSDimitry Andric #include "llvm/LTO/LTO.h"
5481ad6265SDimitry Andric #include "llvm/Object/Archive.h"
555f757f3fSDimitry Andric #include "llvm/Object/IRObjectFile.h"
56e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
570b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
580b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
5981ad6265SDimitry Andric #include "llvm/Support/FileSystem.h"
600b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h"
610b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
625ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
630b57cec5SDimitry Andric #include "llvm/Support/Path.h"
640b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
650b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
665ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h"
670b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
680b57cec5SDimitry Andric #include <cstdlib>
6906c3fb27SDimitry Andric #include <tuple>
700b57cec5SDimitry Andric #include <utility>
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric using namespace llvm;
730b57cec5SDimitry Andric using namespace llvm::ELF;
740b57cec5SDimitry Andric using namespace llvm::object;
750b57cec5SDimitry Andric using namespace llvm::sys;
760b57cec5SDimitry Andric using namespace llvm::support;
775ffd83dbSDimitry Andric using namespace lld;
785ffd83dbSDimitry Andric using namespace lld::elf;
790b57cec5SDimitry Andric 
80bdd1243dSDimitry Andric ConfigWrapper elf::config;
81bdd1243dSDimitry Andric Ctx elf::ctx;
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args);
840b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args);
850b57cec5SDimitry Andric 
861fd87a68SDimitry Andric void elf::errorOrWarn(const Twine &msg) {
871fd87a68SDimitry Andric   if (config->noinhibitExec)
881fd87a68SDimitry Andric     warn(msg);
891fd87a68SDimitry Andric   else
901fd87a68SDimitry Andric     error(msg);
911fd87a68SDimitry Andric }
921fd87a68SDimitry Andric 
93bdd1243dSDimitry Andric void Ctx::reset() {
94bdd1243dSDimitry Andric   driver = LinkerDriver();
95bdd1243dSDimitry Andric   memoryBuffers.clear();
96bdd1243dSDimitry Andric   objectFiles.clear();
97bdd1243dSDimitry Andric   sharedFiles.clear();
98bdd1243dSDimitry Andric   binaryFiles.clear();
99bdd1243dSDimitry Andric   bitcodeFiles.clear();
100bdd1243dSDimitry Andric   lazyBitcodeFiles.clear();
101bdd1243dSDimitry Andric   inputSections.clear();
102bdd1243dSDimitry Andric   ehInputSections.clear();
103bdd1243dSDimitry Andric   duplicates.clear();
104bdd1243dSDimitry Andric   nonPrevailingSyms.clear();
105bdd1243dSDimitry Andric   whyExtractRecords.clear();
106bdd1243dSDimitry Andric   backwardReferences.clear();
1075f757f3fSDimitry Andric   auxiliaryFiles.clear();
1087a6dacacSDimitry Andric   internalFile = nullptr;
109bdd1243dSDimitry Andric   hasSympart.store(false, std::memory_order_relaxed);
1105f757f3fSDimitry Andric   hasTlsIe.store(false, std::memory_order_relaxed);
111bdd1243dSDimitry Andric   needsTlsLd.store(false, std::memory_order_relaxed);
1125f757f3fSDimitry Andric   scriptSymOrderCounter = 1;
1135f757f3fSDimitry Andric   scriptSymOrder.clear();
1145f757f3fSDimitry Andric   ltoAllVtablesHaveTypeInfos = false;
115bdd1243dSDimitry Andric }
116bdd1243dSDimitry Andric 
11706c3fb27SDimitry Andric llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,
11806c3fb27SDimitry Andric                                             std::error_code &ec) {
11906c3fb27SDimitry Andric   using namespace llvm::sys::fs;
12006c3fb27SDimitry Andric   OpenFlags flags =
12106c3fb27SDimitry Andric       auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;
12206c3fb27SDimitry Andric   return {filename, ec, flags};
12306c3fb27SDimitry Andric }
12406c3fb27SDimitry Andric 
12506c3fb27SDimitry Andric namespace lld {
12606c3fb27SDimitry Andric namespace elf {
12706c3fb27SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
12806c3fb27SDimitry Andric           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
12906c3fb27SDimitry Andric   // This driver-specific context will be freed later by unsafeLldMain().
13004eeddc0SDimitry Andric   auto *ctx = new CommonLinkerContext;
131480093f4SDimitry Andric 
13204eeddc0SDimitry Andric   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
13304eeddc0SDimitry Andric   ctx->e.cleanupCallback = []() {
134bdd1243dSDimitry Andric     elf::ctx.reset();
135bdd1243dSDimitry Andric     symtab = SymbolTable();
136bdd1243dSDimitry Andric 
1370b57cec5SDimitry Andric     outputSections.clear();
13804eeddc0SDimitry Andric     symAux.clear();
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     tar = nullptr;
14104eeddc0SDimitry Andric     in.reset();
1420b57cec5SDimitry Andric 
14304eeddc0SDimitry Andric     partitions.clear();
14404eeddc0SDimitry Andric     partitions.emplace_back();
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     SharedFile::vernauxNum = 0;
147e8d8bef9SDimitry Andric   };
14804eeddc0SDimitry Andric   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
14904eeddc0SDimitry Andric   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
15081ad6265SDimitry Andric                                  "--error-limit=0 to see all errors)";
151e8d8bef9SDimitry Andric 
152bdd1243dSDimitry Andric   config = ConfigWrapper();
1530eae32dcSDimitry Andric   script = std::make_unique<LinkerScript>();
154bdd1243dSDimitry Andric 
155bdd1243dSDimitry Andric   symAux.emplace_back();
156e8d8bef9SDimitry Andric 
15704eeddc0SDimitry Andric   partitions.clear();
15804eeddc0SDimitry Andric   partitions.emplace_back();
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   config->progName = args[0];
1610b57cec5SDimitry Andric 
162bdd1243dSDimitry Andric   elf::ctx.driver.linkerMain(args);
1630b57cec5SDimitry Andric 
16404eeddc0SDimitry Andric   return errorCount() == 0;
1650b57cec5SDimitry Andric }
16606c3fb27SDimitry Andric } // namespace elf
16706c3fb27SDimitry Andric } // namespace lld
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric // Parses a linker -m option.
1700b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
1710b57cec5SDimitry Andric   uint8_t osabi = 0;
1720b57cec5SDimitry Andric   StringRef s = emul;
17306c3fb27SDimitry Andric   if (s.ends_with("_fbsd")) {
1740b57cec5SDimitry Andric     s = s.drop_back(5);
1750b57cec5SDimitry Andric     osabi = ELFOSABI_FREEBSD;
1760b57cec5SDimitry Andric   }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   std::pair<ELFKind, uint16_t> ret =
1790b57cec5SDimitry Andric       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
180fe6060f1SDimitry Andric           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
181fe6060f1SDimitry Andric           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
1820b57cec5SDimitry Andric           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
18306c3fb27SDimitry Andric           .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM})
1840b57cec5SDimitry Andric           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
1850b57cec5SDimitry Andric           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
1860b57cec5SDimitry Andric           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
1870b57cec5SDimitry Andric           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
1880b57cec5SDimitry Andric           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
189e8d8bef9SDimitry Andric           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
19006c3fb27SDimitry Andric           .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH})
1910b57cec5SDimitry Andric           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
1920b57cec5SDimitry Andric           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
1930b57cec5SDimitry Andric           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
1940b57cec5SDimitry Andric           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
1950b57cec5SDimitry Andric           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
1960b57cec5SDimitry Andric           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
1970b57cec5SDimitry Andric           .Case("elf_i386", {ELF32LEKind, EM_386})
1980b57cec5SDimitry Andric           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
1995ffd83dbSDimitry Andric           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
200e8d8bef9SDimitry Andric           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
201bdd1243dSDimitry Andric           .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})
20206c3fb27SDimitry Andric           .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH})
203*74626c16SDimitry Andric           .Case("elf64_s390", {ELF64BEKind, EM_S390})
2040b57cec5SDimitry Andric           .Default({ELFNoneKind, EM_NONE});
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   if (ret.first == ELFNoneKind)
2070b57cec5SDimitry Andric     error("unknown emulation: " + emul);
208e8d8bef9SDimitry Andric   if (ret.second == EM_MSP430)
209e8d8bef9SDimitry Andric     osabi = ELFOSABI_STANDALONE;
210bdd1243dSDimitry Andric   else if (ret.second == EM_AMDGPU)
211bdd1243dSDimitry Andric     osabi = ELFOSABI_AMDGPU_HSA;
2120b57cec5SDimitry Andric   return std::make_tuple(ret.first, ret.second, osabi);
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file.
2160b57cec5SDimitry Andric // Each slice consists of a member file in the archive.
2170b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
2180b57cec5SDimitry Andric     MemoryBufferRef mb) {
2190b57cec5SDimitry Andric   std::unique_ptr<Archive> file =
2200b57cec5SDimitry Andric       CHECK(Archive::create(mb),
2210b57cec5SDimitry Andric             mb.getBufferIdentifier() + ": failed to parse archive");
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
2240b57cec5SDimitry Andric   Error err = Error::success();
2250b57cec5SDimitry Andric   bool addToTar = file->isThin() && tar;
226480093f4SDimitry Andric   for (const Archive::Child &c : file->children(err)) {
2270b57cec5SDimitry Andric     MemoryBufferRef mbref =
2280b57cec5SDimitry Andric         CHECK(c.getMemoryBufferRef(),
2290b57cec5SDimitry Andric               mb.getBufferIdentifier() +
2300b57cec5SDimitry Andric                   ": could not get the buffer for a child of the archive");
2310b57cec5SDimitry Andric     if (addToTar)
2320b57cec5SDimitry Andric       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
2330b57cec5SDimitry Andric     v.push_back(std::make_pair(mbref, c.getChildOffset()));
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric   if (err)
2360b57cec5SDimitry Andric     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
2370b57cec5SDimitry Andric           toString(std::move(err)));
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   // Take ownership of memory buffers created for members of thin archives.
2401fd87a68SDimitry Andric   std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
241bdd1243dSDimitry Andric   std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   return v;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
246fcaf7f86SDimitry Andric static bool isBitcode(MemoryBufferRef mb) {
247fcaf7f86SDimitry Andric   return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
248fcaf7f86SDimitry Andric }
249fcaf7f86SDimitry Andric 
2505f757f3fSDimitry Andric bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,
2515f757f3fSDimitry Andric                                     uint64_t offsetInArchive, bool lazy) {
2525f757f3fSDimitry Andric   if (!config->fatLTOObjects)
2535f757f3fSDimitry Andric     return false;
2545f757f3fSDimitry Andric   Expected<MemoryBufferRef> fatLTOData =
2555f757f3fSDimitry Andric       IRObjectFile::findBitcodeInMemBuffer(mb);
2565f757f3fSDimitry Andric   if (errorToBool(fatLTOData.takeError()))
2575f757f3fSDimitry Andric     return false;
2585f757f3fSDimitry Andric   files.push_back(
2595f757f3fSDimitry Andric       make<BitcodeFile>(*fatLTOData, archiveName, offsetInArchive, lazy));
2605f757f3fSDimitry Andric   return true;
2615f757f3fSDimitry Andric }
2625f757f3fSDimitry Andric 
2630b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already.
2640b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) {
2650b57cec5SDimitry Andric   using namespace sys::fs;
2660b57cec5SDimitry Andric 
267bdd1243dSDimitry Andric   std::optional<MemoryBufferRef> buffer = readFile(path);
26881ad6265SDimitry Andric   if (!buffer)
2690b57cec5SDimitry Andric     return;
2700b57cec5SDimitry Andric   MemoryBufferRef mbref = *buffer;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   if (config->formatBinary) {
2730b57cec5SDimitry Andric     files.push_back(make<BinaryFile>(mbref));
2740b57cec5SDimitry Andric     return;
2750b57cec5SDimitry Andric   }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
2780b57cec5SDimitry Andric   case file_magic::unknown:
2790b57cec5SDimitry Andric     readLinkerScript(mbref);
2800b57cec5SDimitry Andric     return;
2810b57cec5SDimitry Andric   case file_magic::archive: {
282bdd1243dSDimitry Andric     auto members = getArchiveMembers(mbref);
2830b57cec5SDimitry Andric     if (inWholeArchive) {
284bdd1243dSDimitry Andric       for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
285fcaf7f86SDimitry Andric         if (isBitcode(p.first))
286fcaf7f86SDimitry Andric           files.push_back(make<BitcodeFile>(p.first, path, p.second, false));
2875f757f3fSDimitry Andric         else if (!tryAddFatLTOFile(p.first, path, p.second, false))
288fcaf7f86SDimitry Andric           files.push_back(createObjFile(p.first, path));
289fcaf7f86SDimitry Andric       }
2900b57cec5SDimitry Andric       return;
2910b57cec5SDimitry Andric     }
2920b57cec5SDimitry Andric 
29381ad6265SDimitry Andric     archiveFiles.emplace_back(path, members.size());
2940b57cec5SDimitry Andric 
29581ad6265SDimitry Andric     // Handle archives and --start-lib/--end-lib using the same code path. This
29681ad6265SDimitry Andric     // scans all the ELF relocatable object files and bitcode files in the
29781ad6265SDimitry Andric     // archive rather than just the index file, with the benefit that the
29881ad6265SDimitry Andric     // symbols are only loaded once. For many projects archives see high
29981ad6265SDimitry Andric     // utilization rates and it is a net performance win. --start-lib scans
30081ad6265SDimitry Andric     // symbols in the same order that llvm-ar adds them to the index, so in the
30181ad6265SDimitry Andric     // common case the semantics are identical. If the archive symbol table was
30281ad6265SDimitry Andric     // created in a different order, or is incomplete, this strategy has
30381ad6265SDimitry Andric     // different semantics. Such output differences are considered user error.
30481ad6265SDimitry Andric     //
305d56accc7SDimitry Andric     // All files within the archive get the same group ID to allow mutual
306d56accc7SDimitry Andric     // references for --warn-backrefs.
307d56accc7SDimitry Andric     bool saved = InputFile::isInGroup;
308d56accc7SDimitry Andric     InputFile::isInGroup = true;
30981ad6265SDimitry Andric     for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
31004eeddc0SDimitry Andric       auto magic = identify_magic(p.first.getBuffer());
3115f757f3fSDimitry Andric       if (magic == file_magic::elf_relocatable) {
3125f757f3fSDimitry Andric         if (!tryAddFatLTOFile(p.first, path, p.second, true))
313fcaf7f86SDimitry Andric           files.push_back(createObjFile(p.first, path, true));
3145f757f3fSDimitry Andric       } else if (magic == file_magic::bitcode)
315fcaf7f86SDimitry Andric         files.push_back(make<BitcodeFile>(p.first, path, p.second, true));
31604eeddc0SDimitry Andric       else
31781ad6265SDimitry Andric         warn(path + ": archive member '" + p.first.getBufferIdentifier() +
31804eeddc0SDimitry Andric              "' is neither ET_REL nor LLVM bitcode");
31904eeddc0SDimitry Andric     }
320d56accc7SDimitry Andric     InputFile::isInGroup = saved;
321d56accc7SDimitry Andric     if (!saved)
322d56accc7SDimitry Andric       ++InputFile::nextGroupId;
3230b57cec5SDimitry Andric     return;
3240b57cec5SDimitry Andric   }
325bdd1243dSDimitry Andric   case file_magic::elf_shared_object: {
3260b57cec5SDimitry Andric     if (config->isStatic || config->relocatable) {
3270b57cec5SDimitry Andric       error("attempted static link of dynamic object " + path);
3280b57cec5SDimitry Andric       return;
3290b57cec5SDimitry Andric     }
3300b57cec5SDimitry Andric 
331349cc55cSDimitry Andric     // Shared objects are identified by soname. soname is (if specified)
332349cc55cSDimitry Andric     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
333349cc55cSDimitry Andric     // the directory part is ignored. Note that path may be a temporary and
334349cc55cSDimitry Andric     // cannot be stored into SharedFile::soName.
335349cc55cSDimitry Andric     path = mbref.getBufferIdentifier();
336bdd1243dSDimitry Andric     auto *f =
337bdd1243dSDimitry Andric         make<SharedFile>(mbref, withLOption ? path::filename(path) : path);
338bdd1243dSDimitry Andric     f->init();
339bdd1243dSDimitry Andric     files.push_back(f);
3400b57cec5SDimitry Andric     return;
341bdd1243dSDimitry Andric   }
3420b57cec5SDimitry Andric   case file_magic::bitcode:
343fcaf7f86SDimitry Andric     files.push_back(make<BitcodeFile>(mbref, "", 0, inLib));
344fcaf7f86SDimitry Andric     break;
3450b57cec5SDimitry Andric   case file_magic::elf_relocatable:
3465f757f3fSDimitry Andric     if (!tryAddFatLTOFile(mbref, "", 0, inLib))
347fcaf7f86SDimitry Andric       files.push_back(createObjFile(mbref, "", inLib));
3480b57cec5SDimitry Andric     break;
3490b57cec5SDimitry Andric   default:
3500b57cec5SDimitry Andric     error(path + ": unknown file type");
3510b57cec5SDimitry Andric   }
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric // Add a given library by searching it from input search paths.
3550b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) {
356bdd1243dSDimitry Andric   if (std::optional<std::string> path = searchLibrary(name))
357972a253aSDimitry Andric     addFile(saver().save(*path), /*withLOption=*/true);
3580b57cec5SDimitry Andric   else
359e8d8bef9SDimitry Andric     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since
3630b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code.
3640b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but
3650b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast.
3660b57cec5SDimitry Andric static void initLLVM() {
3670b57cec5SDimitry Andric   InitializeAllTargets();
3680b57cec5SDimitry Andric   InitializeAllTargetMCs();
3690b57cec5SDimitry Andric   InitializeAllAsmPrinters();
3700b57cec5SDimitry Andric   InitializeAllAsmParsers();
3710b57cec5SDimitry Andric }
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed.
3740b57cec5SDimitry Andric // This function checks for such errors.
3750b57cec5SDimitry Andric static void checkOptions() {
3760b57cec5SDimitry Andric   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
3770b57cec5SDimitry Andric   // table which is a relatively new feature.
3780b57cec5SDimitry Andric   if (config->emachine == EM_MIPS && config->gnuHash)
3790b57cec5SDimitry Andric     error("the .gnu.hash section is not compatible with the MIPS target");
3800b57cec5SDimitry Andric 
38106c3fb27SDimitry Andric   if (config->emachine == EM_ARM) {
38206c3fb27SDimitry Andric     if (!config->cmseImplib) {
38306c3fb27SDimitry Andric       if (!config->cmseInputLib.empty())
38406c3fb27SDimitry Andric         error("--in-implib may not be used without --cmse-implib");
38506c3fb27SDimitry Andric       if (!config->cmseOutputLib.empty())
38606c3fb27SDimitry Andric         error("--out-implib may not be used without --cmse-implib");
38706c3fb27SDimitry Andric     }
38806c3fb27SDimitry Andric   } else {
38906c3fb27SDimitry Andric     if (config->cmseImplib)
39006c3fb27SDimitry Andric       error("--cmse-implib is only supported on ARM targets");
39106c3fb27SDimitry Andric     if (!config->cmseInputLib.empty())
39206c3fb27SDimitry Andric       error("--in-implib is only supported on ARM targets");
39306c3fb27SDimitry Andric     if (!config->cmseOutputLib.empty())
39406c3fb27SDimitry Andric       error("--out-implib is only supported on ARM targets");
39506c3fb27SDimitry Andric   }
39606c3fb27SDimitry Andric 
3970b57cec5SDimitry Andric   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
3980b57cec5SDimitry Andric     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
3990b57cec5SDimitry Andric 
40085868e8aSDimitry Andric   if (config->fixCortexA8 && config->emachine != EM_ARM)
40185868e8aSDimitry Andric     error("--fix-cortex-a8 is only supported on ARM targets");
40285868e8aSDimitry Andric 
40306c3fb27SDimitry Andric   if (config->armBe8 && config->emachine != EM_ARM)
40406c3fb27SDimitry Andric     error("--be8 is only supported on ARM targets");
40506c3fb27SDimitry Andric 
40606c3fb27SDimitry Andric   if (config->fixCortexA8 && !config->isLE)
40706c3fb27SDimitry Andric     error("--fix-cortex-a8 is not supported on big endian targets");
40806c3fb27SDimitry Andric 
4090b57cec5SDimitry Andric   if (config->tocOptimize && config->emachine != EM_PPC64)
410e8d8bef9SDimitry Andric     error("--toc-optimize is only supported on PowerPC64 targets");
411e8d8bef9SDimitry Andric 
412e8d8bef9SDimitry Andric   if (config->pcRelOptimize && config->emachine != EM_PPC64)
413e8d8bef9SDimitry Andric     error("--pcrel-optimize is only supported on PowerPC64 targets");
4140b57cec5SDimitry Andric 
41506c3fb27SDimitry Andric   if (config->relaxGP && config->emachine != EM_RISCV)
41606c3fb27SDimitry Andric     error("--relax-gp is only supported on RISC-V targets");
41706c3fb27SDimitry Andric 
4180b57cec5SDimitry Andric   if (config->pie && config->shared)
4190b57cec5SDimitry Andric     error("-shared and -pie may not be used together");
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   if (!config->shared && !config->filterList.empty())
4220b57cec5SDimitry Andric     error("-F may not be used without -shared");
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   if (!config->shared && !config->auxiliaryList.empty())
4250b57cec5SDimitry Andric     error("-f may not be used without -shared");
4260b57cec5SDimitry Andric 
42785868e8aSDimitry Andric   if (config->strip == StripPolicy::All && config->emitRelocs)
42885868e8aSDimitry Andric     error("--strip-all and --emit-relocs may not be used together");
42985868e8aSDimitry Andric 
4300b57cec5SDimitry Andric   if (config->zText && config->zIfuncNoplt)
4310b57cec5SDimitry Andric     error("-z text and -z ifunc-noplt may not be used together");
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   if (config->relocatable) {
4340b57cec5SDimitry Andric     if (config->shared)
4350b57cec5SDimitry Andric       error("-r and -shared may not be used together");
4360b57cec5SDimitry Andric     if (config->gdbIndex)
4370b57cec5SDimitry Andric       error("-r and --gdb-index may not be used together");
4380b57cec5SDimitry Andric     if (config->icf != ICFLevel::None)
4390b57cec5SDimitry Andric       error("-r and --icf may not be used together");
4400b57cec5SDimitry Andric     if (config->pie)
4410b57cec5SDimitry Andric       error("-r and -pie may not be used together");
44285868e8aSDimitry Andric     if (config->exportDynamic)
44385868e8aSDimitry Andric       error("-r and --export-dynamic may not be used together");
4440b57cec5SDimitry Andric   }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   if (config->executeOnly) {
4470b57cec5SDimitry Andric     if (config->emachine != EM_AARCH64)
448349cc55cSDimitry Andric       error("--execute-only is only supported on AArch64 targets");
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric     if (config->singleRoRx && !script->hasSectionsCommand)
451349cc55cSDimitry Andric       error("--execute-only and --no-rosegment cannot be used together");
4520b57cec5SDimitry Andric   }
4530b57cec5SDimitry Andric 
454480093f4SDimitry Andric   if (config->zRetpolineplt && config->zForceIbt)
455480093f4SDimitry Andric     error("-z force-ibt may not be used with -z retpolineplt");
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   if (config->emachine != EM_AARCH64) {
4585ffd83dbSDimitry Andric     if (config->zPacPlt)
459480093f4SDimitry Andric       error("-z pac-plt only supported on AArch64");
4605ffd83dbSDimitry Andric     if (config->zForceBti)
461480093f4SDimitry Andric       error("-z force-bti only supported on AArch64");
4620eae32dcSDimitry Andric     if (config->zBtiReport != "none")
4630eae32dcSDimitry Andric       error("-z bti-report only supported on AArch64");
4640b57cec5SDimitry Andric   }
4650eae32dcSDimitry Andric 
4660eae32dcSDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
4670eae32dcSDimitry Andric       config->zCetReport != "none")
4680eae32dcSDimitry Andric     error("-z cet-report only supported on X86 and X86_64");
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) {
4720b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
4730b57cec5SDimitry Andric     return arg->getValue();
4740b57cec5SDimitry Andric   return getenv("LLD_REPRODUCE");
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) {
4787a6dacacSDimitry Andric   bool ret = false;
4790b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
4807a6dacacSDimitry Andric     if (key == arg->getValue()) {
4817a6dacacSDimitry Andric       ret = true;
4827a6dacacSDimitry Andric       arg->claim();
4837a6dacacSDimitry Andric     }
4847a6dacacSDimitry Andric   return ret;
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
4887a6dacacSDimitry Andric                      bool defaultValue) {
4897a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
4907a6dacacSDimitry Andric     StringRef v = arg->getValue();
4917a6dacacSDimitry Andric     if (k1 == v)
4927a6dacacSDimitry Andric       defaultValue = true;
4937a6dacacSDimitry Andric     else if (k2 == v)
4947a6dacacSDimitry Andric       defaultValue = false;
4957a6dacacSDimitry Andric     else
4967a6dacacSDimitry Andric       continue;
4977a6dacacSDimitry Andric     arg->claim();
4980b57cec5SDimitry Andric   }
4997a6dacacSDimitry Andric   return defaultValue;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
50285868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
5037a6dacacSDimitry Andric   auto ret = SeparateSegmentKind::None;
5047a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
50585868e8aSDimitry Andric     StringRef v = arg->getValue();
50685868e8aSDimitry Andric     if (v == "noseparate-code")
5077a6dacacSDimitry Andric       ret = SeparateSegmentKind::None;
5087a6dacacSDimitry Andric     else if (v == "separate-code")
5097a6dacacSDimitry Andric       ret = SeparateSegmentKind::Code;
5107a6dacacSDimitry Andric     else if (v == "separate-loadable-segments")
5117a6dacacSDimitry Andric       ret = SeparateSegmentKind::Loadable;
5127a6dacacSDimitry Andric     else
5137a6dacacSDimitry Andric       continue;
5147a6dacacSDimitry Andric     arg->claim();
51585868e8aSDimitry Andric   }
5167a6dacacSDimitry Andric   return ret;
51785868e8aSDimitry Andric }
51885868e8aSDimitry Andric 
519480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) {
5207a6dacacSDimitry Andric   auto ret = GnuStackKind::NoExec;
5217a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5227a6dacacSDimitry Andric     StringRef v = arg->getValue();
5237a6dacacSDimitry Andric     if (v == "execstack")
5247a6dacacSDimitry Andric       ret = GnuStackKind::Exec;
5257a6dacacSDimitry Andric     else if (v == "noexecstack")
5267a6dacacSDimitry Andric       ret = GnuStackKind::NoExec;
5277a6dacacSDimitry Andric     else if (v == "nognustack")
5287a6dacacSDimitry Andric       ret = GnuStackKind::None;
5297a6dacacSDimitry Andric     else
5307a6dacacSDimitry Andric       continue;
5317a6dacacSDimitry Andric     arg->claim();
532480093f4SDimitry Andric   }
5337a6dacacSDimitry Andric   return ret;
534480093f4SDimitry Andric }
535480093f4SDimitry Andric 
5365ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
5377a6dacacSDimitry Andric   uint8_t ret = STV_PROTECTED;
5387a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5395ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
5405ffd83dbSDimitry Andric     if (kv.first == "start-stop-visibility") {
5417a6dacacSDimitry Andric       arg->claim();
5425ffd83dbSDimitry Andric       if (kv.second == "default")
5437a6dacacSDimitry Andric         ret = STV_DEFAULT;
5445ffd83dbSDimitry Andric       else if (kv.second == "internal")
5457a6dacacSDimitry Andric         ret = STV_INTERNAL;
5465ffd83dbSDimitry Andric       else if (kv.second == "hidden")
5477a6dacacSDimitry Andric         ret = STV_HIDDEN;
5485ffd83dbSDimitry Andric       else if (kv.second == "protected")
5497a6dacacSDimitry Andric         ret = STV_PROTECTED;
5507a6dacacSDimitry Andric       else
5517a6dacacSDimitry Andric         error("unknown -z start-stop-visibility= value: " +
5527a6dacacSDimitry Andric               StringRef(kv.second));
5535ffd83dbSDimitry Andric     }
5545ffd83dbSDimitry Andric   }
5557a6dacacSDimitry Andric   return ret;
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
5584824e7fdSDimitry Andric // Report a warning for an unknown -z option.
5590b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) {
5607a6dacacSDimitry Andric   // This function is called before getTarget(), when certain options are not
5617a6dacacSDimitry Andric   // initialized yet. Claim them here.
5627a6dacacSDimitry Andric   args::getZOptionValue(args, OPT_z, "max-page-size", 0);
5637a6dacacSDimitry Andric   args::getZOptionValue(args, OPT_z, "common-page-size", 0);
5647a6dacacSDimitry Andric   getZFlag(args, "rel", "rela", false);
5650b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
5667a6dacacSDimitry Andric     if (!arg->isClaimed())
5674824e7fdSDimitry Andric       warn("unknown -z value: " + StringRef(arg->getValue()));
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric 
570753f127fSDimitry Andric constexpr const char *saveTempsValues[] = {
571753f127fSDimitry Andric     "resolution", "preopt",     "promote", "internalize",  "import",
572753f127fSDimitry Andric     "opt",        "precodegen", "prelink", "combinedindex"};
573753f127fSDimitry Andric 
574e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
5750b57cec5SDimitry Andric   ELFOptTable parser;
5760b57cec5SDimitry Andric   opt::InputArgList args = parser.parse(argsArr.slice(1));
5770b57cec5SDimitry Andric 
57881ad6265SDimitry Andric   // Interpret these flags early because error()/warn() depend on them.
5790b57cec5SDimitry Andric   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
5804824e7fdSDimitry Andric   errorHandler().fatalWarnings =
581bdd1243dSDimitry Andric       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&
582bdd1243dSDimitry Andric       !args.hasArg(OPT_no_warnings);
583bdd1243dSDimitry Andric   errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   // Handle -help
5860b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
5870b57cec5SDimitry Andric     printHelp();
5880b57cec5SDimitry Andric     return;
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   // Handle -v or -version.
5920b57cec5SDimitry Andric   //
5930b57cec5SDimitry Andric   // A note about "compatible with GNU linkers" message: this is a hack for
594349cc55cSDimitry Andric   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
595349cc55cSDimitry Andric   // a GNU compatible linker. See
596349cc55cSDimitry Andric   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
5970b57cec5SDimitry Andric   //
5980b57cec5SDimitry Andric   // This is somewhat ugly hack, but in reality, we had no choice other
5990b57cec5SDimitry Andric   // than doing this. Considering the very long release cycle of Libtool,
6000b57cec5SDimitry Andric   // it is not easy to improve it to recognize LLD as a GNU compatible
6010b57cec5SDimitry Andric   // linker in a timely manner. Even if we can make it, there are still a
6020b57cec5SDimitry Andric   // lot of "configure" scripts out there that are generated by old version
6030b57cec5SDimitry Andric   // of Libtool. We cannot convince every software developer to migrate to
6040b57cec5SDimitry Andric   // the latest version and re-generate scripts. So we have this hack.
6050b57cec5SDimitry Andric   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
6060b57cec5SDimitry Andric     message(getLLDVersion() + " (compatible with GNU linkers)");
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   if (const char *path = getReproduceOption(args)) {
6090b57cec5SDimitry Andric     // Note that --reproduce is a debug option so you can ignore it
6100b57cec5SDimitry Andric     // if you are trying to understand the whole picture of the code.
6110b57cec5SDimitry Andric     Expected<std::unique_ptr<TarWriter>> errOrWriter =
6120b57cec5SDimitry Andric         TarWriter::create(path, path::stem(path));
6130b57cec5SDimitry Andric     if (errOrWriter) {
6140b57cec5SDimitry Andric       tar = std::move(*errOrWriter);
6150b57cec5SDimitry Andric       tar->append("response.txt", createResponseFile(args));
6160b57cec5SDimitry Andric       tar->append("version.txt", getLLDVersion() + "\n");
617e8d8bef9SDimitry Andric       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
618e8d8bef9SDimitry Andric       if (!ltoSampleProfile.empty())
619e8d8bef9SDimitry Andric         readFile(ltoSampleProfile);
6200b57cec5SDimitry Andric     } else {
6210b57cec5SDimitry Andric       error("--reproduce: " + toString(errOrWriter.takeError()));
6220b57cec5SDimitry Andric     }
6230b57cec5SDimitry Andric   }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   readConfigs(args);
6267a6dacacSDimitry Andric   checkZOptions(args);
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // The behavior of -v or --version is a bit strange, but this is
6290b57cec5SDimitry Andric   // needed for compatibility with GNU linkers.
6300b57cec5SDimitry Andric   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
6310b57cec5SDimitry Andric     return;
6320b57cec5SDimitry Andric   if (args.hasArg(OPT_version))
6330b57cec5SDimitry Andric     return;
6340b57cec5SDimitry Andric 
6355ffd83dbSDimitry Andric   // Initialize time trace profiler.
6365ffd83dbSDimitry Andric   if (config->timeTraceEnabled)
6375ffd83dbSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
6385ffd83dbSDimitry Andric 
6395ffd83dbSDimitry Andric   {
6405ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("ExecuteLinker");
6415ffd83dbSDimitry Andric 
6420b57cec5SDimitry Andric     initLLVM();
6430b57cec5SDimitry Andric     createFiles(args);
6440b57cec5SDimitry Andric     if (errorCount())
6450b57cec5SDimitry Andric       return;
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric     inferMachineType();
6480b57cec5SDimitry Andric     setConfigs(args);
6490b57cec5SDimitry Andric     checkOptions();
6500b57cec5SDimitry Andric     if (errorCount())
6510b57cec5SDimitry Andric       return;
6520b57cec5SDimitry Andric 
6531fd87a68SDimitry Andric     link(args);
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6565ffd83dbSDimitry Andric   if (config->timeTraceEnabled) {
657349cc55cSDimitry Andric     checkError(timeTraceProfilerWrite(
65881ad6265SDimitry Andric         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
6595ffd83dbSDimitry Andric     timeTraceProfilerCleanup();
6605ffd83dbSDimitry Andric   }
6615ffd83dbSDimitry Andric }
6625ffd83dbSDimitry Andric 
6630b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) {
664bdd1243dSDimitry Andric   SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);
6650b57cec5SDimitry Andric   return llvm::join(v.begin(), v.end(), ":");
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved
6690b57cec5SDimitry Andric // symbols after the name resolution.
670e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
6710b57cec5SDimitry Andric   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
6720b57cec5SDimitry Andric                                               OPT_warn_unresolved_symbols, true)
6730b57cec5SDimitry Andric                                      ? UnresolvedPolicy::ReportError
6740b57cec5SDimitry Andric                                      : UnresolvedPolicy::Warn;
675349cc55cSDimitry Andric   // -shared implies --unresolved-symbols=ignore-all because missing
676e8d8bef9SDimitry Andric   // symbols are likely to be resolved at runtime.
677e8d8bef9SDimitry Andric   bool diagRegular = !config->shared, diagShlib = !config->shared;
6780b57cec5SDimitry Andric 
679e8d8bef9SDimitry Andric   for (const opt::Arg *arg : args) {
6800b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
6810b57cec5SDimitry Andric     case OPT_unresolved_symbols: {
6820b57cec5SDimitry Andric       StringRef s = arg->getValue();
683e8d8bef9SDimitry Andric       if (s == "ignore-all") {
684e8d8bef9SDimitry Andric         diagRegular = false;
685e8d8bef9SDimitry Andric         diagShlib = false;
686e8d8bef9SDimitry Andric       } else if (s == "ignore-in-object-files") {
687e8d8bef9SDimitry Andric         diagRegular = false;
688e8d8bef9SDimitry Andric         diagShlib = true;
689e8d8bef9SDimitry Andric       } else if (s == "ignore-in-shared-libs") {
690e8d8bef9SDimitry Andric         diagRegular = true;
691e8d8bef9SDimitry Andric         diagShlib = false;
692e8d8bef9SDimitry Andric       } else if (s == "report-all") {
693e8d8bef9SDimitry Andric         diagRegular = true;
694e8d8bef9SDimitry Andric         diagShlib = true;
695e8d8bef9SDimitry Andric       } else {
6960b57cec5SDimitry Andric         error("unknown --unresolved-symbols value: " + s);
697e8d8bef9SDimitry Andric       }
698e8d8bef9SDimitry Andric       break;
6990b57cec5SDimitry Andric     }
7000b57cec5SDimitry Andric     case OPT_no_undefined:
701e8d8bef9SDimitry Andric       diagRegular = true;
702e8d8bef9SDimitry Andric       break;
7030b57cec5SDimitry Andric     case OPT_z:
7040b57cec5SDimitry Andric       if (StringRef(arg->getValue()) == "defs")
705e8d8bef9SDimitry Andric         diagRegular = true;
706e8d8bef9SDimitry Andric       else if (StringRef(arg->getValue()) == "undefs")
707e8d8bef9SDimitry Andric         diagRegular = false;
7087a6dacacSDimitry Andric       else
7097a6dacacSDimitry Andric         break;
7107a6dacacSDimitry Andric       arg->claim();
711e8d8bef9SDimitry Andric       break;
712e8d8bef9SDimitry Andric     case OPT_allow_shlib_undefined:
713e8d8bef9SDimitry Andric       diagShlib = false;
714e8d8bef9SDimitry Andric       break;
715e8d8bef9SDimitry Andric     case OPT_no_allow_shlib_undefined:
716e8d8bef9SDimitry Andric       diagShlib = true;
717e8d8bef9SDimitry Andric       break;
7180b57cec5SDimitry Andric     }
7190b57cec5SDimitry Andric   }
7200b57cec5SDimitry Andric 
721e8d8bef9SDimitry Andric   config->unresolvedSymbols =
722e8d8bef9SDimitry Andric       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
723e8d8bef9SDimitry Andric   config->unresolvedSymbolsInShlib =
724e8d8bef9SDimitry Andric       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
7250b57cec5SDimitry Andric }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) {
7280b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
7290b57cec5SDimitry Andric   if (s == "rel")
7300b57cec5SDimitry Andric     return Target2Policy::Rel;
7310b57cec5SDimitry Andric   if (s == "abs")
7320b57cec5SDimitry Andric     return Target2Policy::Abs;
7330b57cec5SDimitry Andric   if (s == "got-rel")
7340b57cec5SDimitry Andric     return Target2Policy::GotRel;
7350b57cec5SDimitry Andric   error("unknown --target2 option: " + s);
7360b57cec5SDimitry Andric   return Target2Policy::GotRel;
7370b57cec5SDimitry Andric }
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) {
7400b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
7410b57cec5SDimitry Andric   if (s == "binary")
7420b57cec5SDimitry Andric     return true;
74306c3fb27SDimitry Andric   if (!s.starts_with("elf"))
7440b57cec5SDimitry Andric     error("unknown --oformat value: " + s);
7450b57cec5SDimitry Andric   return false;
7460b57cec5SDimitry Andric }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) {
7490b57cec5SDimitry Andric   auto *arg =
7500b57cec5SDimitry Andric       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
7510b57cec5SDimitry Andric   if (!arg)
7520b57cec5SDimitry Andric     return DiscardPolicy::Default;
7530b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_all)
7540b57cec5SDimitry Andric     return DiscardPolicy::All;
7550b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_locals)
7560b57cec5SDimitry Andric     return DiscardPolicy::Locals;
7570b57cec5SDimitry Andric   return DiscardPolicy::None;
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) {
7610b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
76255e4f9d5SDimitry Andric   if (!arg)
7630b57cec5SDimitry Andric     return "";
76455e4f9d5SDimitry Andric   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
76555e4f9d5SDimitry Andric     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
76655e4f9d5SDimitry Andric     config->noDynamicLinker = true;
76755e4f9d5SDimitry Andric     return "";
76855e4f9d5SDimitry Andric   }
7690b57cec5SDimitry Andric   return arg->getValue();
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
77281ad6265SDimitry Andric static int getMemtagMode(opt::InputArgList &args) {
77381ad6265SDimitry Andric   StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);
77406c3fb27SDimitry Andric   if (memtagModeArg.empty()) {
77506c3fb27SDimitry Andric     if (config->androidMemtagStack)
77606c3fb27SDimitry Andric       warn("--android-memtag-mode is unspecified, leaving "
77706c3fb27SDimitry Andric            "--android-memtag-stack a no-op");
77806c3fb27SDimitry Andric     else if (config->androidMemtagHeap)
77906c3fb27SDimitry Andric       warn("--android-memtag-mode is unspecified, leaving "
78006c3fb27SDimitry Andric            "--android-memtag-heap a no-op");
78106c3fb27SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_NONE;
78206c3fb27SDimitry Andric   }
78306c3fb27SDimitry Andric 
78406c3fb27SDimitry Andric   if (memtagModeArg == "sync")
78581ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_SYNC;
78681ad6265SDimitry Andric   if (memtagModeArg == "async")
78781ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_ASYNC;
78881ad6265SDimitry Andric   if (memtagModeArg == "none")
78981ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_NONE;
79081ad6265SDimitry Andric 
79181ad6265SDimitry Andric   error("unknown --android-memtag-mode value: \"" + memtagModeArg +
79281ad6265SDimitry Andric         "\", should be one of {async, sync, none}");
79381ad6265SDimitry Andric   return ELF::NT_MEMTAG_LEVEL_NONE;
79481ad6265SDimitry Andric }
79581ad6265SDimitry Andric 
7960b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) {
7970b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
7980b57cec5SDimitry Andric   if (!arg || arg->getOption().getID() == OPT_icf_none)
7990b57cec5SDimitry Andric     return ICFLevel::None;
8000b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_icf_safe)
8010b57cec5SDimitry Andric     return ICFLevel::Safe;
8020b57cec5SDimitry Andric   return ICFLevel::All;
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) {
8060b57cec5SDimitry Andric   if (args.hasArg(OPT_relocatable))
8070b57cec5SDimitry Andric     return StripPolicy::None;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
8100b57cec5SDimitry Andric   if (!arg)
8110b57cec5SDimitry Andric     return StripPolicy::None;
8120b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_strip_all)
8130b57cec5SDimitry Andric     return StripPolicy::All;
8140b57cec5SDimitry Andric   return StripPolicy::Debug;
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
8180b57cec5SDimitry Andric                                     const opt::Arg &arg) {
8190b57cec5SDimitry Andric   uint64_t va = 0;
82006c3fb27SDimitry Andric   if (s.starts_with("0x"))
8210b57cec5SDimitry Andric     s = s.drop_front(2);
8220b57cec5SDimitry Andric   if (!to_integer(s, va, 16))
8230b57cec5SDimitry Andric     error("invalid argument: " + arg.getAsString(args));
8240b57cec5SDimitry Andric   return va;
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
8280b57cec5SDimitry Andric   StringMap<uint64_t> ret;
8290b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section_start)) {
8300b57cec5SDimitry Andric     StringRef name;
8310b57cec5SDimitry Andric     StringRef addr;
8320b57cec5SDimitry Andric     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
8330b57cec5SDimitry Andric     ret[name] = parseSectionAddress(addr, args, *arg);
8340b57cec5SDimitry Andric   }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Ttext))
8370b57cec5SDimitry Andric     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
8380b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tdata))
8390b57cec5SDimitry Andric     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
8400b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tbss))
8410b57cec5SDimitry Andric     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
8420b57cec5SDimitry Andric   return ret;
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) {
8460b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_sort_section);
8470b57cec5SDimitry Andric   if (s == "alignment")
8480b57cec5SDimitry Andric     return SortSectionPolicy::Alignment;
8490b57cec5SDimitry Andric   if (s == "name")
8500b57cec5SDimitry Andric     return SortSectionPolicy::Name;
8510b57cec5SDimitry Andric   if (!s.empty())
8520b57cec5SDimitry Andric     error("unknown --sort-section rule: " + s);
8530b57cec5SDimitry Andric   return SortSectionPolicy::Default;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
8570b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
8580b57cec5SDimitry Andric   if (s == "warn")
8590b57cec5SDimitry Andric     return OrphanHandlingPolicy::Warn;
8600b57cec5SDimitry Andric   if (s == "error")
8610b57cec5SDimitry Andric     return OrphanHandlingPolicy::Error;
8620b57cec5SDimitry Andric   if (s != "place")
8630b57cec5SDimitry Andric     error("unknown --orphan-handling mode: " + s);
8640b57cec5SDimitry Andric   return OrphanHandlingPolicy::Place;
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a
8680b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including
869349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons.
870bdd1243dSDimitry Andric static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>
8710b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) {
872972a253aSDimitry Andric   auto *arg = args.getLastArg(OPT_build_id);
8730b57cec5SDimitry Andric   if (!arg)
8740b57cec5SDimitry Andric     return {BuildIdKind::None, {}};
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   StringRef s = arg->getValue();
8770b57cec5SDimitry Andric   if (s == "fast")
8780b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
8790b57cec5SDimitry Andric   if (s == "md5")
8800b57cec5SDimitry Andric     return {BuildIdKind::Md5, {}};
8810b57cec5SDimitry Andric   if (s == "sha1" || s == "tree")
8820b57cec5SDimitry Andric     return {BuildIdKind::Sha1, {}};
8830b57cec5SDimitry Andric   if (s == "uuid")
8840b57cec5SDimitry Andric     return {BuildIdKind::Uuid, {}};
88506c3fb27SDimitry Andric   if (s.starts_with("0x"))
8860b57cec5SDimitry Andric     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   if (s != "none")
8890b57cec5SDimitry Andric     error("unknown --build-id style: " + s);
8900b57cec5SDimitry Andric   return {BuildIdKind::None, {}};
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
8940b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
8950b57cec5SDimitry Andric   if (s == "android")
8960b57cec5SDimitry Andric     return {true, false};
8970b57cec5SDimitry Andric   if (s == "relr")
8980b57cec5SDimitry Andric     return {false, true};
8990b57cec5SDimitry Andric   if (s == "android+relr")
9000b57cec5SDimitry Andric     return {true, true};
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric   if (s != "none")
903349cc55cSDimitry Andric     error("unknown --pack-dyn-relocs format: " + s);
9040b57cec5SDimitry Andric   return {false, false};
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) {
9080b57cec5SDimitry Andric   // Build a map from symbol name to section
9090b57cec5SDimitry Andric   DenseMap<StringRef, Symbol *> map;
910bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
9110b57cec5SDimitry Andric     for (Symbol *sym : file->getSymbols())
9120b57cec5SDimitry Andric       map[sym->getName()] = sym;
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   auto findSection = [&](StringRef name) -> InputSectionBase * {
9150b57cec5SDimitry Andric     Symbol *sym = map.lookup(name);
9160b57cec5SDimitry Andric     if (!sym) {
9170b57cec5SDimitry Andric       if (config->warnSymbolOrdering)
9180b57cec5SDimitry Andric         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
9190b57cec5SDimitry Andric       return nullptr;
9200b57cec5SDimitry Andric     }
9210b57cec5SDimitry Andric     maybeWarnUnorderableSymbol(sym);
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
9240b57cec5SDimitry Andric       return dyn_cast_or_null<InputSectionBase>(dr->section);
9250b57cec5SDimitry Andric     return nullptr;
9260b57cec5SDimitry Andric   };
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   for (StringRef line : args::getLines(mb)) {
9290b57cec5SDimitry Andric     SmallVector<StringRef, 3> fields;
9300b57cec5SDimitry Andric     line.split(fields, ' ');
9310b57cec5SDimitry Andric     uint64_t count;
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
9340b57cec5SDimitry Andric       error(mb.getBufferIdentifier() + ": parse error");
9350b57cec5SDimitry Andric       return;
9360b57cec5SDimitry Andric     }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric     if (InputSectionBase *from = findSection(fields[0]))
9390b57cec5SDimitry Andric       if (InputSectionBase *to = findSection(fields[1]))
9400b57cec5SDimitry Andric         config->callGraphProfile[std::make_pair(from, to)] += count;
9410b57cec5SDimitry Andric   }
9420b57cec5SDimitry Andric }
9430b57cec5SDimitry Andric 
944fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
945fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices.
946fe6060f1SDimitry Andric template <class ELFT>
947fe6060f1SDimitry Andric static bool
948fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
949fe6060f1SDimitry Andric                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
950fe6060f1SDimitry Andric                             ObjFile<ELFT> *inputObj) {
951fe6060f1SDimitry Andric   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
952fe6060f1SDimitry Andric     return false;
953fe6060f1SDimitry Andric 
9540eae32dcSDimitry Andric   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
9550eae32dcSDimitry Andric       inputObj->template getELFShdrs<ELFT>();
9560eae32dcSDimitry Andric   symbolIndices.clear();
9570eae32dcSDimitry Andric   const ELFFile<ELFT> &obj = inputObj->getObj();
958fe6060f1SDimitry Andric   cgProfile =
959fe6060f1SDimitry Andric       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
960fe6060f1SDimitry Andric           objSections[inputObj->cgProfileSectionIndex]));
961fe6060f1SDimitry Andric 
962fe6060f1SDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
963fe6060f1SDimitry Andric     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
964fe6060f1SDimitry Andric     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
965fe6060f1SDimitry Andric       if (sec.sh_type == SHT_RELA) {
966fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rela> relas =
967fe6060f1SDimitry Andric             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
968fe6060f1SDimitry Andric         for (const typename ELFT::Rela &rel : relas)
969fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
970fe6060f1SDimitry Andric         break;
971fe6060f1SDimitry Andric       }
972fe6060f1SDimitry Andric       if (sec.sh_type == SHT_REL) {
973fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rel> rels =
974fe6060f1SDimitry Andric             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
975fe6060f1SDimitry Andric         for (const typename ELFT::Rel &rel : rels)
976fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
977fe6060f1SDimitry Andric         break;
978fe6060f1SDimitry Andric       }
979fe6060f1SDimitry Andric     }
980fe6060f1SDimitry Andric   }
981fe6060f1SDimitry Andric   if (symbolIndices.empty())
982fe6060f1SDimitry Andric     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
983fe6060f1SDimitry Andric   return !symbolIndices.empty();
984fe6060f1SDimitry Andric }
985fe6060f1SDimitry Andric 
9860b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() {
987fe6060f1SDimitry Andric   SmallVector<uint32_t, 32> symbolIndices;
988fe6060f1SDimitry Andric   ArrayRef<typename ELFT::CGProfile> cgProfile;
989bdd1243dSDimitry Andric   for (auto file : ctx.objectFiles) {
9900b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
991fe6060f1SDimitry Andric     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
992fe6060f1SDimitry Andric       continue;
9930b57cec5SDimitry Andric 
994fe6060f1SDimitry Andric     if (symbolIndices.size() != cgProfile.size() * 2)
995fe6060f1SDimitry Andric       fatal("number of relocations doesn't match Weights");
996fe6060f1SDimitry Andric 
997fe6060f1SDimitry Andric     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
998fe6060f1SDimitry Andric       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
999fe6060f1SDimitry Andric       uint32_t fromIndex = symbolIndices[i * 2];
1000fe6060f1SDimitry Andric       uint32_t toIndex = symbolIndices[i * 2 + 1];
1001fe6060f1SDimitry Andric       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
1002fe6060f1SDimitry Andric       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
10030b57cec5SDimitry Andric       if (!fromSym || !toSym)
10040b57cec5SDimitry Andric         continue;
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
10070b57cec5SDimitry Andric       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
10080b57cec5SDimitry Andric       if (from && to)
10090b57cec5SDimitry Andric         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
10100b57cec5SDimitry Andric     }
10110b57cec5SDimitry Andric   }
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric 
10145f757f3fSDimitry Andric template <class ELFT>
10155f757f3fSDimitry Andric static void ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList &args) {
10165f757f3fSDimitry Andric   DenseSet<StringRef> typeInfoSymbols;
10175f757f3fSDimitry Andric   SmallSetVector<StringRef, 0> vtableSymbols;
10185f757f3fSDimitry Andric   auto processVtableAndTypeInfoSymbols = [&](StringRef name) {
10195f757f3fSDimitry Andric     if (name.consume_front("_ZTI"))
10205f757f3fSDimitry Andric       typeInfoSymbols.insert(name);
10215f757f3fSDimitry Andric     else if (name.consume_front("_ZTV"))
10225f757f3fSDimitry Andric       vtableSymbols.insert(name);
10235f757f3fSDimitry Andric   };
10245f757f3fSDimitry Andric 
10255f757f3fSDimitry Andric   // Examine all native symbol tables.
10265f757f3fSDimitry Andric   for (ELFFileBase *f : ctx.objectFiles) {
10275f757f3fSDimitry Andric     using Elf_Sym = typename ELFT::Sym;
10285f757f3fSDimitry Andric     for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {
10295f757f3fSDimitry Andric       if (s.st_shndx != SHN_UNDEF) {
10305f757f3fSDimitry Andric         StringRef name = check(s.getName(f->getStringTable()));
10315f757f3fSDimitry Andric         processVtableAndTypeInfoSymbols(name);
10325f757f3fSDimitry Andric       }
10335f757f3fSDimitry Andric     }
10345f757f3fSDimitry Andric   }
10355f757f3fSDimitry Andric 
10365f757f3fSDimitry Andric   for (SharedFile *f : ctx.sharedFiles) {
10375f757f3fSDimitry Andric     using Elf_Sym = typename ELFT::Sym;
10385f757f3fSDimitry Andric     for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {
10395f757f3fSDimitry Andric       if (s.st_shndx != SHN_UNDEF) {
10405f757f3fSDimitry Andric         StringRef name = check(s.getName(f->getStringTable()));
10415f757f3fSDimitry Andric         processVtableAndTypeInfoSymbols(name);
10425f757f3fSDimitry Andric       }
10435f757f3fSDimitry Andric     }
10445f757f3fSDimitry Andric   }
10455f757f3fSDimitry Andric 
10465f757f3fSDimitry Andric   SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI;
10475f757f3fSDimitry Andric   for (StringRef s : vtableSymbols)
10485f757f3fSDimitry Andric     if (!typeInfoSymbols.count(s))
10495f757f3fSDimitry Andric       vtableSymbolsWithNoRTTI.insert(s);
10505f757f3fSDimitry Andric 
10515f757f3fSDimitry Andric   // Remove known safe symbols.
10525f757f3fSDimitry Andric   for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) {
10535f757f3fSDimitry Andric     StringRef knownSafeName = arg->getValue();
10545f757f3fSDimitry Andric     if (!knownSafeName.consume_front("_ZTV"))
10555f757f3fSDimitry Andric       error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, "
10565f757f3fSDimitry Andric             "but got " +
10575f757f3fSDimitry Andric             knownSafeName);
10587a6dacacSDimitry Andric     Expected<GlobPattern> pat = GlobPattern::create(knownSafeName);
10597a6dacacSDimitry Andric     if (!pat)
10607a6dacacSDimitry Andric       error("--lto-known-safe-vtables=: " + toString(pat.takeError()));
10617a6dacacSDimitry Andric     vtableSymbolsWithNoRTTI.remove_if(
10627a6dacacSDimitry Andric         [&](StringRef s) { return pat->match(s); });
10635f757f3fSDimitry Andric   }
10645f757f3fSDimitry Andric 
10655f757f3fSDimitry Andric   ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty();
10665f757f3fSDimitry Andric   // Check for unmatched RTTI symbols
10675f757f3fSDimitry Andric   for (StringRef s : vtableSymbolsWithNoRTTI) {
10685f757f3fSDimitry Andric     message(
10695f757f3fSDimitry Andric         "--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable "
10705f757f3fSDimitry Andric         "_ZTV" +
10715f757f3fSDimitry Andric         s + ", --lto-whole-program-visibility disabled");
10725f757f3fSDimitry Andric   }
10735f757f3fSDimitry Andric }
10745f757f3fSDimitry Andric 
10755f757f3fSDimitry Andric static CGProfileSortKind getCGProfileSortKind(opt::InputArgList &args) {
10765f757f3fSDimitry Andric   StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort");
10775f757f3fSDimitry Andric   if (s == "hfsort")
10785f757f3fSDimitry Andric     return CGProfileSortKind::Hfsort;
10795f757f3fSDimitry Andric   if (s == "cdsort")
10805f757f3fSDimitry Andric     return CGProfileSortKind::Cdsort;
10815f757f3fSDimitry Andric   if (s != "none")
10825f757f3fSDimitry Andric     error("unknown --call-graph-profile-sort= value: " + s);
10835f757f3fSDimitry Andric   return CGProfileSortKind::None;
10845f757f3fSDimitry Andric }
10855f757f3fSDimitry Andric 
108606c3fb27SDimitry Andric static DebugCompressionType getCompressionType(StringRef s, StringRef option) {
108706c3fb27SDimitry Andric   DebugCompressionType type = StringSwitch<DebugCompressionType>(s)
108806c3fb27SDimitry Andric                                   .Case("zlib", DebugCompressionType::Zlib)
108906c3fb27SDimitry Andric                                   .Case("zstd", DebugCompressionType::Zstd)
109006c3fb27SDimitry Andric                                   .Default(DebugCompressionType::None);
109106c3fb27SDimitry Andric   if (type == DebugCompressionType::None) {
1092bdd1243dSDimitry Andric     if (s != "none")
109306c3fb27SDimitry Andric       error("unknown " + option + " value: " + s);
109406c3fb27SDimitry Andric   } else if (const char *reason = compression::getReasonIfUnsupported(
109506c3fb27SDimitry Andric                  compression::formatFor(type))) {
109606c3fb27SDimitry Andric     error(option + ": " + reason);
109706c3fb27SDimitry Andric   }
109806c3fb27SDimitry Andric   return type;
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
110185868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) {
110285868e8aSDimitry Andric   if (const opt::Arg *alias = arg->getAlias())
110385868e8aSDimitry Andric     return alias->getSpelling();
110485868e8aSDimitry Andric   return arg->getSpelling();
110585868e8aSDimitry Andric }
110685868e8aSDimitry Andric 
11070b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
11080b57cec5SDimitry Andric                                                         unsigned id) {
11090b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
11100b57cec5SDimitry Andric   if (!arg)
11110b57cec5SDimitry Andric     return {"", ""};
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   StringRef s = arg->getValue();
11140b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
11150b57cec5SDimitry Andric   if (ret.second.empty())
111685868e8aSDimitry Andric     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
11170b57cec5SDimitry Andric   return ret;
11180b57cec5SDimitry Andric }
11190b57cec5SDimitry Andric 
112006c3fb27SDimitry Andric // Parse options of the form "old;new[;extra]".
112106c3fb27SDimitry Andric static std::tuple<StringRef, StringRef, StringRef>
112206c3fb27SDimitry Andric getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
112306c3fb27SDimitry Andric   auto [oldDir, second] = getOldNewOptions(args, id);
112406c3fb27SDimitry Andric   auto [newDir, extraDir] = second.split(';');
112506c3fb27SDimitry Andric   return {oldDir, newDir, extraDir};
112606c3fb27SDimitry Andric }
112706c3fb27SDimitry Andric 
11280b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries.
1129bdd1243dSDimitry Andric static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) {
1130bdd1243dSDimitry Andric   SetVector<StringRef, SmallVector<StringRef, 0>> names;
11310b57cec5SDimitry Andric   for (StringRef s : args::getLines(mb))
11320b57cec5SDimitry Andric     if (!names.insert(s) && config->warnSymbolOrdering)
11330b57cec5SDimitry Andric       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   return names.takeVector();
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
11385ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) {
11397a6dacacSDimitry Andric   // The psABI specifies the default relocation entry format.
11407a6dacacSDimitry Andric   bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH,
1141*74626c16SDimitry Andric                             EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64},
11427a6dacacSDimitry Andric                            config->emachine);
11435ffd83dbSDimitry Andric   // If -z rel or -z rela is specified, use the last option.
11447a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
11455ffd83dbSDimitry Andric     StringRef s(arg->getValue());
11465ffd83dbSDimitry Andric     if (s == "rel")
11477a6dacacSDimitry Andric       rela = false;
11487a6dacacSDimitry Andric     else if (s == "rela")
11497a6dacacSDimitry Andric       rela = true;
11507a6dacacSDimitry Andric     else
11517a6dacacSDimitry Andric       continue;
11527a6dacacSDimitry Andric     arg->claim();
11535ffd83dbSDimitry Andric   }
11547a6dacacSDimitry Andric   return rela;
11555ffd83dbSDimitry Andric }
11565ffd83dbSDimitry Andric 
11570b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) {
11580b57cec5SDimitry Andric   std::string err;
11590b57cec5SDimitry Andric   raw_string_ostream os(err);
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   const char *argv[] = {config->progName.data(), opt.data()};
11620b57cec5SDimitry Andric   if (cl::ParseCommandLineOptions(2, argv, "", &os))
11630b57cec5SDimitry Andric     return;
11640b57cec5SDimitry Andric   os.flush();
11650b57cec5SDimitry Andric   error(msg + ": " + StringRef(err).trim());
11660b57cec5SDimitry Andric }
11670b57cec5SDimitry Andric 
11680eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options.
11690eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) {
11700eae32dcSDimitry Andric   return arg == "none" || arg == "warning" || arg == "error";
11710eae32dcSDimitry Andric }
11720eae32dcSDimitry Andric 
117306c3fb27SDimitry Andric // Process a remap pattern 'from-glob=to-file'.
117406c3fb27SDimitry Andric static bool remapInputs(StringRef line, const Twine &location) {
117506c3fb27SDimitry Andric   SmallVector<StringRef, 0> fields;
117606c3fb27SDimitry Andric   line.split(fields, '=');
117706c3fb27SDimitry Andric   if (fields.size() != 2 || fields[1].empty()) {
117806c3fb27SDimitry Andric     error(location + ": parse error, not 'from-glob=to-file'");
117906c3fb27SDimitry Andric     return true;
118006c3fb27SDimitry Andric   }
118106c3fb27SDimitry Andric   if (!hasWildcard(fields[0]))
118206c3fb27SDimitry Andric     config->remapInputs[fields[0]] = fields[1];
118306c3fb27SDimitry Andric   else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))
118406c3fb27SDimitry Andric     config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);
118506c3fb27SDimitry Andric   else {
11865f757f3fSDimitry Andric     error(location + ": " + toString(pat.takeError()) + ": " + fields[0]);
118706c3fb27SDimitry Andric     return true;
118806c3fb27SDimitry Andric   }
118906c3fb27SDimitry Andric   return false;
119006c3fb27SDimitry Andric }
119106c3fb27SDimitry Andric 
11920b57cec5SDimitry Andric // Initializes Config members by the command line options.
11930b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) {
11940b57cec5SDimitry Andric   errorHandler().verbose = args.hasArg(OPT_verbose);
11950b57cec5SDimitry Andric   errorHandler().vsDiagnostics =
11960b57cec5SDimitry Andric       args.hasArg(OPT_visual_studio_diagnostics_format, false);
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   config->allowMultipleDefinition =
11997a6dacacSDimitry Andric       hasZOption(args, "muldefs") ||
12000b57cec5SDimitry Andric       args.hasFlag(OPT_allow_multiple_definition,
12017a6dacacSDimitry Andric                    OPT_no_allow_multiple_definition, false);
120281ad6265SDimitry Andric   config->androidMemtagHeap =
120381ad6265SDimitry Andric       args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);
120481ad6265SDimitry Andric   config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
120581ad6265SDimitry Andric                                             OPT_no_android_memtag_stack, false);
12065f757f3fSDimitry Andric   config->fatLTOObjects =
12075f757f3fSDimitry Andric       args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false);
120881ad6265SDimitry Andric   config->androidMemtagMode = getMemtagMode(args);
12090b57cec5SDimitry Andric   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
121006c3fb27SDimitry Andric   config->armBe8 = args.hasArg(OPT_be8);
12115f757f3fSDimitry Andric   if (opt::Arg *arg = args.getLastArg(
12125f757f3fSDimitry Andric           OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
12135f757f3fSDimitry Andric           OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) {
12146e75b2fbSDimitry Andric     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
12156e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
12166e75b2fbSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
12176e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::Functions;
12185f757f3fSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))
12195f757f3fSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeak;
1220fe6060f1SDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic))
12216e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::All;
1222fe6060f1SDimitry Andric   }
12235f757f3fSDimitry Andric   config->callGraphProfileSort = getCGProfileSortKind(args);
12240b57cec5SDimitry Andric   config->checkSections =
12250b57cec5SDimitry Andric       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
12260b57cec5SDimitry Andric   config->chroot = args.getLastArgValue(OPT_chroot);
122706c3fb27SDimitry Andric   config->compressDebugSections = getCompressionType(
122806c3fb27SDimitry Andric       args.getLastArgValue(OPT_compress_debug_sections, "none"),
122906c3fb27SDimitry Andric       "--compress-debug-sections");
1230fe6060f1SDimitry Andric   config->cref = args.hasArg(OPT_cref);
12315ffd83dbSDimitry Andric   config->optimizeBBJumps =
12325ffd83dbSDimitry Andric       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
12330b57cec5SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1234e8d8bef9SDimitry Andric   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
12350b57cec5SDimitry Andric   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
12360b57cec5SDimitry Andric   config->disableVerify = args.hasArg(OPT_disable_verify);
12370b57cec5SDimitry Andric   config->discard = getDiscard(args);
12380b57cec5SDimitry Andric   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
12390b57cec5SDimitry Andric   config->dynamicLinker = getDynamicLinker(args);
12400b57cec5SDimitry Andric   config->ehFrameHdr =
12410b57cec5SDimitry Andric       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
12420b57cec5SDimitry Andric   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
12430b57cec5SDimitry Andric   config->emitRelocs = args.hasArg(OPT_emit_relocs);
12440b57cec5SDimitry Andric   config->enableNewDtags =
12450b57cec5SDimitry Andric       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
12460b57cec5SDimitry Andric   config->entry = args.getLastArgValue(OPT_entry);
1247e8d8bef9SDimitry Andric 
1248e8d8bef9SDimitry Andric   errorHandler().errorHandlingScript =
1249e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_error_handling_script);
1250e8d8bef9SDimitry Andric 
12510b57cec5SDimitry Andric   config->executeOnly =
12520b57cec5SDimitry Andric       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
12530b57cec5SDimitry Andric   config->exportDynamic =
125481ad6265SDimitry Andric       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||
125581ad6265SDimitry Andric       args.hasArg(OPT_shared);
12560b57cec5SDimitry Andric   config->filterList = args::getStrings(args, OPT_filter);
12570b57cec5SDimitry Andric   config->fini = args.getLastArgValue(OPT_fini, "_fini");
12585ffd83dbSDimitry Andric   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
12595ffd83dbSDimitry Andric                                      !args.hasArg(OPT_relocatable);
126006c3fb27SDimitry Andric   config->cmseImplib = args.hasArg(OPT_cmse_implib);
126106c3fb27SDimitry Andric   config->cmseInputLib = args.getLastArgValue(OPT_in_implib);
126206c3fb27SDimitry Andric   config->cmseOutputLib = args.getLastArgValue(OPT_out_implib);
12635ffd83dbSDimitry Andric   config->fixCortexA8 =
12645ffd83dbSDimitry Andric       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1265e8d8bef9SDimitry Andric   config->fortranCommon =
126681ad6265SDimitry Andric       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);
12670b57cec5SDimitry Andric   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
12680b57cec5SDimitry Andric   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
12690b57cec5SDimitry Andric   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
12700b57cec5SDimitry Andric   config->icf = getICF(args);
12710b57cec5SDimitry Andric   config->ignoreDataAddressEquality =
12720b57cec5SDimitry Andric       args.hasArg(OPT_ignore_data_address_equality);
12730b57cec5SDimitry Andric   config->ignoreFunctionAddressEquality =
12740b57cec5SDimitry Andric       args.hasArg(OPT_ignore_function_address_equality);
12750b57cec5SDimitry Andric   config->init = args.getLastArgValue(OPT_init, "_init");
12760b57cec5SDimitry Andric   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
12770b57cec5SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
12780b57cec5SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1279349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1280349cc55cSDimitry Andric                                             OPT_no_lto_pgo_warn_mismatch, true);
12810b57cec5SDimitry Andric   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
12825ffd83dbSDimitry Andric   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
12830b57cec5SDimitry Andric   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
12845ffd83dbSDimitry Andric   config->ltoWholeProgramVisibility =
1285e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_whole_program_visibility,
1286e8d8bef9SDimitry Andric                    OPT_no_lto_whole_program_visibility, false);
12875f757f3fSDimitry Andric   config->ltoValidateAllVtablesHaveTypeInfos =
12885f757f3fSDimitry Andric       args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos,
12895f757f3fSDimitry Andric                    OPT_no_lto_validate_all_vtables_have_type_infos, false);
12900b57cec5SDimitry Andric   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
129106c3fb27SDimitry Andric   if (config->ltoo > 3)
129206c3fb27SDimitry Andric     error("invalid optimization level for LTO: " + Twine(config->ltoo));
129306c3fb27SDimitry Andric   unsigned ltoCgo =
129406c3fb27SDimitry Andric       args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
129506c3fb27SDimitry Andric   if (auto level = CodeGenOpt::getLevel(ltoCgo))
129606c3fb27SDimitry Andric     config->ltoCgo = *level;
129706c3fb27SDimitry Andric   else
129806c3fb27SDimitry Andric     error("invalid codegen optimization level for LTO: " + Twine(ltoCgo));
129985868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
13000b57cec5SDimitry Andric   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
13010b57cec5SDimitry Andric   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
13025ffd83dbSDimitry Andric   config->ltoBasicBlockSections =
1303e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_lto_basic_block_sections);
13045ffd83dbSDimitry Andric   config->ltoUniqueBasicBlockSectionNames =
1305e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1306e8d8bef9SDimitry Andric                    OPT_no_lto_unique_basic_block_section_names, false);
13070b57cec5SDimitry Andric   config->mapFile = args.getLastArgValue(OPT_Map);
13080b57cec5SDimitry Andric   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
13090b57cec5SDimitry Andric   config->mergeArmExidx =
13100b57cec5SDimitry Andric       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1311480093f4SDimitry Andric   config->mmapOutputFile =
1312480093f4SDimitry Andric       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
13130b57cec5SDimitry Andric   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
13140b57cec5SDimitry Andric   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
13150b57cec5SDimitry Andric   config->nostdlib = args.hasArg(OPT_nostdlib);
13160b57cec5SDimitry Andric   config->oFormatBinary = isOutputFormatBinary(args);
13170b57cec5SDimitry Andric   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
13180b57cec5SDimitry Andric   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
131981ad6265SDimitry Andric   config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1320e8d8bef9SDimitry Andric 
1321e8d8bef9SDimitry Andric   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1322e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1323e8d8bef9SDimitry Andric     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1324e8d8bef9SDimitry Andric     if (!resultOrErr)
1325e8d8bef9SDimitry Andric       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1326e8d8bef9SDimitry Andric             "', only integer or 'auto' is supported");
1327e8d8bef9SDimitry Andric     else
1328e8d8bef9SDimitry Andric       config->optRemarksHotnessThreshold = *resultOrErr;
1329e8d8bef9SDimitry Andric   }
1330e8d8bef9SDimitry Andric 
13310b57cec5SDimitry Andric   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
13320b57cec5SDimitry Andric   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
13330b57cec5SDimitry Andric   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
13340b57cec5SDimitry Andric   config->optimize = args::getInteger(args, OPT_O, 1);
13350b57cec5SDimitry Andric   config->orphanHandling = getOrphanHandling(args);
13360b57cec5SDimitry Andric   config->outputFile = args.getLastArgValue(OPT_o);
133761cfbce3SDimitry Andric   config->packageMetadata = args.getLastArgValue(OPT_package_metadata);
13380b57cec5SDimitry Andric   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
13390b57cec5SDimitry Andric   config->printIcfSections =
13400b57cec5SDimitry Andric       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
13410b57cec5SDimitry Andric   config->printGcSections =
13420b57cec5SDimitry Andric       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
134306c3fb27SDimitry Andric   config->printMemoryUsage = args.hasArg(OPT_print_memory_usage);
13445ffd83dbSDimitry Andric   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
13450b57cec5SDimitry Andric   config->printSymbolOrder =
13460b57cec5SDimitry Andric       args.getLastArgValue(OPT_print_symbol_order);
1347349cc55cSDimitry Andric   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
134806c3fb27SDimitry Andric   config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);
13490b57cec5SDimitry Andric   config->rpath = getRpath(args);
13500b57cec5SDimitry Andric   config->relocatable = args.hasArg(OPT_relocatable);
1351753f127fSDimitry Andric 
1352753f127fSDimitry Andric   if (args.hasArg(OPT_save_temps)) {
1353753f127fSDimitry Andric     // --save-temps implies saving all temps.
1354753f127fSDimitry Andric     for (const char *s : saveTempsValues)
1355753f127fSDimitry Andric       config->saveTempsArgs.insert(s);
1356753f127fSDimitry Andric   } else {
1357753f127fSDimitry Andric     for (auto *arg : args.filtered(OPT_save_temps_eq)) {
1358753f127fSDimitry Andric       StringRef s = arg->getValue();
1359753f127fSDimitry Andric       if (llvm::is_contained(saveTempsValues, s))
1360753f127fSDimitry Andric         config->saveTempsArgs.insert(s);
1361753f127fSDimitry Andric       else
1362753f127fSDimitry Andric         error("unknown --save-temps value: " + s);
1363753f127fSDimitry Andric     }
1364753f127fSDimitry Andric   }
1365753f127fSDimitry Andric 
13660b57cec5SDimitry Andric   config->searchPaths = args::getStrings(args, OPT_library_path);
13670b57cec5SDimitry Andric   config->sectionStartMap = getSectionStartMap(args);
13680b57cec5SDimitry Andric   config->shared = args.hasArg(OPT_shared);
13695ffd83dbSDimitry Andric   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
13700b57cec5SDimitry Andric   config->soName = args.getLastArgValue(OPT_soname);
13710b57cec5SDimitry Andric   config->sortSection = getSortSection(args);
13720b57cec5SDimitry Andric   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
13730b57cec5SDimitry Andric   config->strip = getStrip(args);
13740b57cec5SDimitry Andric   config->sysroot = args.getLastArgValue(OPT_sysroot);
13750b57cec5SDimitry Andric   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
13760b57cec5SDimitry Andric   config->target2 = getTarget2(args);
13770b57cec5SDimitry Andric   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
13780b57cec5SDimitry Andric   config->thinLTOCachePolicy = CHECK(
13790b57cec5SDimitry Andric       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
13800b57cec5SDimitry Andric       "--thinlto-cache-policy: invalid cache policy");
138185868e8aSDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
138281ad6265SDimitry Andric   config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
138381ad6265SDimitry Andric                                   args.hasArg(OPT_thinlto_index_only) ||
138481ad6265SDimitry Andric                                   args.hasArg(OPT_thinlto_index_only_eq);
138585868e8aSDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
138685868e8aSDimitry Andric                              args.hasArg(OPT_thinlto_index_only_eq);
138785868e8aSDimitry Andric   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
13880b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
138985868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
139006c3fb27SDimitry Andric   std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
139106c3fb27SDimitry Andric            config->thinLTOPrefixReplaceNativeObject) =
139206c3fb27SDimitry Andric       getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);
139381ad6265SDimitry Andric   if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
139481ad6265SDimitry Andric     if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
139581ad6265SDimitry Andric       error("--thinlto-object-suffix-replace is not supported with "
139681ad6265SDimitry Andric             "--thinlto-emit-index-files");
139781ad6265SDimitry Andric     else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
139881ad6265SDimitry Andric       error("--thinlto-prefix-replace is not supported with "
139981ad6265SDimitry Andric             "--thinlto-emit-index-files");
140081ad6265SDimitry Andric   }
140106c3fb27SDimitry Andric   if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
140206c3fb27SDimitry Andric       config->thinLTOIndexOnlyArg.empty()) {
140306c3fb27SDimitry Andric     error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
140406c3fb27SDimitry Andric           "--thinlto-index-only=");
140506c3fb27SDimitry Andric   }
14065ffd83dbSDimitry Andric   config->thinLTOModulesToCompile =
14075ffd83dbSDimitry Andric       args::getStrings(args, OPT_thinlto_single_module_eq);
140881ad6265SDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
14095ffd83dbSDimitry Andric   config->timeTraceGranularity =
14105ffd83dbSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity, 500);
14110b57cec5SDimitry Andric   config->trace = args.hasArg(OPT_trace);
14120b57cec5SDimitry Andric   config->undefined = args::getStrings(args, OPT_undefined);
14130b57cec5SDimitry Andric   config->undefinedVersion =
1414bdd1243dSDimitry Andric       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);
14155ffd83dbSDimitry Andric   config->unique = args.hasArg(OPT_unique);
14160b57cec5SDimitry Andric   config->useAndroidRelrTags = args.hasFlag(
14170b57cec5SDimitry Andric       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
14180b57cec5SDimitry Andric   config->warnBackrefs =
14190b57cec5SDimitry Andric       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
14200b57cec5SDimitry Andric   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
14210b57cec5SDimitry Andric   config->warnSymbolOrdering =
14220b57cec5SDimitry Andric       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1423349cc55cSDimitry Andric   config->whyExtract = args.getLastArgValue(OPT_why_extract);
14240b57cec5SDimitry Andric   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
14250b57cec5SDimitry Andric   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
14265ffd83dbSDimitry Andric   config->zForceBti = hasZOption(args, "force-bti");
1427480093f4SDimitry Andric   config->zForceIbt = hasZOption(args, "force-ibt");
14280b57cec5SDimitry Andric   config->zGlobal = hasZOption(args, "global");
1429480093f4SDimitry Andric   config->zGnustack = getZGnuStack(args);
14300b57cec5SDimitry Andric   config->zHazardplt = hasZOption(args, "hazardplt");
14310b57cec5SDimitry Andric   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
14320b57cec5SDimitry Andric   config->zInitfirst = hasZOption(args, "initfirst");
14330b57cec5SDimitry Andric   config->zInterpose = hasZOption(args, "interpose");
14340b57cec5SDimitry Andric   config->zKeepTextSectionPrefix = getZFlag(
14350b57cec5SDimitry Andric       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
14360b57cec5SDimitry Andric   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
14370b57cec5SDimitry Andric   config->zNodelete = hasZOption(args, "nodelete");
14380b57cec5SDimitry Andric   config->zNodlopen = hasZOption(args, "nodlopen");
14390b57cec5SDimitry Andric   config->zNow = getZFlag(args, "now", "lazy", false);
14400b57cec5SDimitry Andric   config->zOrigin = hasZOption(args, "origin");
14415ffd83dbSDimitry Andric   config->zPacPlt = hasZOption(args, "pac-plt");
14420b57cec5SDimitry Andric   config->zRelro = getZFlag(args, "relro", "norelro", true);
14430b57cec5SDimitry Andric   config->zRetpolineplt = hasZOption(args, "retpolineplt");
14440b57cec5SDimitry Andric   config->zRodynamic = hasZOption(args, "rodynamic");
144585868e8aSDimitry Andric   config->zSeparate = getZSeparate(args);
1446480093f4SDimitry Andric   config->zShstk = hasZOption(args, "shstk");
14470b57cec5SDimitry Andric   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1448fe6060f1SDimitry Andric   config->zStartStopGC =
1449fe6060f1SDimitry Andric       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
14505ffd83dbSDimitry Andric   config->zStartStopVisibility = getZStartStopVisibility(args);
14510b57cec5SDimitry Andric   config->zText = getZFlag(args, "text", "notext", true);
14520b57cec5SDimitry Andric   config->zWxneeded = hasZOption(args, "wxneeded");
1453e8d8bef9SDimitry Andric   setUnresolvedSymbolPolicy(args);
14544824e7fdSDimitry Andric   config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1455fe6060f1SDimitry Andric 
1456fe6060f1SDimitry Andric   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1457fe6060f1SDimitry Andric     if (arg->getOption().matches(OPT_eb))
1458fe6060f1SDimitry Andric       config->optEB = true;
1459fe6060f1SDimitry Andric     else
1460fe6060f1SDimitry Andric       config->optEL = true;
1461fe6060f1SDimitry Andric   }
1462fe6060f1SDimitry Andric 
146306c3fb27SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {
146406c3fb27SDimitry Andric     StringRef value(arg->getValue());
146506c3fb27SDimitry Andric     remapInputs(value, arg->getSpelling());
146606c3fb27SDimitry Andric   }
146706c3fb27SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {
146806c3fb27SDimitry Andric     StringRef filename(arg->getValue());
146906c3fb27SDimitry Andric     std::optional<MemoryBufferRef> buffer = readFile(filename);
147006c3fb27SDimitry Andric     if (!buffer)
147106c3fb27SDimitry Andric       continue;
147206c3fb27SDimitry Andric     // Parse 'from-glob=to-file' lines, ignoring #-led comments.
147306c3fb27SDimitry Andric     for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))
147406c3fb27SDimitry Andric       if (remapInputs(line, filename + ":" + Twine(lineno + 1)))
147506c3fb27SDimitry Andric         break;
147606c3fb27SDimitry Andric   }
147706c3fb27SDimitry Andric 
1478fe6060f1SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1479fe6060f1SDimitry Andric     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1480fe6060f1SDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1481fe6060f1SDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
1482fe6060f1SDimitry Andric       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1483fe6060f1SDimitry Andric             arg->getValue() + "'");
1484fe6060f1SDimitry Andric       continue;
1485fe6060f1SDimitry Andric     }
1486fe6060f1SDimitry Andric     // Signed so that <section_glob>=-1 is allowed.
1487fe6060f1SDimitry Andric     int64_t v;
1488fe6060f1SDimitry Andric     if (!to_integer(kv.second, v))
1489fe6060f1SDimitry Andric       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1490fe6060f1SDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1491fe6060f1SDimitry Andric       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1492fe6060f1SDimitry Andric     else
14935f757f3fSDimitry Andric       error(errPrefix + toString(pat.takeError()) + ": " + kv.first);
1494fe6060f1SDimitry Andric   }
14950b57cec5SDimitry Andric 
14960eae32dcSDimitry Andric   auto reports = {std::make_pair("bti-report", &config->zBtiReport),
14970eae32dcSDimitry Andric                   std::make_pair("cet-report", &config->zCetReport)};
14980eae32dcSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
14990eae32dcSDimitry Andric     std::pair<StringRef, StringRef> option =
15000eae32dcSDimitry Andric         StringRef(arg->getValue()).split('=');
15010eae32dcSDimitry Andric     for (auto reportArg : reports) {
15020eae32dcSDimitry Andric       if (option.first != reportArg.first)
15030eae32dcSDimitry Andric         continue;
15047a6dacacSDimitry Andric       arg->claim();
15050eae32dcSDimitry Andric       if (!isValidReportString(option.second)) {
15060eae32dcSDimitry Andric         error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
15070eae32dcSDimitry Andric               " is not recognized");
15080eae32dcSDimitry Andric         continue;
15090eae32dcSDimitry Andric       }
15100eae32dcSDimitry Andric       *reportArg.second = option.second;
15110eae32dcSDimitry Andric     }
15120eae32dcSDimitry Andric   }
15130eae32dcSDimitry Andric 
15145ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
15155ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> option =
15165ffd83dbSDimitry Andric         StringRef(arg->getValue()).split('=');
15175ffd83dbSDimitry Andric     if (option.first != "dead-reloc-in-nonalloc")
15185ffd83dbSDimitry Andric       continue;
15197a6dacacSDimitry Andric     arg->claim();
15205ffd83dbSDimitry Andric     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
15215ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = option.second.split('=');
15225ffd83dbSDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
15235ffd83dbSDimitry Andric       error(errPrefix + "expected <section_glob>=<value>");
15245ffd83dbSDimitry Andric       continue;
15255ffd83dbSDimitry Andric     }
15265ffd83dbSDimitry Andric     uint64_t v;
15275ffd83dbSDimitry Andric     if (!to_integer(kv.second, v))
15285ffd83dbSDimitry Andric       error(errPrefix + "expected a non-negative integer, but got '" +
15295ffd83dbSDimitry Andric             kv.second + "'");
15305ffd83dbSDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
15315ffd83dbSDimitry Andric       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
15325ffd83dbSDimitry Andric     else
15335f757f3fSDimitry Andric       error(errPrefix + toString(pat.takeError()) + ": " + kv.first);
15345ffd83dbSDimitry Andric   }
15355ffd83dbSDimitry Andric 
1536e8d8bef9SDimitry Andric   cl::ResetAllOptionOccurrences();
1537e8d8bef9SDimitry Andric 
15380b57cec5SDimitry Andric   // Parse LTO options.
15390b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
154004eeddc0SDimitry Andric     parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
15410b57cec5SDimitry Andric                      arg->getSpelling());
15420b57cec5SDimitry Andric 
15435ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
15445ffd83dbSDimitry Andric     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
15455ffd83dbSDimitry Andric 
15465ffd83dbSDimitry Andric   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1547f3fd488fSDimitry Andric   // relative path. Just ignore. If not ended with "lto-wrapper" (or
1548f3fd488fSDimitry Andric   // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
15495ffd83dbSDimitry Andric   // unsupported LLVMgold.so option and error.
1550f3fd488fSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
1551f3fd488fSDimitry Andric     StringRef v(arg->getValue());
155206c3fb27SDimitry Andric     if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
15535ffd83dbSDimitry Andric       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
15545ffd83dbSDimitry Andric             "'");
1555f3fd488fSDimitry Andric   }
15560b57cec5SDimitry Andric 
155781ad6265SDimitry Andric   config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
155881ad6265SDimitry Andric 
15590b57cec5SDimitry Andric   // Parse -mllvm options.
1560bdd1243dSDimitry Andric   for (const auto *arg : args.filtered(OPT_mllvm)) {
15610b57cec5SDimitry Andric     parseClangOption(arg->getValue(), arg->getSpelling());
1562bdd1243dSDimitry Andric     config->mllvmOpts.emplace_back(arg->getValue());
1563bdd1243dSDimitry Andric   }
15640b57cec5SDimitry Andric 
156506c3fb27SDimitry Andric   config->ltoKind = LtoKind::Default;
156606c3fb27SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lto)) {
156706c3fb27SDimitry Andric     StringRef s = arg->getValue();
156806c3fb27SDimitry Andric     if (s == "thin")
156906c3fb27SDimitry Andric       config->ltoKind = LtoKind::UnifiedThin;
157006c3fb27SDimitry Andric     else if (s == "full")
157106c3fb27SDimitry Andric       config->ltoKind = LtoKind::UnifiedRegular;
157206c3fb27SDimitry Andric     else if (s == "default")
157306c3fb27SDimitry Andric       config->ltoKind = LtoKind::Default;
157406c3fb27SDimitry Andric     else
157506c3fb27SDimitry Andric       error("unknown LTO mode: " + s);
157606c3fb27SDimitry Andric   }
157706c3fb27SDimitry Andric 
15785ffd83dbSDimitry Andric   // --threads= takes a positive integer and provides the default value for
157906c3fb27SDimitry Andric   // --thinlto-jobs=. If unspecified, cap the number of threads since
158006c3fb27SDimitry Andric   // overhead outweighs optimization for used parallel algorithms for the
158106c3fb27SDimitry Andric   // non-LTO parts.
15825ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
15835ffd83dbSDimitry Andric     StringRef v(arg->getValue());
15845ffd83dbSDimitry Andric     unsigned threads = 0;
15855ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
15865ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
15875ffd83dbSDimitry Andric             arg->getValue() + "'");
15885ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
15895ffd83dbSDimitry Andric     config->thinLTOJobs = v;
159006c3fb27SDimitry Andric   } else if (parallel::strategy.compute_thread_count() > 16) {
159106c3fb27SDimitry Andric     log("set maximum concurrency to 16, specify --threads= to change");
159206c3fb27SDimitry Andric     parallel::strategy = hardware_concurrency(16);
15935ffd83dbSDimitry Andric   }
1594bdd1243dSDimitry Andric   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
15955ffd83dbSDimitry Andric     config->thinLTOJobs = arg->getValue();
1596bdd1243dSDimitry Andric   config->threadCount = parallel::strategy.compute_thread_count();
15975ffd83dbSDimitry Andric 
15980b57cec5SDimitry Andric   if (config->ltoPartitions == 0)
15990b57cec5SDimitry Andric     error("--lto-partitions: number of threads must be > 0");
16005ffd83dbSDimitry Andric   if (!get_threadpool_strategy(config->thinLTOJobs))
16015ffd83dbSDimitry Andric     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric   if (config->splitStackAdjustSize < 0)
16040b57cec5SDimitry Andric     error("--split-stack-adjust-size: size must be >= 0");
16050b57cec5SDimitry Andric 
1606480093f4SDimitry Andric   // The text segment is traditionally the first segment, whose address equals
1607480093f4SDimitry Andric   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1608480093f4SDimitry Andric   // is an old-fashioned option that does not play well with lld's layout.
1609480093f4SDimitry Andric   // Suggest --image-base as a likely alternative.
1610480093f4SDimitry Andric   if (args.hasArg(OPT_Ttext_segment))
1611480093f4SDimitry Andric     error("-Ttext-segment is not supported. Use --image-base if you "
1612480093f4SDimitry Andric           "intend to set the base address");
1613480093f4SDimitry Andric 
16140b57cec5SDimitry Andric   // Parse ELF{32,64}{LE,BE} and CPU type.
16150b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_m)) {
16160b57cec5SDimitry Andric     StringRef s = arg->getValue();
16170b57cec5SDimitry Andric     std::tie(config->ekind, config->emachine, config->osabi) =
16180b57cec5SDimitry Andric         parseEmulation(s);
16190b57cec5SDimitry Andric     config->mipsN32Abi =
162006c3fb27SDimitry Andric         (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));
16210b57cec5SDimitry Andric     config->emulation = s;
16220b57cec5SDimitry Andric   }
16230b57cec5SDimitry Andric 
1624349cc55cSDimitry Andric   // Parse --hash-style={sysv,gnu,both}.
16250b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_hash_style)) {
16260b57cec5SDimitry Andric     StringRef s = arg->getValue();
16270b57cec5SDimitry Andric     if (s == "sysv")
16280b57cec5SDimitry Andric       config->sysvHash = true;
16290b57cec5SDimitry Andric     else if (s == "gnu")
16300b57cec5SDimitry Andric       config->gnuHash = true;
16310b57cec5SDimitry Andric     else if (s == "both")
16320b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
16330b57cec5SDimitry Andric     else
1634349cc55cSDimitry Andric       error("unknown --hash-style: " + s);
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   if (args.hasArg(OPT_print_map))
16380b57cec5SDimitry Andric     config->mapFile = "-";
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
16410b57cec5SDimitry Andric   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
16425f757f3fSDimitry Andric   // it. Also disable RELRO for -r.
16435f757f3fSDimitry Andric   if (config->nmagic || config->omagic || config->relocatable)
16440b57cec5SDimitry Andric     config->zRelro = false;
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
16470b57cec5SDimitry Andric 
164881ad6265SDimitry Andric   if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
164981ad6265SDimitry Andric     config->relrGlibc = true;
165081ad6265SDimitry Andric     config->relrPackDynRelocs = true;
165181ad6265SDimitry Andric   } else {
16520b57cec5SDimitry Andric     std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
16530b57cec5SDimitry Andric         getPackDynRelocs(args);
165481ad6265SDimitry Andric   }
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
16570b57cec5SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
16580b57cec5SDimitry Andric       error("--symbol-ordering-file and --call-graph-order-file "
16590b57cec5SDimitry Andric             "may not be used together");
1660bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) {
16610b57cec5SDimitry Andric       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
16620b57cec5SDimitry Andric       // Also need to disable CallGraphProfileSort to prevent
16630b57cec5SDimitry Andric       // LLD order symbols with CGProfile
16645f757f3fSDimitry Andric       config->callGraphProfileSort = CGProfileSortKind::None;
16650b57cec5SDimitry Andric     }
16660b57cec5SDimitry Andric   }
16670b57cec5SDimitry Andric 
166885868e8aSDimitry Andric   assert(config->versionDefinitions.empty());
166985868e8aSDimitry Andric   config->versionDefinitions.push_back(
16706e75b2fbSDimitry Andric       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
16716e75b2fbSDimitry Andric   config->versionDefinitions.push_back(
16726e75b2fbSDimitry Andric       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
167385868e8aSDimitry Andric 
16740b57cec5SDimitry Andric   // If --retain-symbol-file is used, we'll keep only the symbols listed in
16750b57cec5SDimitry Andric   // the file and discard all others.
16760b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
16776e75b2fbSDimitry Andric     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
167885868e8aSDimitry Andric         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1679bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
16800b57cec5SDimitry Andric       for (StringRef s : args::getLines(*buffer))
16816e75b2fbSDimitry Andric         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
168285868e8aSDimitry Andric             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
16830b57cec5SDimitry Andric   }
16840b57cec5SDimitry Andric 
16855ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
16865ffd83dbSDimitry Andric     StringRef pattern(arg->getValue());
16875ffd83dbSDimitry Andric     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
16885ffd83dbSDimitry Andric       config->warnBackrefsExclude.push_back(std::move(*pat));
16895ffd83dbSDimitry Andric     else
16905f757f3fSDimitry Andric       error(arg->getSpelling() + ": " + toString(pat.takeError()) + ": " +
16915f757f3fSDimitry Andric             pattern);
16925ffd83dbSDimitry Andric   }
16935ffd83dbSDimitry Andric 
1694349cc55cSDimitry Andric   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1695349cc55cSDimitry Andric   // which should be exported. For -shared, references to matched non-local
1696349cc55cSDimitry Andric   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1697349cc55cSDimitry Andric   // even if other options express a symbolic intention: -Bsymbolic,
16985ffd83dbSDimitry Andric   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
16990b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
17000b57cec5SDimitry Andric     config->dynamicList.push_back(
17015ffd83dbSDimitry Andric         {arg->getValue(), /*isExternCpp=*/false,
17025ffd83dbSDimitry Andric          /*hasWildcard=*/hasWildcard(arg->getValue())});
17030b57cec5SDimitry Andric 
1704349cc55cSDimitry Andric   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1705349cc55cSDimitry Andric   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1706349cc55cSDimitry Andric   // like semantics.
1707349cc55cSDimitry Andric   config->symbolic =
1708349cc55cSDimitry Andric       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1709349cc55cSDimitry Andric   for (auto *arg :
1710349cc55cSDimitry Andric        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1711bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1712349cc55cSDimitry Andric       readDynamicList(*buffer);
1713349cc55cSDimitry Andric 
17140b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_version_script))
1715bdd1243dSDimitry Andric     if (std::optional<std::string> path = searchScript(arg->getValue())) {
1716bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> buffer = readFile(*path))
17170b57cec5SDimitry Andric         readVersionScript(*buffer);
17180b57cec5SDimitry Andric     } else {
17190b57cec5SDimitry Andric       error(Twine("cannot find version script ") + arg->getValue());
17200b57cec5SDimitry Andric     }
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular
17240b57cec5SDimitry Andric // command line options, but computed based on other Config values.
17250b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details
17260b57cec5SDimitry Andric // of these values.
17270b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) {
17280b57cec5SDimitry Andric   ELFKind k = config->ekind;
17290b57cec5SDimitry Andric   uint16_t m = config->emachine;
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   config->copyRelocs = (config->relocatable || config->emitRelocs);
17320b57cec5SDimitry Andric   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
17330b57cec5SDimitry Andric   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
17340b57cec5SDimitry Andric   config->endianness = config->isLE ? endianness::little : endianness::big;
17350b57cec5SDimitry Andric   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
17360b57cec5SDimitry Andric   config->isPic = config->pie || config->shared;
17370b57cec5SDimitry Andric   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
17380b57cec5SDimitry Andric   config->wordsize = config->is64 ? 8 : 4;
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric   // ELF defines two different ways to store relocation addends as shown below:
17410b57cec5SDimitry Andric   //
17425ffd83dbSDimitry Andric   //  Rel: Addends are stored to the location where relocations are applied. It
17435ffd83dbSDimitry Andric   //  cannot pack the full range of addend values for all relocation types, but
17445ffd83dbSDimitry Andric   //  this only affects relocation types that we don't support emitting as
17455ffd83dbSDimitry Andric   //  dynamic relocations (see getDynRel).
17460b57cec5SDimitry Andric   //  Rela: Addends are stored as part of relocation entry.
17470b57cec5SDimitry Andric   //
17480b57cec5SDimitry Andric   // In other words, Rela makes it easy to read addends at the price of extra
17495ffd83dbSDimitry Andric   // 4 or 8 byte for each relocation entry.
17500b57cec5SDimitry Andric   //
17515ffd83dbSDimitry Andric   // We pick the format for dynamic relocations according to the psABI for each
17525ffd83dbSDimitry Andric   // processor, but a contrary choice can be made if the dynamic loader
17535ffd83dbSDimitry Andric   // supports.
17545ffd83dbSDimitry Andric   config->isRela = getIsRela(args);
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   // If the output uses REL relocations we must store the dynamic relocation
17570b57cec5SDimitry Andric   // addends to the output sections. We also store addends for RELA relocations
17580b57cec5SDimitry Andric   // if --apply-dynamic-relocs is used.
17590b57cec5SDimitry Andric   // We default to not writing the addends when using RELA relocations since
17600b57cec5SDimitry Andric   // any standard conforming tool can find it in r_addend.
17610b57cec5SDimitry Andric   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
17620b57cec5SDimitry Andric                                       OPT_no_apply_dynamic_relocs, false) ||
17630b57cec5SDimitry Andric                          !config->isRela;
1764fe6060f1SDimitry Andric   // Validation of dynamic relocation addends is on by default for assertions
17655f757f3fSDimitry Andric   // builds and disabled otherwise. This check is enabled when writeAddends is
17665f757f3fSDimitry Andric   // true.
1767fe6060f1SDimitry Andric #ifndef NDEBUG
17685f757f3fSDimitry Andric   bool checkDynamicRelocsDefault = true;
1769fe6060f1SDimitry Andric #else
1770fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = false;
1771fe6060f1SDimitry Andric #endif
1772fe6060f1SDimitry Andric   config->checkDynamicRelocs =
1773fe6060f1SDimitry Andric       args.hasFlag(OPT_check_dynamic_relocations,
1774fe6060f1SDimitry Andric                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
17750b57cec5SDimitry Andric   config->tocOptimize =
17760b57cec5SDimitry Andric       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1777e8d8bef9SDimitry Andric   config->pcRelOptimize =
1778e8d8bef9SDimitry Andric       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
17790b57cec5SDimitry Andric }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) {
17820b57cec5SDimitry Andric   if (s == "binary")
17830b57cec5SDimitry Andric     return true;
17840b57cec5SDimitry Andric   if (s == "elf" || s == "default")
17850b57cec5SDimitry Andric     return false;
1786349cc55cSDimitry Andric   error("unknown --format value: " + s +
17870b57cec5SDimitry Andric         " (supported formats: elf, default, binary)");
17880b57cec5SDimitry Andric   return false;
17890b57cec5SDimitry Andric }
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) {
1792e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files");
17930b57cec5SDimitry Andric   // For --{push,pop}-state.
17940b57cec5SDimitry Andric   std::vector<std::tuple<bool, bool, bool>> stack;
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   // Iterate over argv to process input files and positional arguments.
1797e8d8bef9SDimitry Andric   InputFile::isInGroup = false;
179881ad6265SDimitry Andric   bool hasInput = false;
17990b57cec5SDimitry Andric   for (auto *arg : args) {
18000b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
18010b57cec5SDimitry Andric     case OPT_library:
18020b57cec5SDimitry Andric       addLibrary(arg->getValue());
180381ad6265SDimitry Andric       hasInput = true;
18040b57cec5SDimitry Andric       break;
18050b57cec5SDimitry Andric     case OPT_INPUT:
18060b57cec5SDimitry Andric       addFile(arg->getValue(), /*withLOption=*/false);
180781ad6265SDimitry Andric       hasInput = true;
18080b57cec5SDimitry Andric       break;
18090b57cec5SDimitry Andric     case OPT_defsym: {
18100b57cec5SDimitry Andric       StringRef from;
18110b57cec5SDimitry Andric       StringRef to;
18120b57cec5SDimitry Andric       std::tie(from, to) = StringRef(arg->getValue()).split('=');
18130b57cec5SDimitry Andric       if (from.empty() || to.empty())
1814349cc55cSDimitry Andric         error("--defsym: syntax error: " + StringRef(arg->getValue()));
18150b57cec5SDimitry Andric       else
1816349cc55cSDimitry Andric         readDefsym(from, MemoryBufferRef(to, "--defsym"));
18170b57cec5SDimitry Andric       break;
18180b57cec5SDimitry Andric     }
18190b57cec5SDimitry Andric     case OPT_script:
1820bdd1243dSDimitry Andric       if (std::optional<std::string> path = searchScript(arg->getValue())) {
1821bdd1243dSDimitry Andric         if (std::optional<MemoryBufferRef> mb = readFile(*path))
18220b57cec5SDimitry Andric           readLinkerScript(*mb);
18230b57cec5SDimitry Andric         break;
18240b57cec5SDimitry Andric       }
18250b57cec5SDimitry Andric       error(Twine("cannot find linker script ") + arg->getValue());
18260b57cec5SDimitry Andric       break;
18270b57cec5SDimitry Andric     case OPT_as_needed:
18280b57cec5SDimitry Andric       config->asNeeded = true;
18290b57cec5SDimitry Andric       break;
18300b57cec5SDimitry Andric     case OPT_format:
18310b57cec5SDimitry Andric       config->formatBinary = isFormatBinary(arg->getValue());
18320b57cec5SDimitry Andric       break;
18330b57cec5SDimitry Andric     case OPT_no_as_needed:
18340b57cec5SDimitry Andric       config->asNeeded = false;
18350b57cec5SDimitry Andric       break;
18360b57cec5SDimitry Andric     case OPT_Bstatic:
18370b57cec5SDimitry Andric     case OPT_omagic:
18380b57cec5SDimitry Andric     case OPT_nmagic:
18390b57cec5SDimitry Andric       config->isStatic = true;
18400b57cec5SDimitry Andric       break;
18410b57cec5SDimitry Andric     case OPT_Bdynamic:
18420b57cec5SDimitry Andric       config->isStatic = false;
18430b57cec5SDimitry Andric       break;
18440b57cec5SDimitry Andric     case OPT_whole_archive:
18450b57cec5SDimitry Andric       inWholeArchive = true;
18460b57cec5SDimitry Andric       break;
18470b57cec5SDimitry Andric     case OPT_no_whole_archive:
18480b57cec5SDimitry Andric       inWholeArchive = false;
18490b57cec5SDimitry Andric       break;
18500b57cec5SDimitry Andric     case OPT_just_symbols:
1851bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1852fcaf7f86SDimitry Andric         files.push_back(createObjFile(*mb));
18530b57cec5SDimitry Andric         files.back()->justSymbols = true;
18540b57cec5SDimitry Andric       }
18550b57cec5SDimitry Andric       break;
185606c3fb27SDimitry Andric     case OPT_in_implib:
185706c3fb27SDimitry Andric       if (armCmseImpLib)
185806c3fb27SDimitry Andric         error("multiple CMSE import libraries not supported");
185906c3fb27SDimitry Andric       else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue()))
186006c3fb27SDimitry Andric         armCmseImpLib = createObjFile(*mb);
186106c3fb27SDimitry Andric       break;
18620b57cec5SDimitry Andric     case OPT_start_group:
18630b57cec5SDimitry Andric       if (InputFile::isInGroup)
18640b57cec5SDimitry Andric         error("nested --start-group");
18650b57cec5SDimitry Andric       InputFile::isInGroup = true;
18660b57cec5SDimitry Andric       break;
18670b57cec5SDimitry Andric     case OPT_end_group:
18680b57cec5SDimitry Andric       if (!InputFile::isInGroup)
18690b57cec5SDimitry Andric         error("stray --end-group");
18700b57cec5SDimitry Andric       InputFile::isInGroup = false;
18710b57cec5SDimitry Andric       ++InputFile::nextGroupId;
18720b57cec5SDimitry Andric       break;
18730b57cec5SDimitry Andric     case OPT_start_lib:
18740b57cec5SDimitry Andric       if (inLib)
18750b57cec5SDimitry Andric         error("nested --start-lib");
18760b57cec5SDimitry Andric       if (InputFile::isInGroup)
18770b57cec5SDimitry Andric         error("may not nest --start-lib in --start-group");
18780b57cec5SDimitry Andric       inLib = true;
18790b57cec5SDimitry Andric       InputFile::isInGroup = true;
18800b57cec5SDimitry Andric       break;
18810b57cec5SDimitry Andric     case OPT_end_lib:
18820b57cec5SDimitry Andric       if (!inLib)
18830b57cec5SDimitry Andric         error("stray --end-lib");
18840b57cec5SDimitry Andric       inLib = false;
18850b57cec5SDimitry Andric       InputFile::isInGroup = false;
18860b57cec5SDimitry Andric       ++InputFile::nextGroupId;
18870b57cec5SDimitry Andric       break;
18880b57cec5SDimitry Andric     case OPT_push_state:
18890b57cec5SDimitry Andric       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
18900b57cec5SDimitry Andric       break;
18910b57cec5SDimitry Andric     case OPT_pop_state:
18920b57cec5SDimitry Andric       if (stack.empty()) {
18930b57cec5SDimitry Andric         error("unbalanced --push-state/--pop-state");
18940b57cec5SDimitry Andric         break;
18950b57cec5SDimitry Andric       }
18960b57cec5SDimitry Andric       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
18970b57cec5SDimitry Andric       stack.pop_back();
18980b57cec5SDimitry Andric       break;
18990b57cec5SDimitry Andric     }
19000b57cec5SDimitry Andric   }
19010b57cec5SDimitry Andric 
190281ad6265SDimitry Andric   if (files.empty() && !hasInput && errorCount() == 0)
19030b57cec5SDimitry Andric     error("no input files");
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files.
19070b57cec5SDimitry Andric void LinkerDriver::inferMachineType() {
19080b57cec5SDimitry Andric   if (config->ekind != ELFNoneKind)
19090b57cec5SDimitry Andric     return;
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric   for (InputFile *f : files) {
19120b57cec5SDimitry Andric     if (f->ekind == ELFNoneKind)
19130b57cec5SDimitry Andric       continue;
19140b57cec5SDimitry Andric     config->ekind = f->ekind;
19150b57cec5SDimitry Andric     config->emachine = f->emachine;
19160b57cec5SDimitry Andric     config->osabi = f->osabi;
19170b57cec5SDimitry Andric     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
19180b57cec5SDimitry Andric     return;
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric   error("target emulation unknown: -m or at least one .o file required");
19210b57cec5SDimitry Andric }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by
19240b57cec5SDimitry Andric // each target.
19250b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) {
19260b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
19270b57cec5SDimitry Andric                                        target->defaultMaxPageSize);
1928972a253aSDimitry Andric   if (!isPowerOf2_64(val)) {
19290b57cec5SDimitry Andric     error("max-page-size: value isn't a power of 2");
1930972a253aSDimitry Andric     return target->defaultMaxPageSize;
1931972a253aSDimitry Andric   }
19320b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
19330b57cec5SDimitry Andric     if (val != target->defaultMaxPageSize)
19340b57cec5SDimitry Andric       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
19350b57cec5SDimitry Andric     return 1;
19360b57cec5SDimitry Andric   }
19370b57cec5SDimitry Andric   return val;
19380b57cec5SDimitry Andric }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by
19410b57cec5SDimitry Andric // each target.
19420b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) {
19430b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
19440b57cec5SDimitry Andric                                        target->defaultCommonPageSize);
1945972a253aSDimitry Andric   if (!isPowerOf2_64(val)) {
19460b57cec5SDimitry Andric     error("common-page-size: value isn't a power of 2");
1947972a253aSDimitry Andric     return target->defaultCommonPageSize;
1948972a253aSDimitry Andric   }
19490b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
19500b57cec5SDimitry Andric     if (val != target->defaultCommonPageSize)
19510b57cec5SDimitry Andric       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
19520b57cec5SDimitry Andric     return 1;
19530b57cec5SDimitry Andric   }
19540b57cec5SDimitry Andric   // commonPageSize can't be larger than maxPageSize.
19550b57cec5SDimitry Andric   if (val > config->maxPageSize)
19560b57cec5SDimitry Andric     val = config->maxPageSize;
19570b57cec5SDimitry Andric   return val;
19580b57cec5SDimitry Andric }
19590b57cec5SDimitry Andric 
1960349cc55cSDimitry Andric // Parses --image-base option.
1961bdd1243dSDimitry Andric static std::optional<uint64_t> getImageBase(opt::InputArgList &args) {
19620b57cec5SDimitry Andric   // Because we are using "Config->maxPageSize" here, this function has to be
19630b57cec5SDimitry Andric   // called after the variable is initialized.
19640b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_image_base);
19650b57cec5SDimitry Andric   if (!arg)
1966bdd1243dSDimitry Andric     return std::nullopt;
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric   StringRef s = arg->getValue();
19690b57cec5SDimitry Andric   uint64_t v;
19700b57cec5SDimitry Andric   if (!to_integer(s, v)) {
1971349cc55cSDimitry Andric     error("--image-base: number expected, but got " + s);
19720b57cec5SDimitry Andric     return 0;
19730b57cec5SDimitry Andric   }
19740b57cec5SDimitry Andric   if ((v % config->maxPageSize) != 0)
1975349cc55cSDimitry Andric     warn("--image-base: address isn't multiple of page size: " + s);
19760b57cec5SDimitry Andric   return v;
19770b57cec5SDimitry Andric }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`.
19800b57cec5SDimitry Andric // The library names may be delimited by commas or colons.
19810b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
19820b57cec5SDimitry Andric   DenseSet<StringRef> ret;
19830b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_libs)) {
19840b57cec5SDimitry Andric     StringRef s = arg->getValue();
19850b57cec5SDimitry Andric     for (;;) {
19860b57cec5SDimitry Andric       size_t pos = s.find_first_of(",:");
19870b57cec5SDimitry Andric       if (pos == StringRef::npos)
19880b57cec5SDimitry Andric         break;
19890b57cec5SDimitry Andric       ret.insert(s.substr(0, pos));
19900b57cec5SDimitry Andric       s = s.substr(pos + 1);
19910b57cec5SDimitry Andric     }
19920b57cec5SDimitry Andric     ret.insert(s);
19930b57cec5SDimitry Andric   }
19940b57cec5SDimitry Andric   return ret;
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric 
1997349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified
1998349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become
19990b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something.
20000b57cec5SDimitry Andric // A special library name "ALL" means all archive files.
20010b57cec5SDimitry Andric //
20020b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it.
20030b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) {
20040b57cec5SDimitry Andric   DenseSet<StringRef> libs = getExcludeLibs(args);
20050b57cec5SDimitry Andric   bool all = libs.count("ALL");
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   auto visit = [&](InputFile *file) {
200881ad6265SDimitry Andric     if (file->archiveName.empty() ||
200981ad6265SDimitry Andric         !(all || libs.count(path::filename(file->archiveName))))
201081ad6265SDimitry Andric       return;
201181ad6265SDimitry Andric     ArrayRef<Symbol *> symbols = file->getSymbols();
201281ad6265SDimitry Andric     if (isa<ELFFileBase>(file))
201381ad6265SDimitry Andric       symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
201481ad6265SDimitry Andric     for (Symbol *sym : symbols)
201581ad6265SDimitry Andric       if (!sym->isUndefined() && sym->file == file)
20160b57cec5SDimitry Andric         sym->versionId = VER_NDX_LOCAL;
20170b57cec5SDimitry Andric   };
20180b57cec5SDimitry Andric 
2019bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
20200b57cec5SDimitry Andric     visit(file);
20210b57cec5SDimitry Andric 
2022bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
20230b57cec5SDimitry Andric     visit(file);
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric 
20265ffd83dbSDimitry Andric // Force Sym to be entered in the output.
2027349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) {
20280b57cec5SDimitry Andric   // Since a symbol may not be used inside the program, LTO may
20290b57cec5SDimitry Andric   // eliminate it. Mark the symbol as "used" to prevent it.
20300b57cec5SDimitry Andric   sym->isUsedInRegularObj = true;
20310b57cec5SDimitry Andric 
2032349cc55cSDimitry Andric   if (!sym->isLazy())
2033349cc55cSDimitry Andric     return;
20344824e7fdSDimitry Andric   sym->extract();
2035349cc55cSDimitry Andric   if (!config->whyExtract.empty())
2036bdd1243dSDimitry Andric     ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);
20370b57cec5SDimitry Andric }
20380b57cec5SDimitry Andric 
2039480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u`
20400b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given
20410b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`.
20420b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) {
20430b57cec5SDimitry Andric   Expected<GlobPattern> pat = GlobPattern::create(arg);
20440b57cec5SDimitry Andric   if (!pat) {
20455f757f3fSDimitry Andric     error("--undefined-glob: " + toString(pat.takeError()) + ": " + arg);
20460b57cec5SDimitry Andric     return;
20470b57cec5SDimitry Andric   }
20480b57cec5SDimitry Andric 
20494824e7fdSDimitry Andric   // Calling sym->extract() in the loop is not safe because it may add new
20504824e7fdSDimitry Andric   // symbols to the symbol table, invalidating the current iterator.
20511fd87a68SDimitry Andric   SmallVector<Symbol *, 0> syms;
2052bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
205304eeddc0SDimitry Andric     if (!sym->isPlaceholder() && pat->match(sym->getName()))
20540b57cec5SDimitry Andric       syms.push_back(sym);
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric   for (Symbol *sym : syms)
2057349cc55cSDimitry Andric     handleUndefined(sym, "--undefined-glob");
20580b57cec5SDimitry Andric }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric static void handleLibcall(StringRef name) {
2061bdd1243dSDimitry Andric   Symbol *sym = symtab.find(name);
20627a6dacacSDimitry Andric   if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file))
20634824e7fdSDimitry Andric     sym->extract();
20640b57cec5SDimitry Andric }
20650b57cec5SDimitry Andric 
206681ad6265SDimitry Andric static void writeArchiveStats() {
206781ad6265SDimitry Andric   if (config->printArchiveStats.empty())
206881ad6265SDimitry Andric     return;
206981ad6265SDimitry Andric 
207081ad6265SDimitry Andric   std::error_code ec;
207106c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec);
207281ad6265SDimitry Andric   if (ec) {
207381ad6265SDimitry Andric     error("--print-archive-stats=: cannot open " + config->printArchiveStats +
207481ad6265SDimitry Andric           ": " + ec.message());
207581ad6265SDimitry Andric     return;
207681ad6265SDimitry Andric   }
207781ad6265SDimitry Andric 
207881ad6265SDimitry Andric   os << "members\textracted\tarchive\n";
207981ad6265SDimitry Andric 
208081ad6265SDimitry Andric   SmallVector<StringRef, 0> archives;
208181ad6265SDimitry Andric   DenseMap<CachedHashStringRef, unsigned> all, extracted;
2082bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
208381ad6265SDimitry Andric     if (file->archiveName.size())
208481ad6265SDimitry Andric       ++extracted[CachedHashStringRef(file->archiveName)];
2085bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
208681ad6265SDimitry Andric     if (file->archiveName.size())
208781ad6265SDimitry Andric       ++extracted[CachedHashStringRef(file->archiveName)];
2088bdd1243dSDimitry Andric   for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {
208981ad6265SDimitry Andric     unsigned &v = extracted[CachedHashString(f.first)];
209081ad6265SDimitry Andric     os << f.second << '\t' << v << '\t' << f.first << '\n';
209181ad6265SDimitry Andric     // If the archive occurs multiple times, other instances have a count of 0.
209281ad6265SDimitry Andric     v = 0;
209381ad6265SDimitry Andric   }
209481ad6265SDimitry Andric }
209581ad6265SDimitry Andric 
209681ad6265SDimitry Andric static void writeWhyExtract() {
209781ad6265SDimitry Andric   if (config->whyExtract.empty())
209881ad6265SDimitry Andric     return;
209981ad6265SDimitry Andric 
210081ad6265SDimitry Andric   std::error_code ec;
210106c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec);
210281ad6265SDimitry Andric   if (ec) {
210381ad6265SDimitry Andric     error("cannot open --why-extract= file " + config->whyExtract + ": " +
210481ad6265SDimitry Andric           ec.message());
210581ad6265SDimitry Andric     return;
210681ad6265SDimitry Andric   }
210781ad6265SDimitry Andric 
210881ad6265SDimitry Andric   os << "reference\textracted\tsymbol\n";
2109bdd1243dSDimitry Andric   for (auto &entry : ctx.whyExtractRecords) {
211081ad6265SDimitry Andric     os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
211181ad6265SDimitry Andric        << toString(std::get<2>(entry)) << '\n';
211281ad6265SDimitry Andric   }
211381ad6265SDimitry Andric }
211481ad6265SDimitry Andric 
211581ad6265SDimitry Andric static void reportBackrefs() {
2116bdd1243dSDimitry Andric   for (auto &ref : ctx.backwardReferences) {
211781ad6265SDimitry Andric     const Symbol &sym = *ref.first;
211881ad6265SDimitry Andric     std::string to = toString(ref.second.second);
211981ad6265SDimitry Andric     // Some libraries have known problems and can cause noise. Filter them out
212081ad6265SDimitry Andric     // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
212181ad6265SDimitry Andric     // *.o or (archive member) *.a(*.o).
212281ad6265SDimitry Andric     bool exclude = false;
212381ad6265SDimitry Andric     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
212481ad6265SDimitry Andric       if (pat.match(to)) {
212581ad6265SDimitry Andric         exclude = true;
212681ad6265SDimitry Andric         break;
212781ad6265SDimitry Andric       }
212881ad6265SDimitry Andric     if (!exclude)
212981ad6265SDimitry Andric       warn("backward reference detected: " + sym.getName() + " in " +
213081ad6265SDimitry Andric            toString(ref.second.first) + " refers to " + to);
213181ad6265SDimitry Andric   }
213281ad6265SDimitry Andric }
213381ad6265SDimitry Andric 
2134e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a
2135e8d8bef9SDimitry Andric // file at a given path with the following contents:
2136e8d8bef9SDimitry Andric //
2137e8d8bef9SDimitry Andric //   <output-file>: <input-file> ...
2138e8d8bef9SDimitry Andric //
2139e8d8bef9SDimitry Andric //   <input-file>:
2140e8d8bef9SDimitry Andric //
2141e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file>
2142e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a
2143e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write
2144e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is
2145e8d8bef9SDimitry Andric // removed.
2146e8d8bef9SDimitry Andric //
2147e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend
2148e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why.
2149e8d8bef9SDimitry Andric //
2150e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final
2151e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you
2152e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc)
2153e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system
2154e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a
2155e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make
2156e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies
2157e8d8bef9SDimitry Andric // easily.
2158e8d8bef9SDimitry Andric static void writeDependencyFile() {
2159e8d8bef9SDimitry Andric   std::error_code ec;
216006c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec);
2161e8d8bef9SDimitry Andric   if (ec) {
2162e8d8bef9SDimitry Andric     error("cannot open " + config->dependencyFile + ": " + ec.message());
2163e8d8bef9SDimitry Andric     return;
2164e8d8bef9SDimitry Andric   }
2165e8d8bef9SDimitry Andric 
2166e8d8bef9SDimitry Andric   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
2167e8d8bef9SDimitry Andric   // * A space is escaped by a backslash which itself must be escaped.
2168e8d8bef9SDimitry Andric   // * A hash sign is escaped by a single backslash.
2169e8d8bef9SDimitry Andric   // * $ is escapes as $$.
2170e8d8bef9SDimitry Andric   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
2171e8d8bef9SDimitry Andric     llvm::SmallString<256> nativePath;
2172e8d8bef9SDimitry Andric     llvm::sys::path::native(filename.str(), nativePath);
2173e8d8bef9SDimitry Andric     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
2174e8d8bef9SDimitry Andric     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
2175e8d8bef9SDimitry Andric       if (nativePath[i] == '#') {
2176e8d8bef9SDimitry Andric         os << '\\';
2177e8d8bef9SDimitry Andric       } else if (nativePath[i] == ' ') {
2178e8d8bef9SDimitry Andric         os << '\\';
2179e8d8bef9SDimitry Andric         unsigned j = i;
2180e8d8bef9SDimitry Andric         while (j > 0 && nativePath[--j] == '\\')
2181e8d8bef9SDimitry Andric           os << '\\';
2182e8d8bef9SDimitry Andric       } else if (nativePath[i] == '$') {
2183e8d8bef9SDimitry Andric         os << '$';
2184e8d8bef9SDimitry Andric       }
2185e8d8bef9SDimitry Andric       os << nativePath[i];
2186e8d8bef9SDimitry Andric     }
2187e8d8bef9SDimitry Andric   };
2188e8d8bef9SDimitry Andric 
2189e8d8bef9SDimitry Andric   os << config->outputFile << ":";
2190e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
2191e8d8bef9SDimitry Andric     os << " \\\n ";
2192e8d8bef9SDimitry Andric     printFilename(os, path);
2193e8d8bef9SDimitry Andric   }
2194e8d8bef9SDimitry Andric   os << "\n";
2195e8d8bef9SDimitry Andric 
2196e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
2197e8d8bef9SDimitry Andric     os << "\n";
2198e8d8bef9SDimitry Andric     printFilename(os, path);
2199e8d8bef9SDimitry Andric     os << ":\n";
2200e8d8bef9SDimitry Andric   }
2201e8d8bef9SDimitry Andric }
2202e8d8bef9SDimitry Andric 
22030b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections.
22040b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a
22050b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any
22060b57cec5SDimitry Andric // symbols of type CommonSymbol.
22070b57cec5SDimitry Andric static void replaceCommonSymbols() {
2208e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Replace common symbols");
2209bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles) {
22100eae32dcSDimitry Andric     if (!file->hasCommonSyms)
22110eae32dcSDimitry Andric       continue;
22120eae32dcSDimitry Andric     for (Symbol *sym : file->getGlobalSymbols()) {
22130b57cec5SDimitry Andric       auto *s = dyn_cast<CommonSymbol>(sym);
22140b57cec5SDimitry Andric       if (!s)
2215480093f4SDimitry Andric         continue;
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric       auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
22180b57cec5SDimitry Andric       bss->file = s->file;
2219bdd1243dSDimitry Andric       ctx.inputSections.push_back(bss);
2220bdd1243dSDimitry Andric       Defined(s->file, StringRef(), s->binding, s->stOther, s->type,
2221bdd1243dSDimitry Andric               /*value=*/0, s->size, bss)
2222bdd1243dSDimitry Andric           .overwrite(*s);
2223480093f4SDimitry Andric     }
22240b57cec5SDimitry Andric   }
22250eae32dcSDimitry Andric }
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the
22280b57cec5SDimitry Andric // keepUnique flag on the section if appropriate.
22290b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
22300b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
22310b57cec5SDimitry Andric     if (d->section)
22320b57cec5SDimitry Andric       // We don't need to keep text sections unique under --icf=all even if they
22330b57cec5SDimitry Andric       // are address-significant.
22340b57cec5SDimitry Andric       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
22350b57cec5SDimitry Andric         d->section->keepUnique = true;
22360b57cec5SDimitry Andric }
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol>
22390b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are
22400b57cec5SDimitry Andric // ineligible for ICF.
22410b57cec5SDimitry Andric template <class ELFT>
22420b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) {
22430b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_keep_unique)) {
22440b57cec5SDimitry Andric     StringRef name = arg->getValue();
2245bdd1243dSDimitry Andric     auto *d = dyn_cast_or_null<Defined>(symtab.find(name));
22460b57cec5SDimitry Andric     if (!d || !d->section) {
22470b57cec5SDimitry Andric       warn("could not find symbol " + name + " to keep unique");
22480b57cec5SDimitry Andric       continue;
22490b57cec5SDimitry Andric     }
22500b57cec5SDimitry Andric     d->section->keepUnique = true;
22510b57cec5SDimitry Andric   }
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric   // --icf=all --ignore-data-address-equality means that we can ignore
22540b57cec5SDimitry Andric   // the dynsym and address-significance tables entirely.
22550b57cec5SDimitry Andric   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
22560b57cec5SDimitry Andric     return;
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric   // Symbols in the dynsym could be address-significant in other executables
22590b57cec5SDimitry Andric   // or DSOs, so we conservatively mark them as address-significant.
2260bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
22610b57cec5SDimitry Andric     if (sym->includeInDynsym())
22620b57cec5SDimitry Andric       markAddrsig(sym);
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
22650b57cec5SDimitry Andric   // referenced symbol as address-significant.
2266bdd1243dSDimitry Andric   for (InputFile *f : ctx.objectFiles) {
22670b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(f);
22680b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
22690b57cec5SDimitry Andric     if (obj->addrsigSec) {
22700b57cec5SDimitry Andric       ArrayRef<uint8_t> contents =
2271e8d8bef9SDimitry Andric           check(obj->getObj().getSectionContents(*obj->addrsigSec));
22720b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
22730b57cec5SDimitry Andric       while (cur != contents.end()) {
22740b57cec5SDimitry Andric         unsigned size;
22755f757f3fSDimitry Andric         const char *err = nullptr;
22760b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
22770b57cec5SDimitry Andric         if (err)
22780b57cec5SDimitry Andric           fatal(toString(f) + ": could not decode addrsig section: " + err);
22790b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
22800b57cec5SDimitry Andric         cur += size;
22810b57cec5SDimitry Andric       }
22820b57cec5SDimitry Andric     } else {
22830b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
22840b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
22850b57cec5SDimitry Andric       for (Symbol *s : syms)
22860b57cec5SDimitry Andric         markAddrsig(s);
22870b57cec5SDimitry Andric     }
22880b57cec5SDimitry Andric   }
22890b57cec5SDimitry Andric }
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections
22920b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See
22930b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions.
22940b57cec5SDimitry Andric template <typename ELFT>
22950b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) {
22960b57cec5SDimitry Andric   // Read the relocation that refers to the partition's entry point symbol.
22970b57cec5SDimitry Andric   Symbol *sym;
2298349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2299349cc55cSDimitry Andric   if (rels.areRelocsRel())
2300349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
23010b57cec5SDimitry Andric   else
2302349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
23030b57cec5SDimitry Andric   if (!isa<Defined>(sym) || !sym->includeInDynsym())
23040b57cec5SDimitry Andric     return;
23050b57cec5SDimitry Andric 
2306bdd1243dSDimitry Andric   StringRef partName = reinterpret_cast<const char *>(s->content().data());
23070b57cec5SDimitry Andric   for (Partition &part : partitions) {
23080b57cec5SDimitry Andric     if (part.name == partName) {
23090b57cec5SDimitry Andric       sym->partition = part.getNumber();
23100b57cec5SDimitry Andric       return;
23110b57cec5SDimitry Andric     }
23120b57cec5SDimitry Andric   }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric   // Forbid partitions from being used on incompatible targets, and forbid them
23150b57cec5SDimitry Andric   // from being used together with various linker features that assume a single
23160b57cec5SDimitry Andric   // set of output sections.
23170b57cec5SDimitry Andric   if (script->hasSectionsCommand)
23180b57cec5SDimitry Andric     error(toString(s->file) +
23190b57cec5SDimitry Andric           ": partitions cannot be used with the SECTIONS command");
23200b57cec5SDimitry Andric   if (script->hasPhdrsCommands())
23210b57cec5SDimitry Andric     error(toString(s->file) +
23220b57cec5SDimitry Andric           ": partitions cannot be used with the PHDRS command");
23230b57cec5SDimitry Andric   if (!config->sectionStartMap.empty())
23240b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used with "
23250b57cec5SDimitry Andric                               "--section-start, -Ttext, -Tdata or -Tbss");
23260b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
23270b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used on this target");
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   // Impose a limit of no more than 254 partitions. This limit comes from the
23300b57cec5SDimitry Andric   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
23310b57cec5SDimitry Andric   // the amount of space devoted to the partition number in RankFlags.
23320b57cec5SDimitry Andric   if (partitions.size() == 254)
23330b57cec5SDimitry Andric     fatal("may not have more than 254 partitions");
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric   partitions.emplace_back();
23360b57cec5SDimitry Andric   Partition &newPart = partitions.back();
23370b57cec5SDimitry Andric   newPart.name = partName;
23380b57cec5SDimitry Andric   sym->partition = newPart.getNumber();
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric 
2341fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name,
2342fe6060f1SDimitry Andric                                   uint8_t binding = STB_GLOBAL) {
23437a6dacacSDimitry Andric   return symtab.addSymbol(
23447a6dacacSDimitry Andric       Undefined{ctx.internalFile, name, binding, STV_DEFAULT, 0});
23455ffd83dbSDimitry Andric }
23465ffd83dbSDimitry Andric 
234704eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) {
234804eeddc0SDimitry Andric   // With --thinlto-index-only, all buffers are nearly unused from now on
234904eeddc0SDimitry Andric   // (except symbol/section names used by infrequent passes). Mark input file
235004eeddc0SDimitry Andric   // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
235104eeddc0SDimitry Andric   // thin link, saving memory.
235204eeddc0SDimitry Andric   if (skipLinkedOutput) {
2353bdd1243dSDimitry Andric     for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
235404eeddc0SDimitry Andric       mb.dontNeedIfMmap();
235504eeddc0SDimitry Andric     return;
235604eeddc0SDimitry Andric   }
235704eeddc0SDimitry Andric 
235804eeddc0SDimitry Andric   // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
235904eeddc0SDimitry Andric   DenseSet<const char *> bufs;
2360bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
236104eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
2362bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.lazyBitcodeFiles)
236304eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
2364bdd1243dSDimitry Andric   for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
236504eeddc0SDimitry Andric     if (bufs.count(mb.getBufferStart()))
236604eeddc0SDimitry Andric       mb.dontNeedIfMmap();
236704eeddc0SDimitry Andric }
236804eeddc0SDimitry Andric 
23690b57cec5SDimitry Andric // This function is where all the optimizations of link-time
23700b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are
23710b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format.
23720b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files
23730b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results.
23740b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to
23750b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization.
237604eeddc0SDimitry Andric template <class ELFT>
237704eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
23785ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("LTO");
23790b57cec5SDimitry Andric   // Compile bitcode files and replace bitcode symbols.
23800b57cec5SDimitry Andric   lto.reset(new BitcodeCompiler);
2381bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
23820b57cec5SDimitry Andric     lto->add(*file);
23830b57cec5SDimitry Andric 
2384bdd1243dSDimitry Andric   if (!ctx.bitcodeFiles.empty())
238504eeddc0SDimitry Andric     markBuffersAsDontNeed(skipLinkedOutput);
238604eeddc0SDimitry Andric 
23870b57cec5SDimitry Andric   for (InputFile *file : lto->compile()) {
23880b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
23890b57cec5SDimitry Andric     obj->parse(/*ignoreComdats=*/true);
23905ffd83dbSDimitry Andric 
23915ffd83dbSDimitry Andric     // Parse '@' in symbol names for non-relocatable output.
23925ffd83dbSDimitry Andric     if (!config->relocatable)
23930b57cec5SDimitry Andric       for (Symbol *sym : obj->getGlobalSymbols())
239404eeddc0SDimitry Andric         if (sym->hasVersionSuffix)
23950b57cec5SDimitry Andric           sym->parseSymbolVersion();
2396bdd1243dSDimitry Andric     ctx.objectFiles.push_back(obj);
23970b57cec5SDimitry Andric   }
23980b57cec5SDimitry Andric }
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write
2401349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all
2402e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2403e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original
2404e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your
24050b57cec5SDimitry Andric // wrapper.
24060b57cec5SDimitry Andric //
2407349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option.
24080b57cec5SDimitry Andric struct WrappedSymbol {
24090b57cec5SDimitry Andric   Symbol *sym;
24100b57cec5SDimitry Andric   Symbol *real;
24110b57cec5SDimitry Andric   Symbol *wrap;
24120b57cec5SDimitry Andric };
24130b57cec5SDimitry Andric 
2414349cc55cSDimitry Andric // Handles --wrap option.
24150b57cec5SDimitry Andric //
24160b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem
24170b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so
24180b57cec5SDimitry Andric // that LTO won't eliminate them.
24190b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
24200b57cec5SDimitry Andric   std::vector<WrappedSymbol> v;
24210b57cec5SDimitry Andric   DenseSet<StringRef> seen;
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wrap)) {
24240b57cec5SDimitry Andric     StringRef name = arg->getValue();
24250b57cec5SDimitry Andric     if (!seen.insert(name).second)
24260b57cec5SDimitry Andric       continue;
24270b57cec5SDimitry Andric 
2428bdd1243dSDimitry Andric     Symbol *sym = symtab.find(name);
24290b57cec5SDimitry Andric     if (!sym)
24300b57cec5SDimitry Andric       continue;
24310b57cec5SDimitry Andric 
2432fe6060f1SDimitry Andric     Symbol *wrap =
243304eeddc0SDimitry Andric         addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2434bdd1243dSDimitry Andric 
2435bdd1243dSDimitry Andric     // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
2436bdd1243dSDimitry Andric     // processing __wrap_ as that may have referenced __real_.
2437bdd1243dSDimitry Andric     StringRef realName = saver().save("__real_" + name);
2438bdd1243dSDimitry Andric     if (symtab.find(realName))
2439bdd1243dSDimitry Andric       addUnusedUndefined(name, sym->binding);
2440bdd1243dSDimitry Andric 
2441bdd1243dSDimitry Andric     Symbol *real = addUnusedUndefined(realName);
24420b57cec5SDimitry Andric     v.push_back({sym, real, wrap});
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric     // We want to tell LTO not to inline symbols to be overwritten
24450b57cec5SDimitry Andric     // because LTO doesn't know the final symbol contents after renaming.
244681ad6265SDimitry Andric     real->scriptDefined = true;
244781ad6265SDimitry Andric     sym->scriptDefined = true;
24480b57cec5SDimitry Andric 
244981ad6265SDimitry Andric     // If a symbol is referenced in any object file, bitcode file or shared
245081ad6265SDimitry Andric     // object, mark its redirection target (foo for __real_foo and __wrap_foo
245181ad6265SDimitry Andric     // for foo) as referenced after redirection, which will be used to tell LTO
245281ad6265SDimitry Andric     // to not eliminate the redirection target. If the object file defining the
245381ad6265SDimitry Andric     // symbol also references it, we cannot easily distinguish the case from
245481ad6265SDimitry Andric     // cases where the symbol is not referenced. Retain the redirection target
245581ad6265SDimitry Andric     // in this case because we choose to wrap symbol references regardless of
245681ad6265SDimitry Andric     // whether the symbol is defined
2457e8d8bef9SDimitry Andric     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
245881ad6265SDimitry Andric     if (real->referenced || real->isDefined())
245981ad6265SDimitry Andric       sym->referencedAfterWrap = true;
2460e8d8bef9SDimitry Andric     if (sym->referenced || sym->isDefined())
246181ad6265SDimitry Andric       wrap->referencedAfterWrap = true;
24620b57cec5SDimitry Andric   }
24630b57cec5SDimitry Andric   return v;
24640b57cec5SDimitry Andric }
24650b57cec5SDimitry Andric 
2466bdd1243dSDimitry Andric static void combineVersionedSymbol(Symbol &sym,
2467bdd1243dSDimitry Andric                                    DenseMap<Symbol *, Symbol *> &map) {
2468bdd1243dSDimitry Andric   const char *suffix1 = sym.getVersionSuffix();
2469bdd1243dSDimitry Andric   if (suffix1[0] != '@' || suffix1[1] == '@')
2470bdd1243dSDimitry Andric     return;
2471bdd1243dSDimitry Andric 
2472bdd1243dSDimitry Andric   // Check the existing symbol foo. We have two special cases to handle:
2473bdd1243dSDimitry Andric   //
2474bdd1243dSDimitry Andric   // * There is a definition of foo@v1 and foo@@v1.
2475bdd1243dSDimitry Andric   // * There is a definition of foo@v1 and foo.
2476bdd1243dSDimitry Andric   Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName()));
2477bdd1243dSDimitry Andric   if (!sym2)
2478bdd1243dSDimitry Andric     return;
2479bdd1243dSDimitry Andric   const char *suffix2 = sym2->getVersionSuffix();
2480bdd1243dSDimitry Andric   if (suffix2[0] == '@' && suffix2[1] == '@' &&
2481bdd1243dSDimitry Andric       strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2482bdd1243dSDimitry Andric     // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2483bdd1243dSDimitry Andric     map.try_emplace(&sym, sym2);
2484bdd1243dSDimitry Andric     // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2485bdd1243dSDimitry Andric     // duplicate definition error.
2486bdd1243dSDimitry Andric     if (sym.isDefined()) {
2487bdd1243dSDimitry Andric       sym2->checkDuplicate(cast<Defined>(sym));
2488bdd1243dSDimitry Andric       sym2->resolve(cast<Defined>(sym));
2489bdd1243dSDimitry Andric     } else if (sym.isUndefined()) {
2490bdd1243dSDimitry Andric       sym2->resolve(cast<Undefined>(sym));
2491bdd1243dSDimitry Andric     } else {
2492bdd1243dSDimitry Andric       sym2->resolve(cast<SharedSymbol>(sym));
2493bdd1243dSDimitry Andric     }
2494bdd1243dSDimitry Andric     // Eliminate foo@v1 from the symbol table.
2495bdd1243dSDimitry Andric     sym.symbolKind = Symbol::PlaceholderKind;
2496bdd1243dSDimitry Andric     sym.isUsedInRegularObj = false;
2497bdd1243dSDimitry Andric   } else if (auto *sym1 = dyn_cast<Defined>(&sym)) {
2498bdd1243dSDimitry Andric     if (sym2->versionId > VER_NDX_GLOBAL
2499bdd1243dSDimitry Andric             ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2500bdd1243dSDimitry Andric             : sym1->section == sym2->section && sym1->value == sym2->value) {
2501bdd1243dSDimitry Andric       // Due to an assembler design flaw, if foo is defined, .symver foo,
2502bdd1243dSDimitry Andric       // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2503bdd1243dSDimitry Andric       // different version, GNU ld makes foo@v1 canonical and eliminates
2504bdd1243dSDimitry Andric       // foo. Emulate its behavior, otherwise we would have foo or foo@@v1
2505bdd1243dSDimitry Andric       // beside foo@v1. foo@v1 and foo combining does not apply if they are
2506bdd1243dSDimitry Andric       // not defined in the same place.
2507bdd1243dSDimitry Andric       map.try_emplace(sym2, &sym);
2508bdd1243dSDimitry Andric       sym2->symbolKind = Symbol::PlaceholderKind;
2509bdd1243dSDimitry Andric       sym2->isUsedInRegularObj = false;
2510bdd1243dSDimitry Andric     }
2511bdd1243dSDimitry Andric   }
2512bdd1243dSDimitry Andric }
2513bdd1243dSDimitry Andric 
2514349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
25150b57cec5SDimitry Andric //
25160b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table
25170b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers,
25180b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line.
2519e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2520e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Redirect symbols");
25210b57cec5SDimitry Andric   DenseMap<Symbol *, Symbol *> map;
25220b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped) {
25230b57cec5SDimitry Andric     map[w.sym] = w.wrap;
25240b57cec5SDimitry Andric     map[w.real] = w.sym;
25250b57cec5SDimitry Andric   }
2526e8d8bef9SDimitry Andric 
2527bdd1243dSDimitry Andric   // If there are version definitions (versionDefinitions.size() > 2), enumerate
2528bdd1243dSDimitry Andric   // symbols with a non-default version (foo@v1) and check whether it should be
2529bdd1243dSDimitry Andric   // combined with foo or foo@@v1.
2530bdd1243dSDimitry Andric   if (config->versionDefinitions.size() > 2)
2531bdd1243dSDimitry Andric     for (Symbol *sym : symtab.getSymbols())
2532bdd1243dSDimitry Andric       if (sym->hasVersionSuffix)
2533bdd1243dSDimitry Andric         combineVersionedSymbol(*sym, map);
2534e8d8bef9SDimitry Andric 
2535e8d8bef9SDimitry Andric   if (map.empty())
2536e8d8bef9SDimitry Andric     return;
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric   // Update pointers in input files.
2539bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
25400eae32dcSDimitry Andric     for (Symbol *&sym : file->getMutableGlobalSymbols())
25410eae32dcSDimitry Andric       if (Symbol *s = map.lookup(sym))
25420eae32dcSDimitry Andric         sym = s;
25430b57cec5SDimitry Andric   });
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric   // Update pointers in the symbol table.
25460b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped)
2547bdd1243dSDimitry Andric     symtab.wrap(w.sym, w.real, w.wrap);
25480b57cec5SDimitry Andric }
25490b57cec5SDimitry Andric 
25500eae32dcSDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features,
25510eae32dcSDimitry Andric                                          uint32_t mask, const Twine &report) {
25520eae32dcSDimitry Andric   if (!(features & mask)) {
25530eae32dcSDimitry Andric     if (config == "error")
25540eae32dcSDimitry Andric       error(report);
25550eae32dcSDimitry Andric     else if (config == "warning")
25560eae32dcSDimitry Andric       warn(report);
25570eae32dcSDimitry Andric   }
25580eae32dcSDimitry Andric }
25590eae32dcSDimitry Andric 
2560bdd1243dSDimitry Andric // To enable CET (x86's hardware-assisted control flow enforcement), each
25610b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled
25620b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible
25630b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible
25640b57cec5SDimitry Andric // with CET.
25650b57cec5SDimitry Andric //
25660b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar
25670b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
25681fd87a68SDimitry Andric static uint32_t getAndFeatures() {
25690b57cec5SDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
25700b57cec5SDimitry Andric       config->emachine != EM_AARCH64)
25710b57cec5SDimitry Andric     return 0;
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric   uint32_t ret = -1;
2574bdd1243dSDimitry Andric   for (ELFFileBase *f : ctx.objectFiles) {
25751fd87a68SDimitry Andric     uint32_t features = f->andFeatures;
25760eae32dcSDimitry Andric 
25770eae32dcSDimitry Andric     checkAndReportMissingFeature(
25780eae32dcSDimitry Andric         config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
25790eae32dcSDimitry Andric         toString(f) + ": -z bti-report: file does not have "
25800eae32dcSDimitry Andric                       "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
25810eae32dcSDimitry Andric 
25820eae32dcSDimitry Andric     checkAndReportMissingFeature(
25830eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
25840eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
25850eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_IBT property");
25860eae32dcSDimitry Andric 
25870eae32dcSDimitry Andric     checkAndReportMissingFeature(
25880eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
25890eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
25900eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
25910eae32dcSDimitry Andric 
25925ffd83dbSDimitry Andric     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
25930eae32dcSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
25940eae32dcSDimitry Andric       if (config->zBtiReport == "none")
25955ffd83dbSDimitry Andric         warn(toString(f) + ": -z force-bti: file does not have "
25965ffd83dbSDimitry Andric                            "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2597480093f4SDimitry Andric     } else if (config->zForceIbt &&
2598480093f4SDimitry Andric                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
25990eae32dcSDimitry Andric       if (config->zCetReport == "none")
2600480093f4SDimitry Andric         warn(toString(f) + ": -z force-ibt: file does not have "
2601480093f4SDimitry Andric                            "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2602480093f4SDimitry Andric       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2603480093f4SDimitry Andric     }
26045ffd83dbSDimitry Andric     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
26055ffd83dbSDimitry Andric       warn(toString(f) + ": -z pac-plt: file does not have "
26065ffd83dbSDimitry Andric                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
26075ffd83dbSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
26085ffd83dbSDimitry Andric     }
26090b57cec5SDimitry Andric     ret &= features;
26100b57cec5SDimitry Andric   }
26110b57cec5SDimitry Andric 
2612480093f4SDimitry Andric   // Force enable Shadow Stack.
2613480093f4SDimitry Andric   if (config->zShstk)
2614480093f4SDimitry Andric     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric   return ret;
26170b57cec5SDimitry Andric }
26180b57cec5SDimitry Andric 
2619bdd1243dSDimitry Andric static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {
2620bdd1243dSDimitry Andric   switch (file->ekind) {
262181ad6265SDimitry Andric   case ELF32LEKind:
2622bdd1243dSDimitry Andric     cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
262381ad6265SDimitry Andric     break;
262481ad6265SDimitry Andric   case ELF32BEKind:
2625bdd1243dSDimitry Andric     cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
262681ad6265SDimitry Andric     break;
262781ad6265SDimitry Andric   case ELF64LEKind:
2628bdd1243dSDimitry Andric     cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
262981ad6265SDimitry Andric     break;
263081ad6265SDimitry Andric   case ELF64BEKind:
2631bdd1243dSDimitry Andric     cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
263281ad6265SDimitry Andric     break;
263381ad6265SDimitry Andric   default:
263481ad6265SDimitry Andric     llvm_unreachable("");
263581ad6265SDimitry Andric   }
263681ad6265SDimitry Andric }
263781ad6265SDimitry Andric 
263881ad6265SDimitry Andric static void postParseObjectFile(ELFFileBase *file) {
2639bdd1243dSDimitry Andric   switch (file->ekind) {
264081ad6265SDimitry Andric   case ELF32LEKind:
264181ad6265SDimitry Andric     cast<ObjFile<ELF32LE>>(file)->postParse();
264281ad6265SDimitry Andric     break;
264381ad6265SDimitry Andric   case ELF32BEKind:
264481ad6265SDimitry Andric     cast<ObjFile<ELF32BE>>(file)->postParse();
264581ad6265SDimitry Andric     break;
264681ad6265SDimitry Andric   case ELF64LEKind:
264781ad6265SDimitry Andric     cast<ObjFile<ELF64LE>>(file)->postParse();
264881ad6265SDimitry Andric     break;
264981ad6265SDimitry Andric   case ELF64BEKind:
265081ad6265SDimitry Andric     cast<ObjFile<ELF64BE>>(file)->postParse();
265181ad6265SDimitry Andric     break;
265281ad6265SDimitry Andric   default:
265381ad6265SDimitry Andric     llvm_unreachable("");
265481ad6265SDimitry Andric   }
265581ad6265SDimitry Andric }
265681ad6265SDimitry Andric 
26570b57cec5SDimitry Andric // Do actual linking. Note that when this function is called,
26580b57cec5SDimitry Andric // all linker scripts have already been parsed.
26591fd87a68SDimitry Andric void LinkerDriver::link(opt::InputArgList &args) {
26605ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2661349cc55cSDimitry Andric   // If a --hash-style option was not given, set to a default value,
26620b57cec5SDimitry Andric   // which varies depending on the target.
26630b57cec5SDimitry Andric   if (!args.hasArg(OPT_hash_style)) {
26640b57cec5SDimitry Andric     if (config->emachine == EM_MIPS)
26650b57cec5SDimitry Andric       config->sysvHash = true;
26660b57cec5SDimitry Andric     else
26670b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
26680b57cec5SDimitry Andric   }
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric   // Default output filename is "a.out" by the Unix tradition.
26710b57cec5SDimitry Andric   if (config->outputFile.empty())
26720b57cec5SDimitry Andric     config->outputFile = "a.out";
26730b57cec5SDimitry Andric 
26740b57cec5SDimitry Andric   // Fail early if the output file or map file is not writable. If a user has a
26750b57cec5SDimitry Andric   // long link, e.g. due to a large LTO link, they do not wish to run it and
26760b57cec5SDimitry Andric   // find that it failed because there was a mistake in their command-line.
2677e8d8bef9SDimitry Andric   {
2678e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Create output files");
26790b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->outputFile))
2680e8d8bef9SDimitry Andric       error("cannot open output file " + config->outputFile + ": " +
2681e8d8bef9SDimitry Andric             e.message());
26820b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->mapFile))
26830b57cec5SDimitry Andric       error("cannot open map file " + config->mapFile + ": " + e.message());
2684349cc55cSDimitry Andric     if (auto e = tryCreateFile(config->whyExtract))
2685349cc55cSDimitry Andric       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2686349cc55cSDimitry Andric             e.message());
2687e8d8bef9SDimitry Andric   }
26880b57cec5SDimitry Andric   if (errorCount())
26890b57cec5SDimitry Andric     return;
26900b57cec5SDimitry Andric 
26910b57cec5SDimitry Andric   // Use default entry point name if no name was given via the command
26920b57cec5SDimitry Andric   // line nor linker scripts. For some reason, MIPS entry point name is
26930b57cec5SDimitry Andric   // different from others.
26940b57cec5SDimitry Andric   config->warnMissingEntry =
26950b57cec5SDimitry Andric       (!config->entry.empty() || (!config->shared && !config->relocatable));
26960b57cec5SDimitry Andric   if (config->entry.empty() && !config->relocatable)
26970b57cec5SDimitry Andric     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   // Handle --trace-symbol.
27000b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_trace_symbol))
2701bdd1243dSDimitry Andric     symtab.insert(arg->getValue())->traced = true;
27020b57cec5SDimitry Andric 
27037a6dacacSDimitry Andric   ctx.internalFile = createInternalFile("<internal>");
27047a6dacacSDimitry Andric 
27055ffd83dbSDimitry Andric   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
27064824e7fdSDimitry Andric   // -u foo a.a b.so will extract a.a.
27075ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
2708e8d8bef9SDimitry Andric     addUnusedUndefined(name)->referenced = true;
27095ffd83dbSDimitry Andric 
27100b57cec5SDimitry Andric   // Add all files to the symbol table. This will add almost all
27110b57cec5SDimitry Andric   // symbols that we need to the symbol table. This process might
27120b57cec5SDimitry Andric   // add files to the link, via autolinking, these files are always
27130b57cec5SDimitry Andric   // appended to the Files vector.
27145ffd83dbSDimitry Andric   {
27155ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("Parse input files");
2716e8d8bef9SDimitry Andric     for (size_t i = 0; i < files.size(); ++i) {
2717e8d8bef9SDimitry Andric       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
27180b57cec5SDimitry Andric       parseFile(files[i]);
27195ffd83dbSDimitry Andric     }
272006c3fb27SDimitry Andric     if (armCmseImpLib)
272106c3fb27SDimitry Andric       parseArmCMSEImportLib(*armCmseImpLib);
2722e8d8bef9SDimitry Andric   }
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   // Now that we have every file, we can decide if we will need a
27250b57cec5SDimitry Andric   // dynamic symbol table.
27260b57cec5SDimitry Andric   // We need one if we were asked to export dynamic symbols or if we are
27270b57cec5SDimitry Andric   // producing a shared library.
27280b57cec5SDimitry Andric   // We also need one if any shared libraries are used and for pie executables
27290b57cec5SDimitry Andric   // (probably because the dynamic linker needs it).
27300b57cec5SDimitry Andric   config->hasDynSymTab =
2731bdd1243dSDimitry Andric       !ctx.sharedFiles.empty() || config->isPic || config->exportDynamic;
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   // Some symbols (such as __ehdr_start) are defined lazily only when there
27340b57cec5SDimitry Andric   // are undefined symbols for them, so we add these to trigger that logic.
273581ad6265SDimitry Andric   for (StringRef name : script->referencedSymbols) {
273681ad6265SDimitry Andric     Symbol *sym = addUnusedUndefined(name);
273781ad6265SDimitry Andric     sym->isUsedInRegularObj = true;
273881ad6265SDimitry Andric     sym->referenced = true;
273981ad6265SDimitry Andric   }
27400b57cec5SDimitry Andric 
27415ffd83dbSDimitry Andric   // Prevent LTO from removing any definition referenced by -u.
27425ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
2743bdd1243dSDimitry Andric     if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name)))
27445ffd83dbSDimitry Andric       sym->isUsedInRegularObj = true;
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric   // If an entry symbol is in a static archive, pull out that file now.
2747bdd1243dSDimitry Andric   if (Symbol *sym = symtab.find(config->entry))
2748349cc55cSDimitry Andric     handleUndefined(sym, "--entry");
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric   // Handle the `--undefined-glob <pattern>` options.
27510b57cec5SDimitry Andric   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
27520b57cec5SDimitry Andric     handleUndefinedGlob(pat);
27530b57cec5SDimitry Andric 
2754480093f4SDimitry Andric   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2755bdd1243dSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init)))
2756480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2757bdd1243dSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini)))
2758480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2759480093f4SDimitry Andric 
27600b57cec5SDimitry Andric   // If any of our inputs are bitcode files, the LTO code generator may create
27610b57cec5SDimitry Andric   // references to certain library functions that might not be explicit in the
27620b57cec5SDimitry Andric   // bitcode file's symbol table. If any of those library functions are defined
27630b57cec5SDimitry Andric   // in a bitcode file in an archive member, we need to arrange to use LTO to
27640b57cec5SDimitry Andric   // compile those archive members by adding them to the link beforehand.
27650b57cec5SDimitry Andric   //
27660b57cec5SDimitry Andric   // However, adding all libcall symbols to the link can have undesired
27670b57cec5SDimitry Andric   // consequences. For example, the libgcc implementation of
27680b57cec5SDimitry Andric   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
27690b57cec5SDimitry Andric   // that aborts the program if the Linux kernel does not support 64-bit
27700b57cec5SDimitry Andric   // atomics, which would prevent the program from running even if it does not
27710b57cec5SDimitry Andric   // use 64-bit atomics.
27720b57cec5SDimitry Andric   //
27730b57cec5SDimitry Andric   // Therefore, we only add libcall symbols to the link before LTO if we have
27740b57cec5SDimitry Andric   // to, i.e. if the symbol's definition is in bitcode. Any other required
27750b57cec5SDimitry Andric   // libcall symbols will be added to the link after LTO when we add the LTO
27760b57cec5SDimitry Andric   // object file to the link.
2777bdd1243dSDimitry Andric   if (!ctx.bitcodeFiles.empty())
277885868e8aSDimitry Andric     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
27790b57cec5SDimitry Andric       handleLibcall(s);
27800b57cec5SDimitry Andric 
278181ad6265SDimitry Andric   // Archive members defining __wrap symbols may be extracted.
278281ad6265SDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
278381ad6265SDimitry Andric 
278481ad6265SDimitry Andric   // No more lazy bitcode can be extracted at this point. Do post parse work
278581ad6265SDimitry Andric   // like checking duplicate symbols.
2786bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
2787bdd1243dSDimitry Andric     initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);
2788bdd1243dSDimitry Andric   });
2789bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, postParseObjectFile);
2790bdd1243dSDimitry Andric   parallelForEach(ctx.bitcodeFiles,
279181ad6265SDimitry Andric                   [](BitcodeFile *file) { file->postParse(); });
2792bdd1243dSDimitry Andric   for (auto &it : ctx.nonPrevailingSyms) {
279381ad6265SDimitry Andric     Symbol &sym = *it.first;
2794bdd1243dSDimitry Andric     Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,
2795bdd1243dSDimitry Andric               it.second)
2796bdd1243dSDimitry Andric         .overwrite(sym);
279781ad6265SDimitry Andric     cast<Undefined>(sym).nonPrevailing = true;
279881ad6265SDimitry Andric   }
2799bdd1243dSDimitry Andric   ctx.nonPrevailingSyms.clear();
2800bdd1243dSDimitry Andric   for (const DuplicateSymbol &d : ctx.duplicates)
280181ad6265SDimitry Andric     reportDuplicate(*d.sym, d.file, d.section, d.value);
2802bdd1243dSDimitry Andric   ctx.duplicates.clear();
280381ad6265SDimitry Andric 
28040b57cec5SDimitry Andric   // Return if there were name resolution errors.
28050b57cec5SDimitry Andric   if (errorCount())
28060b57cec5SDimitry Andric     return;
28070b57cec5SDimitry Andric 
28080b57cec5SDimitry Andric   // We want to declare linker script's symbols early,
28090b57cec5SDimitry Andric   // so that we can version them.
28100b57cec5SDimitry Andric   // They also might be exported if referenced by DSOs.
28110b57cec5SDimitry Andric   script->declareSymbols();
28120b57cec5SDimitry Andric 
2813e8d8bef9SDimitry Andric   // Handle --exclude-libs. This is before scanVersionScript() due to a
2814e8d8bef9SDimitry Andric   // workaround for Android ndk: for a defined versioned symbol in an archive
2815e8d8bef9SDimitry Andric   // without a version node in the version script, Android does not expect a
2816e8d8bef9SDimitry Andric   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2817e8d8bef9SDimitry Andric   // GNU ld errors in this case.
28180b57cec5SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
28190b57cec5SDimitry Andric     excludeLibs(args);
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric   // Create elfHeader early. We need a dummy section in
28220b57cec5SDimitry Andric   // addReservedSymbols to mark the created symbols as not absolute.
28230b57cec5SDimitry Andric   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   // We need to create some reserved symbols such as _end. Create them.
28260b57cec5SDimitry Andric   if (!config->relocatable)
28270b57cec5SDimitry Andric     addReservedSymbols();
28280b57cec5SDimitry Andric 
28290b57cec5SDimitry Andric   // Apply version scripts.
28300b57cec5SDimitry Andric   //
28310b57cec5SDimitry Andric   // For a relocatable output, version scripts don't make sense, and
28320b57cec5SDimitry Andric   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
28330b57cec5SDimitry Andric   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2834e8d8bef9SDimitry Andric   if (!config->relocatable) {
2835e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Process symbol versions");
2836bdd1243dSDimitry Andric     symtab.scanVersionScript();
2837e8d8bef9SDimitry Andric   }
28380b57cec5SDimitry Andric 
283904eeddc0SDimitry Andric   // Skip the normal linked output if some LTO options are specified.
284004eeddc0SDimitry Andric   //
284104eeddc0SDimitry Andric   // For --thinlto-index-only, index file creation is performed in
284204eeddc0SDimitry Andric   // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
284304eeddc0SDimitry Andric   // --plugin-opt=emit-asm create output files in bitcode or assembly code,
284404eeddc0SDimitry Andric   // respectively. When only certain thinLTO modules are specified for
284504eeddc0SDimitry Andric   // compilation, the intermediate object file are the expected output.
284604eeddc0SDimitry Andric   const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
284704eeddc0SDimitry Andric                                 config->ltoEmitAsm ||
284804eeddc0SDimitry Andric                                 !config->thinLTOModulesToCompile.empty();
284904eeddc0SDimitry Andric 
28505f757f3fSDimitry Andric   // Handle --lto-validate-all-vtables-have-type-infos.
28515f757f3fSDimitry Andric   if (config->ltoValidateAllVtablesHaveTypeInfos)
28525f757f3fSDimitry Andric     invokeELFT(ltoValidateAllVtablesHaveTypeInfos, args);
28535f757f3fSDimitry Andric 
28540b57cec5SDimitry Andric   // Do link-time optimization if given files are LLVM bitcode files.
28550b57cec5SDimitry Andric   // This compiles bitcode files into real object files.
28560b57cec5SDimitry Andric   //
28570b57cec5SDimitry Andric   // With this the symbol table should be complete. After this, no new names
28580b57cec5SDimitry Andric   // except a few linker-synthesized ones will be added to the symbol table.
2859bdd1243dSDimitry Andric   const size_t numObjsBeforeLTO = ctx.objectFiles.size();
28601fd87a68SDimitry Andric   invokeELFT(compileBitcodeFiles, skipLinkedOutput);
286104eeddc0SDimitry Andric 
286281ad6265SDimitry Andric   // Symbol resolution finished. Report backward reference problems,
286381ad6265SDimitry Andric   // --print-archive-stats=, and --why-extract=.
286404eeddc0SDimitry Andric   reportBackrefs();
286581ad6265SDimitry Andric   writeArchiveStats();
286681ad6265SDimitry Andric   writeWhyExtract();
286704eeddc0SDimitry Andric   if (errorCount())
286804eeddc0SDimitry Andric     return;
286904eeddc0SDimitry Andric 
287004eeddc0SDimitry Andric   // Bail out if normal linked output is skipped due to LTO.
287104eeddc0SDimitry Andric   if (skipLinkedOutput)
287204eeddc0SDimitry Andric     return;
28735ffd83dbSDimitry Andric 
287481ad6265SDimitry Andric   // compileBitcodeFiles may have produced lto.tmp object files. After this, no
287581ad6265SDimitry Andric   // more file will be added.
2876bdd1243dSDimitry Andric   auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);
2877bdd1243dSDimitry Andric   parallelForEach(newObjectFiles, [](ELFFileBase *file) {
2878bdd1243dSDimitry Andric     initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);
2879bdd1243dSDimitry Andric   });
288081ad6265SDimitry Andric   parallelForEach(newObjectFiles, postParseObjectFile);
2881bdd1243dSDimitry Andric   for (const DuplicateSymbol &d : ctx.duplicates)
288281ad6265SDimitry Andric     reportDuplicate(*d.sym, d.file, d.section, d.value);
288381ad6265SDimitry Andric 
2884e8d8bef9SDimitry Andric   // Handle --exclude-libs again because lto.tmp may reference additional
2885e8d8bef9SDimitry Andric   // libcalls symbols defined in an excluded archive. This may override
2886e8d8bef9SDimitry Andric   // versionId set by scanVersionScript().
2887e8d8bef9SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
2888e8d8bef9SDimitry Andric     excludeLibs(args);
2889e8d8bef9SDimitry Andric 
289006c3fb27SDimitry Andric   // Record [__acle_se_<sym>, <sym>] pairs for later processing.
289106c3fb27SDimitry Andric   processArmCmseSymbols();
289206c3fb27SDimitry Andric 
2893349cc55cSDimitry Andric   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2894e8d8bef9SDimitry Andric   redirectSymbols(wrapped);
28950b57cec5SDimitry Andric 
289604eeddc0SDimitry Andric   // Replace common symbols with regular symbols.
289704eeddc0SDimitry Andric   replaceCommonSymbols();
289804eeddc0SDimitry Andric 
2899e8d8bef9SDimitry Andric   {
2900e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Aggregate sections");
29010b57cec5SDimitry Andric     // Now that we have a complete list of input files.
29020b57cec5SDimitry Andric     // Beyond this point, no new files are added.
29030b57cec5SDimitry Andric     // Aggregate all input sections into one place.
2904bdd1243dSDimitry Andric     for (InputFile *f : ctx.objectFiles) {
2905bdd1243dSDimitry Andric       for (InputSectionBase *s : f->getSections()) {
2906bdd1243dSDimitry Andric         if (!s || s == &InputSection::discarded)
2907bdd1243dSDimitry Andric           continue;
2908bdd1243dSDimitry Andric         if (LLVM_UNLIKELY(isa<EhInputSection>(s)))
2909bdd1243dSDimitry Andric           ctx.ehInputSections.push_back(cast<EhInputSection>(s));
2910bdd1243dSDimitry Andric         else
2911bdd1243dSDimitry Andric           ctx.inputSections.push_back(s);
2912bdd1243dSDimitry Andric       }
2913bdd1243dSDimitry Andric     }
2914bdd1243dSDimitry Andric     for (BinaryFile *f : ctx.binaryFiles)
29150b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
2916bdd1243dSDimitry Andric         ctx.inputSections.push_back(cast<InputSection>(s));
2917e8d8bef9SDimitry Andric   }
29180b57cec5SDimitry Andric 
2919e8d8bef9SDimitry Andric   {
2920e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Strip sections");
2921bdd1243dSDimitry Andric     if (ctx.hasSympart.load(std::memory_order_relaxed)) {
2922bdd1243dSDimitry Andric       llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
292381ad6265SDimitry Andric         if (s->type != SHT_LLVM_SYMPART)
292481ad6265SDimitry Andric           return false;
29251fd87a68SDimitry Andric         invokeELFT(readSymbolPartitionSection, s);
29260b57cec5SDimitry Andric         return true;
292781ad6265SDimitry Andric       });
29280b57cec5SDimitry Andric     }
29290b57cec5SDimitry Andric     // We do not want to emit debug sections if --strip-all
2930349cc55cSDimitry Andric     // or --strip-debug are given.
293181ad6265SDimitry Andric     if (config->strip != StripPolicy::None) {
2932bdd1243dSDimitry Andric       llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
2933d65cd7a5SDimitry Andric         if (isDebugSection(*s))
2934d65cd7a5SDimitry Andric           return true;
2935d65cd7a5SDimitry Andric         if (auto *isec = dyn_cast<InputSection>(s))
2936d65cd7a5SDimitry Andric           if (InputSectionBase *rel = isec->getRelocatedSection())
2937d65cd7a5SDimitry Andric             if (isDebugSection(*rel))
2938d65cd7a5SDimitry Andric               return true;
2939d65cd7a5SDimitry Andric 
2940d65cd7a5SDimitry Andric         return false;
29410b57cec5SDimitry Andric       });
2942e8d8bef9SDimitry Andric     }
294381ad6265SDimitry Andric   }
2944e8d8bef9SDimitry Andric 
2945e8d8bef9SDimitry Andric   // Since we now have a complete set of input files, we can create
2946e8d8bef9SDimitry Andric   // a .d file to record build dependencies.
2947e8d8bef9SDimitry Andric   if (!config->dependencyFile.empty())
2948e8d8bef9SDimitry Andric     writeDependencyFile();
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   // Now that the number of partitions is fixed, save a pointer to the main
29510b57cec5SDimitry Andric   // partition.
29520b57cec5SDimitry Andric   mainPart = &partitions[0];
29530b57cec5SDimitry Andric 
29540b57cec5SDimitry Andric   // Read .note.gnu.property sections from input object files which
29550b57cec5SDimitry Andric   // contain a hint to tweak linker's and loader's behaviors.
29561fd87a68SDimitry Andric   config->andFeatures = getAndFeatures();
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   // The Target instance handles target-specific stuff, such as applying
29590b57cec5SDimitry Andric   // relocations or writing a PLT section. It also contains target-dependent
29600b57cec5SDimitry Andric   // values such as a default image base address.
29610b57cec5SDimitry Andric   target = getTarget();
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric   config->eflags = target->calcEFlags();
29640b57cec5SDimitry Andric   // maxPageSize (sometimes called abi page size) is the maximum page size that
29650b57cec5SDimitry Andric   // the output can be run on. For example if the OS can use 4k or 64k page
29660b57cec5SDimitry Andric   // sizes then maxPageSize must be 64k for the output to be useable on both.
29670b57cec5SDimitry Andric   // All important alignment decisions must use this value.
29680b57cec5SDimitry Andric   config->maxPageSize = getMaxPageSize(args);
29690b57cec5SDimitry Andric   // commonPageSize is the most common page size that the output will be run on.
29700b57cec5SDimitry Andric   // For example if an OS can use 4k or 64k page sizes and 4k is more common
29710b57cec5SDimitry Andric   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
29720b57cec5SDimitry Andric   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
29730b57cec5SDimitry Andric   // is limited to writing trap instructions on the last executable segment.
29740b57cec5SDimitry Andric   config->commonPageSize = getCommonPageSize(args);
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   config->imageBase = getImageBase(args);
29770b57cec5SDimitry Andric 
297885868e8aSDimitry Andric   // This adds a .comment section containing a version string.
29790b57cec5SDimitry Andric   if (!config->relocatable)
2980bdd1243dSDimitry Andric     ctx.inputSections.push_back(createCommentSection());
29810b57cec5SDimitry Andric 
298285868e8aSDimitry Andric   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
298306c3fb27SDimitry Andric   invokeELFT(splitSections,);
298485868e8aSDimitry Andric 
298585868e8aSDimitry Andric   // Garbage collection and removal of shared symbols from unused shared objects.
298606c3fb27SDimitry Andric   invokeELFT(markLive,);
298785868e8aSDimitry Andric 
298885868e8aSDimitry Andric   // Make copies of any input sections that need to be copied into each
298985868e8aSDimitry Andric   // partition.
299085868e8aSDimitry Andric   copySectionsIntoPartitions();
299185868e8aSDimitry Andric 
29925f757f3fSDimitry Andric   if (canHaveMemtagGlobals()) {
29935f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Process memory tagged symbols");
29945f757f3fSDimitry Andric     createTaggedSymbols(ctx.objectFiles);
29955f757f3fSDimitry Andric   }
29965f757f3fSDimitry Andric 
299785868e8aSDimitry Andric   // Create synthesized sections such as .got and .plt. This is called before
299885868e8aSDimitry Andric   // processSectionCommands() so that they can be placed by SECTIONS commands.
299906c3fb27SDimitry Andric   invokeELFT(createSyntheticSections,);
300085868e8aSDimitry Andric 
300185868e8aSDimitry Andric   // Some input sections that are used for exception handling need to be moved
300285868e8aSDimitry Andric   // into synthetic sections. Do that now so that they aren't assigned to
300385868e8aSDimitry Andric   // output sections in the usual way.
300485868e8aSDimitry Andric   if (!config->relocatable)
300585868e8aSDimitry Andric     combineEhSections();
300685868e8aSDimitry Andric 
3007bdd1243dSDimitry Andric   // Merge .riscv.attributes sections.
3008bdd1243dSDimitry Andric   if (config->emachine == EM_RISCV)
3009bdd1243dSDimitry Andric     mergeRISCVAttributesSections();
3010bdd1243dSDimitry Andric 
3011e8d8bef9SDimitry Andric   {
3012e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Assign sections");
3013e8d8bef9SDimitry Andric 
301485868e8aSDimitry Andric     // Create output sections described by SECTIONS commands.
301585868e8aSDimitry Andric     script->processSectionCommands();
301685868e8aSDimitry Andric 
3017e8d8bef9SDimitry Andric     // Linker scripts control how input sections are assigned to output
3018e8d8bef9SDimitry Andric     // sections. Input sections that were not handled by scripts are called
3019e8d8bef9SDimitry Andric     // "orphans", and they are assigned to output sections by the default rule.
3020e8d8bef9SDimitry Andric     // Process that.
302185868e8aSDimitry Andric     script->addOrphanSections();
3022e8d8bef9SDimitry Andric   }
3023e8d8bef9SDimitry Andric 
3024e8d8bef9SDimitry Andric   {
3025e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
302685868e8aSDimitry Andric 
302785868e8aSDimitry Andric     // Migrate InputSectionDescription::sectionBases to sections. This includes
302885868e8aSDimitry Andric     // merging MergeInputSections into a single MergeSyntheticSection. From this
302985868e8aSDimitry Andric     // point onwards InputSectionDescription::sections should be used instead of
303085868e8aSDimitry Andric     // sectionBases.
30314824e7fdSDimitry Andric     for (SectionCommand *cmd : script->sectionCommands)
303281ad6265SDimitry Andric       if (auto *osd = dyn_cast<OutputDesc>(cmd))
303381ad6265SDimitry Andric         osd->osec.finalizeInputSections();
3034e8d8bef9SDimitry Andric   }
303585868e8aSDimitry Andric 
303685868e8aSDimitry Andric   // Two input sections with different output sections should not be folded.
303785868e8aSDimitry Andric   // ICF runs after processSectionCommands() so that we know the output sections.
30380b57cec5SDimitry Andric   if (config->icf != ICFLevel::None) {
30391fd87a68SDimitry Andric     invokeELFT(findKeepUniqueSections, args);
304006c3fb27SDimitry Andric     invokeELFT(doIcf,);
30410b57cec5SDimitry Andric   }
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric   // Read the callgraph now that we know what was gced or icfed
30445f757f3fSDimitry Andric   if (config->callGraphProfileSort != CGProfileSortKind::None) {
30450b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
3046bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
30470b57cec5SDimitry Andric         readCallGraph(*buffer);
304806c3fb27SDimitry Andric     invokeELFT(readCallGraphsFromObjectFiles,);
30490b57cec5SDimitry Andric   }
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric   // Write the result to the file.
305206c3fb27SDimitry Andric   invokeELFT(writeResult,);
30530b57cec5SDimitry Andric }
3054