xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision 9d59cfc6)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Driver.h"
10 #include "COFFLinkerContext.h"
11 #include "Config.h"
12 #include "DebugTypes.h"
13 #include "ICF.h"
14 #include "InputFiles.h"
15 #include "MarkLive.h"
16 #include "MinGW.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "Writer.h"
20 #include "lld/Common/Args.h"
21 #include "lld/Common/Driver.h"
22 #include "lld/Common/Filesystem.h"
23 #include "lld/Common/Timer.h"
24 #include "lld/Common/Version.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/BinaryFormat/Magic.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/LTO/LTO.h"
31 #include "llvm/Object/ArchiveWriter.h"
32 #include "llvm/Object/COFFImportFile.h"
33 #include "llvm/Object/COFFModuleDefinition.h"
34 #include "llvm/Object/WindowsMachineFlag.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/BinaryStreamReader.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Parallel.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/TarWriter.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
50 #include <algorithm>
51 #include <future>
52 #include <memory>
53 
54 using namespace llvm;
55 using namespace llvm::object;
56 using namespace llvm::COFF;
57 using namespace llvm::sys;
58 
59 namespace lld {
60 namespace coff {
61 
62 std::unique_ptr<Configuration> config;
63 std::unique_ptr<LinkerDriver> driver;
64 
65 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
66           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
67   // This driver-specific context will be freed later by lldMain().
68   auto *ctx = new COFFLinkerContext;
69 
70   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
71   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
72   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
73                                  " (use /errorlimit:0 to see all errors)";
74 
75   config = std::make_unique<Configuration>();
76   driver = std::make_unique<LinkerDriver>(*ctx);
77 
78   driver->linkerMain(args);
79 
80   return errorCount() == 0;
81 }
82 
83 // Parse options of the form "old;new".
84 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
85                                                         unsigned id) {
86   auto *arg = args.getLastArg(id);
87   if (!arg)
88     return {"", ""};
89 
90   StringRef s = arg->getValue();
91   std::pair<StringRef, StringRef> ret = s.split(';');
92   if (ret.second.empty())
93     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
94   return ret;
95 }
96 
97 // Drop directory components and replace extension with
98 // ".exe", ".dll" or ".sys".
99 static std::string getOutputPath(StringRef path) {
100   StringRef ext = ".exe";
101   if (config->dll)
102     ext = ".dll";
103   else if (config->driver)
104     ext = ".sys";
105 
106   return (sys::path::stem(path) + ext).str();
107 }
108 
109 // Returns true if S matches /crtend.?\.o$/.
110 static bool isCrtend(StringRef s) {
111   if (!s.endswith(".o"))
112     return false;
113   s = s.drop_back(2);
114   if (s.endswith("crtend"))
115     return true;
116   return !s.empty() && s.drop_back().endswith("crtend");
117 }
118 
119 // ErrorOr is not default constructible, so it cannot be used as the type
120 // parameter of a future.
121 // FIXME: We could open the file in createFutureForFile and avoid needing to
122 // return an error here, but for the moment that would cost us a file descriptor
123 // (a limited resource on Windows) for the duration that the future is pending.
124 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
125 
126 // Create a std::future that opens and maps a file using the best strategy for
127 // the host platform.
128 static std::future<MBErrPair> createFutureForFile(std::string path) {
129 #if _WIN64
130   // On Windows, file I/O is relatively slow so it is best to do this
131   // asynchronously.  But 32-bit has issues with potentially launching tons
132   // of threads
133   auto strategy = std::launch::async;
134 #else
135   auto strategy = std::launch::deferred;
136 #endif
137   return std::async(strategy, [=]() {
138     auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
139                                          /*RequiresNullTerminator=*/false);
140     if (!mbOrErr)
141       return MBErrPair{nullptr, mbOrErr.getError()};
142     return MBErrPair{std::move(*mbOrErr), std::error_code()};
143   });
144 }
145 
146 // Symbol names are mangled by prepending "_" on x86.
147 static StringRef mangle(StringRef sym) {
148   assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
149   if (config->machine == I386)
150     return saver().save("_" + sym);
151   return sym;
152 }
153 
154 static llvm::Triple::ArchType getArch() {
155   switch (config->machine) {
156   case I386:
157     return llvm::Triple::ArchType::x86;
158   case AMD64:
159     return llvm::Triple::ArchType::x86_64;
160   case ARMNT:
161     return llvm::Triple::ArchType::arm;
162   case ARM64:
163     return llvm::Triple::ArchType::aarch64;
164   default:
165     return llvm::Triple::ArchType::UnknownArch;
166   }
167 }
168 
169 bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
170   Symbol *s = ctx.symtab.findMangle(mangle(sym));
171   return s && !isa<Undefined>(s);
172 }
173 
174 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
175   MemoryBufferRef mbref = *mb;
176   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
177 
178   if (driver->tar)
179     driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
180                         mbref.getBuffer());
181   return mbref;
182 }
183 
184 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
185                              bool wholeArchive, bool lazy) {
186   StringRef filename = mb->getBufferIdentifier();
187 
188   MemoryBufferRef mbref = takeBuffer(std::move(mb));
189   filePaths.push_back(filename);
190 
191   // File type is detected by contents, not by file extension.
192   switch (identify_magic(mbref.getBuffer())) {
193   case file_magic::windows_resource:
194     resources.push_back(mbref);
195     break;
196   case file_magic::archive:
197     if (wholeArchive) {
198       std::unique_ptr<Archive> file =
199           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
200       Archive *archive = file.get();
201       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
202 
203       int memberIndex = 0;
204       for (MemoryBufferRef m : getArchiveMembers(archive))
205         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
206       return;
207     }
208     ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
209     break;
210   case file_magic::bitcode:
211     ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
212     break;
213   case file_magic::coff_object:
214   case file_magic::coff_import_library:
215     ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
216     break;
217   case file_magic::pdb:
218     ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
219     break;
220   case file_magic::coff_cl_gl_object:
221     error(filename + ": is not a native COFF file. Recompile without /GL");
222     break;
223   case file_magic::pecoff_executable:
224     if (config->mingw) {
225       ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
226       break;
227     }
228     if (filename.endswith_insensitive(".dll")) {
229       error(filename + ": bad file type. Did you specify a DLL instead of an "
230                        "import library?");
231       break;
232     }
233     LLVM_FALLTHROUGH;
234   default:
235     error(mbref.getBufferIdentifier() + ": unknown file type");
236     break;
237   }
238 }
239 
240 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
241   auto future = std::make_shared<std::future<MBErrPair>>(
242       createFutureForFile(std::string(path)));
243   std::string pathStr = std::string(path);
244   enqueueTask([=]() {
245     auto mbOrErr = future->get();
246     if (mbOrErr.second) {
247       std::string msg =
248           "could not open '" + pathStr + "': " + mbOrErr.second.message();
249       // Check if the filename is a typo for an option flag. OptTable thinks
250       // that all args that are not known options and that start with / are
251       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
252       // the option `/nodefaultlib` than a reference to a file in the root
253       // directory.
254       std::string nearest;
255       if (optTable.findNearest(pathStr, nearest) > 1)
256         error(msg);
257       else
258         error(msg + "; did you mean '" + nearest + "'");
259     } else
260       driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
261   });
262 }
263 
264 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
265                                     StringRef parentName,
266                                     uint64_t offsetInArchive) {
267   file_magic magic = identify_magic(mb.getBuffer());
268   if (magic == file_magic::coff_import_library) {
269     InputFile *imp = make<ImportFile>(ctx, mb);
270     imp->parentName = parentName;
271     ctx.symtab.addFile(imp);
272     return;
273   }
274 
275   InputFile *obj;
276   if (magic == file_magic::coff_object) {
277     obj = make<ObjFile>(ctx, mb);
278   } else if (magic == file_magic::bitcode) {
279     obj =
280         make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
281   } else {
282     error("unknown file type: " + mb.getBufferIdentifier());
283     return;
284   }
285 
286   obj->parentName = parentName;
287   ctx.symtab.addFile(obj);
288   log("Loaded " + toString(obj) + " for " + symName);
289 }
290 
291 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
292                                         const Archive::Symbol &sym,
293                                         StringRef parentName) {
294 
295   auto reportBufferError = [=](Error &&e, StringRef childName) {
296     fatal("could not get the buffer for the member defining symbol " +
297           toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
298           toString(std::move(e)));
299   };
300 
301   if (!c.getParent()->isThin()) {
302     uint64_t offsetInArchive = c.getChildOffset();
303     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
304     if (!mbOrErr)
305       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
306     MemoryBufferRef mb = mbOrErr.get();
307     enqueueTask([=]() {
308       driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
309                                offsetInArchive);
310     });
311     return;
312   }
313 
314   std::string childName = CHECK(
315       c.getFullName(),
316       "could not get the filename for the member defining symbol " +
317       toCOFFString(sym));
318   auto future = std::make_shared<std::future<MBErrPair>>(
319       createFutureForFile(childName));
320   enqueueTask([=]() {
321     auto mbOrErr = future->get();
322     if (mbOrErr.second)
323       reportBufferError(errorCodeToError(mbOrErr.second), childName);
324     // Pass empty string as archive name so that the original filename is
325     // used as the buffer identifier.
326     driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
327                              toCOFFString(sym), "", /*OffsetInArchive=*/0);
328   });
329 }
330 
331 static bool isDecorated(StringRef sym) {
332   return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
333          (!config->mingw && sym.contains('@'));
334 }
335 
336 // Parses .drectve section contents and returns a list of files
337 // specified by /defaultlib.
338 void LinkerDriver::parseDirectives(InputFile *file) {
339   StringRef s = file->getDirectives();
340   if (s.empty())
341     return;
342 
343   log("Directives: " + toString(file) + ": " + s);
344 
345   ArgParser parser;
346   // .drectve is always tokenized using Windows shell rules.
347   // /EXPORT: option can appear too many times, processing in fastpath.
348   ParsedDirectives directives = parser.parseDirectives(s);
349 
350   for (StringRef e : directives.exports) {
351     // If a common header file contains dllexported function
352     // declarations, many object files may end up with having the
353     // same /EXPORT options. In order to save cost of parsing them,
354     // we dedup them first.
355     if (!directivesExports.insert(e).second)
356       continue;
357 
358     Export exp = parseExport(e);
359     if (config->machine == I386 && config->mingw) {
360       if (!isDecorated(exp.name))
361         exp.name = saver().save("_" + exp.name);
362       if (!exp.extName.empty() && !isDecorated(exp.extName))
363         exp.extName = saver().save("_" + exp.extName);
364     }
365     exp.directives = true;
366     config->exports.push_back(exp);
367   }
368 
369   // Handle /include: in bulk.
370   for (StringRef inc : directives.includes)
371     addUndefined(inc);
372 
373   // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
374   for (auto *arg : directives.args) {
375     switch (arg->getOption().getID()) {
376     case OPT_aligncomm:
377       parseAligncomm(arg->getValue());
378       break;
379     case OPT_alternatename:
380       parseAlternateName(arg->getValue());
381       break;
382     case OPT_defaultlib:
383       if (Optional<StringRef> path = findLib(arg->getValue()))
384         enqueuePath(*path, false, false);
385       break;
386     case OPT_entry:
387       config->entry = addUndefined(mangle(arg->getValue()));
388       break;
389     case OPT_failifmismatch:
390       checkFailIfMismatch(arg->getValue(), file);
391       break;
392     case OPT_incl:
393       addUndefined(arg->getValue());
394       break;
395     case OPT_manifestdependency:
396       config->manifestDependencies.insert(arg->getValue());
397       break;
398     case OPT_merge:
399       parseMerge(arg->getValue());
400       break;
401     case OPT_nodefaultlib:
402       config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
403       break;
404     case OPT_section:
405       parseSection(arg->getValue());
406       break;
407     case OPT_stack:
408       parseNumbers(arg->getValue(), &config->stackReserve,
409                    &config->stackCommit);
410       break;
411     case OPT_subsystem: {
412       bool gotVersion = false;
413       parseSubsystem(arg->getValue(), &config->subsystem,
414                      &config->majorSubsystemVersion,
415                      &config->minorSubsystemVersion, &gotVersion);
416       if (gotVersion) {
417         config->majorOSVersion = config->majorSubsystemVersion;
418         config->minorOSVersion = config->minorSubsystemVersion;
419       }
420       break;
421     }
422     // Only add flags here that link.exe accepts in
423     // `#pragma comment(linker, "/flag")`-generated sections.
424     case OPT_editandcontinue:
425     case OPT_guardsym:
426     case OPT_throwingnew:
427       break;
428     default:
429       error(arg->getSpelling() + " is not allowed in .drectve");
430     }
431   }
432 }
433 
434 // Find file from search paths. You can omit ".obj", this function takes
435 // care of that. Note that the returned path is not guaranteed to exist.
436 StringRef LinkerDriver::doFindFile(StringRef filename) {
437   bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
438   if (hasPathSep)
439     return filename;
440   bool hasExt = filename.contains('.');
441   for (StringRef dir : searchPaths) {
442     SmallString<128> path = dir;
443     sys::path::append(path, filename);
444     if (sys::fs::exists(path.str()))
445       return saver().save(path.str());
446     if (!hasExt) {
447       path.append(".obj");
448       if (sys::fs::exists(path.str()))
449         return saver().save(path.str());
450     }
451   }
452   return filename;
453 }
454 
455 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
456   sys::fs::UniqueID ret;
457   if (sys::fs::getUniqueID(path, ret))
458     return None;
459   return ret;
460 }
461 
462 // Resolves a file path. This never returns the same path
463 // (in that case, it returns None).
464 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
465   StringRef path = doFindFile(filename);
466 
467   if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
468     bool seen = !visitedFiles.insert(*id).second;
469     if (seen)
470       return None;
471   }
472 
473   if (path.endswith_insensitive(".lib"))
474     visitedLibs.insert(std::string(sys::path::filename(path)));
475   return path;
476 }
477 
478 // MinGW specific. If an embedded directive specified to link to
479 // foo.lib, but it isn't found, try libfoo.a instead.
480 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
481   if (filename.contains('/') || filename.contains('\\'))
482     return filename;
483 
484   SmallString<128> s = filename;
485   sys::path::replace_extension(s, ".a");
486   StringRef libName = saver().save("lib" + s.str());
487   return doFindFile(libName);
488 }
489 
490 // Find library file from search path.
491 StringRef LinkerDriver::doFindLib(StringRef filename) {
492   // Add ".lib" to Filename if that has no file extension.
493   bool hasExt = filename.contains('.');
494   if (!hasExt)
495     filename = saver().save(filename + ".lib");
496   StringRef ret = doFindFile(filename);
497   // For MinGW, if the find above didn't turn up anything, try
498   // looking for a MinGW formatted library name.
499   if (config->mingw && ret == filename)
500     return doFindLibMinGW(filename);
501   return ret;
502 }
503 
504 // Resolves a library path. /nodefaultlib options are taken into
505 // consideration. This never returns the same path (in that case,
506 // it returns None).
507 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
508   if (config->noDefaultLibAll)
509     return None;
510   if (!visitedLibs.insert(filename.lower()).second)
511     return None;
512 
513   StringRef path = doFindLib(filename);
514   if (config->noDefaultLibs.count(path.lower()))
515     return None;
516 
517   if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
518     if (!visitedFiles.insert(*id).second)
519       return None;
520   return path;
521 }
522 
523 void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
524   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
525 
526   // Check the command line first, that's the user explicitly telling us what to
527   // use. Check the environment next, in case we're being invoked from a VS
528   // command prompt. Failing that, just try to find the newest Visual Studio
529   // version we can and use its default VC toolchain.
530   Optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
531   if (auto *A = Args.getLastArg(OPT_vctoolsdir))
532     VCToolsDir = A->getValue();
533   if (auto *A = Args.getLastArg(OPT_vctoolsversion))
534     VCToolsVersion = A->getValue();
535   if (auto *A = Args.getLastArg(OPT_winsysroot))
536     WinSysRoot = A->getValue();
537   if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
538                                      WinSysRoot, vcToolChainPath, vsLayout) &&
539       (Args.hasArg(OPT_lldignoreenv) ||
540        !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
541       !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) &&
542       !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
543     return;
544 
545   // If the VC environment hasn't been configured (perhaps because the user did
546   // not run vcvarsall), try to build a consistent link environment.  If the
547   // environment variable is set however, assume the user knows what they're
548   // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
549   // vars.
550   if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
551     diaPath = A->getValue();
552     if (A->getOption().getID() == OPT_winsysroot)
553       path::append(diaPath, "DIA SDK");
554   }
555   useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
556                          !Process::GetEnv("LIB") ||
557                          Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
558   if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
559       Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
560     Optional<StringRef> WinSdkDir, WinSdkVersion;
561     if (auto *A = Args.getLastArg(OPT_winsdkdir))
562       WinSdkDir = A->getValue();
563     if (auto *A = Args.getLastArg(OPT_winsdkversion))
564       WinSdkVersion = A->getValue();
565 
566     if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
567       std::string UniversalCRTSdkPath;
568       std::string UCRTVersion;
569       if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
570                                 UniversalCRTSdkPath, UCRTVersion)) {
571         universalCRTLibPath = UniversalCRTSdkPath;
572         path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
573       }
574     }
575 
576     std::string sdkPath;
577     std::string windowsSDKIncludeVersion;
578     std::string windowsSDKLibVersion;
579     if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
580                          sdkMajor, windowsSDKIncludeVersion,
581                          windowsSDKLibVersion)) {
582       windowsSdkLibPath = sdkPath;
583       path::append(windowsSdkLibPath, "Lib");
584       if (sdkMajor >= 8)
585         path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
586     }
587   }
588 }
589 
590 void LinkerDriver::addWinSysRootLibSearchPaths() {
591   if (!diaPath.empty()) {
592     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
593     path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
594     searchPaths.push_back(saver().save(diaPath.str()));
595   }
596   if (useWinSysRootLibPath) {
597     searchPaths.push_back(saver().save(getSubDirectoryPath(
598         SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
599     searchPaths.push_back(saver().save(
600         getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
601                             getArch(), "atlmfc")));
602   }
603   if (!universalCRTLibPath.empty()) {
604     StringRef ArchName = archToWindowsSDKArch(getArch());
605     if (!ArchName.empty()) {
606       path::append(universalCRTLibPath, ArchName);
607       searchPaths.push_back(saver().save(universalCRTLibPath.str()));
608     }
609   }
610   if (!windowsSdkLibPath.empty()) {
611     std::string path;
612     if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
613                                       path))
614       searchPaths.push_back(saver().save(path));
615   }
616 }
617 
618 // Parses LIB environment which contains a list of search paths.
619 void LinkerDriver::addLibSearchPaths() {
620   Optional<std::string> envOpt = Process::GetEnv("LIB");
621   if (!envOpt.hasValue())
622     return;
623   StringRef env = saver().save(*envOpt);
624   while (!env.empty()) {
625     StringRef path;
626     std::tie(path, env) = env.split(';');
627     searchPaths.push_back(path);
628   }
629 }
630 
631 Symbol *LinkerDriver::addUndefined(StringRef name) {
632   Symbol *b = ctx.symtab.addUndefined(name);
633   if (!b->isGCRoot) {
634     b->isGCRoot = true;
635     config->gcroot.push_back(b);
636   }
637   return b;
638 }
639 
640 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
641   // If the plain symbol name has already been resolved, do nothing.
642   Undefined *unmangled = dyn_cast<Undefined>(s);
643   if (!unmangled)
644     return "";
645 
646   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
647   Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
648   if (!mangled)
649     return "";
650 
651   // If we find a similar mangled symbol, make this an alias to it and return
652   // its name.
653   log(unmangled->getName() + " aliased to " + mangled->getName());
654   unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
655   return mangled->getName();
656 }
657 
658 // Windows specific -- find default entry point name.
659 //
660 // There are four different entry point functions for Windows executables,
661 // each of which corresponds to a user-defined "main" function. This function
662 // infers an entry point from a user-defined "main" function.
663 StringRef LinkerDriver::findDefaultEntry() {
664   assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
665          "must handle /subsystem before calling this");
666 
667   if (config->mingw)
668     return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
669                       ? "WinMainCRTStartup"
670                       : "mainCRTStartup");
671 
672   if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
673     if (findUnderscoreMangle("wWinMain")) {
674       if (!findUnderscoreMangle("WinMain"))
675         return mangle("wWinMainCRTStartup");
676       warn("found both wWinMain and WinMain; using latter");
677     }
678     return mangle("WinMainCRTStartup");
679   }
680   if (findUnderscoreMangle("wmain")) {
681     if (!findUnderscoreMangle("main"))
682       return mangle("wmainCRTStartup");
683     warn("found both wmain and main; using latter");
684   }
685   return mangle("mainCRTStartup");
686 }
687 
688 WindowsSubsystem LinkerDriver::inferSubsystem() {
689   if (config->dll)
690     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
691   if (config->mingw)
692     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
693   // Note that link.exe infers the subsystem from the presence of these
694   // functions even if /entry: or /nodefaultlib are passed which causes them
695   // to not be called.
696   bool haveMain = findUnderscoreMangle("main");
697   bool haveWMain = findUnderscoreMangle("wmain");
698   bool haveWinMain = findUnderscoreMangle("WinMain");
699   bool haveWWinMain = findUnderscoreMangle("wWinMain");
700   if (haveMain || haveWMain) {
701     if (haveWinMain || haveWWinMain) {
702       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
703            (haveWinMain ? "WinMain" : "wWinMain") +
704            "; defaulting to /subsystem:console");
705     }
706     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
707   }
708   if (haveWinMain || haveWWinMain)
709     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
710   return IMAGE_SUBSYSTEM_UNKNOWN;
711 }
712 
713 static uint64_t getDefaultImageBase() {
714   if (config->is64())
715     return config->dll ? 0x180000000 : 0x140000000;
716   return config->dll ? 0x10000000 : 0x400000;
717 }
718 
719 static std::string rewritePath(StringRef s) {
720   if (fs::exists(s))
721     return relativeToRoot(s);
722   return std::string(s);
723 }
724 
725 // Reconstructs command line arguments so that so that you can re-run
726 // the same command with the same inputs. This is for --reproduce.
727 static std::string createResponseFile(const opt::InputArgList &args,
728                                       ArrayRef<StringRef> filePaths,
729                                       ArrayRef<StringRef> searchPaths) {
730   SmallString<0> data;
731   raw_svector_ostream os(data);
732 
733   for (auto *arg : args) {
734     switch (arg->getOption().getID()) {
735     case OPT_linkrepro:
736     case OPT_reproduce:
737     case OPT_INPUT:
738     case OPT_defaultlib:
739     case OPT_libpath:
740     case OPT_winsysroot:
741       break;
742     case OPT_call_graph_ordering_file:
743     case OPT_deffile:
744     case OPT_manifestinput:
745     case OPT_natvis:
746       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
747       break;
748     case OPT_order: {
749       StringRef orderFile = arg->getValue();
750       orderFile.consume_front("@");
751       os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
752       break;
753     }
754     case OPT_pdbstream: {
755       const std::pair<StringRef, StringRef> nameFile =
756           StringRef(arg->getValue()).split("=");
757       os << arg->getSpelling() << nameFile.first << '='
758          << quote(rewritePath(nameFile.second)) << '\n';
759       break;
760     }
761     case OPT_implib:
762     case OPT_manifestfile:
763     case OPT_pdb:
764     case OPT_pdbstripped:
765     case OPT_out:
766       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
767       break;
768     default:
769       os << toString(*arg) << "\n";
770     }
771   }
772 
773   for (StringRef path : searchPaths) {
774     std::string relPath = relativeToRoot(path);
775     os << "/libpath:" << quote(relPath) << "\n";
776   }
777 
778   for (StringRef path : filePaths)
779     os << quote(relativeToRoot(path)) << "\n";
780 
781   return std::string(data.str());
782 }
783 
784 enum class DebugKind {
785   Unknown,
786   None,
787   Full,
788   FastLink,
789   GHash,
790   NoGHash,
791   Dwarf,
792   Symtab
793 };
794 
795 static DebugKind parseDebugKind(const opt::InputArgList &args) {
796   auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
797   if (!a)
798     return DebugKind::None;
799   if (a->getNumValues() == 0)
800     return DebugKind::Full;
801 
802   DebugKind debug = StringSwitch<DebugKind>(a->getValue())
803                         .CaseLower("none", DebugKind::None)
804                         .CaseLower("full", DebugKind::Full)
805                         .CaseLower("fastlink", DebugKind::FastLink)
806                         // LLD extensions
807                         .CaseLower("ghash", DebugKind::GHash)
808                         .CaseLower("noghash", DebugKind::NoGHash)
809                         .CaseLower("dwarf", DebugKind::Dwarf)
810                         .CaseLower("symtab", DebugKind::Symtab)
811                         .Default(DebugKind::Unknown);
812 
813   if (debug == DebugKind::FastLink) {
814     warn("/debug:fastlink unsupported; using /debug:full");
815     return DebugKind::Full;
816   }
817   if (debug == DebugKind::Unknown) {
818     error("/debug: unknown option: " + Twine(a->getValue()));
819     return DebugKind::None;
820   }
821   return debug;
822 }
823 
824 static unsigned parseDebugTypes(const opt::InputArgList &args) {
825   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
826 
827   if (auto *a = args.getLastArg(OPT_debugtype)) {
828     SmallVector<StringRef, 3> types;
829     StringRef(a->getValue())
830         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
831 
832     for (StringRef type : types) {
833       unsigned v = StringSwitch<unsigned>(type.lower())
834                        .Case("cv", static_cast<unsigned>(DebugType::CV))
835                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
836                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
837                        .Default(0);
838       if (v == 0) {
839         warn("/debugtype: unknown option '" + type + "'");
840         continue;
841       }
842       debugTypes |= v;
843     }
844     return debugTypes;
845   }
846 
847   // Default debug types
848   debugTypes = static_cast<unsigned>(DebugType::CV);
849   if (args.hasArg(OPT_driver))
850     debugTypes |= static_cast<unsigned>(DebugType::PData);
851   if (args.hasArg(OPT_profile))
852     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
853 
854   return debugTypes;
855 }
856 
857 static std::string getMapFile(const opt::InputArgList &args,
858                               opt::OptSpecifier os, opt::OptSpecifier osFile) {
859   auto *arg = args.getLastArg(os, osFile);
860   if (!arg)
861     return "";
862   if (arg->getOption().getID() == osFile.getID())
863     return arg->getValue();
864 
865   assert(arg->getOption().getID() == os.getID());
866   StringRef outFile = config->outputFile;
867   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
868 }
869 
870 static std::string getImplibPath() {
871   if (!config->implib.empty())
872     return std::string(config->implib);
873   SmallString<128> out = StringRef(config->outputFile);
874   sys::path::replace_extension(out, ".lib");
875   return std::string(out.str());
876 }
877 
878 // The import name is calculated as follows:
879 //
880 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
881 //   -----+----------------+---------------------+------------------
882 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
883 //    LIB | {value}        | {value}.dll         | {output name}.dll
884 //
885 static std::string getImportName(bool asLib) {
886   SmallString<128> out;
887 
888   if (config->importName.empty()) {
889     out.assign(sys::path::filename(config->outputFile));
890     if (asLib)
891       sys::path::replace_extension(out, ".dll");
892   } else {
893     out.assign(config->importName);
894     if (!sys::path::has_extension(out))
895       sys::path::replace_extension(out,
896                                    (config->dll || asLib) ? ".dll" : ".exe");
897   }
898 
899   return std::string(out.str());
900 }
901 
902 static void createImportLibrary(bool asLib) {
903   std::vector<COFFShortExport> exports;
904   for (Export &e1 : config->exports) {
905     COFFShortExport e2;
906     e2.Name = std::string(e1.name);
907     e2.SymbolName = std::string(e1.symbolName);
908     e2.ExtName = std::string(e1.extName);
909     e2.AliasTarget = std::string(e1.aliasTarget);
910     e2.Ordinal = e1.ordinal;
911     e2.Noname = e1.noname;
912     e2.Data = e1.data;
913     e2.Private = e1.isPrivate;
914     e2.Constant = e1.constant;
915     exports.push_back(e2);
916   }
917 
918   std::string libName = getImportName(asLib);
919   std::string path = getImplibPath();
920 
921   if (!config->incremental) {
922     checkError(writeImportLibrary(libName, path, exports, config->machine,
923                                   config->mingw));
924     return;
925   }
926 
927   // If the import library already exists, replace it only if the contents
928   // have changed.
929   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
930       path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
931   if (!oldBuf) {
932     checkError(writeImportLibrary(libName, path, exports, config->machine,
933                                   config->mingw));
934     return;
935   }
936 
937   SmallString<128> tmpName;
938   if (std::error_code ec =
939           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
940     fatal("cannot create temporary file for import library " + path + ": " +
941           ec.message());
942 
943   if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
944                                    config->mingw)) {
945     checkError(std::move(e));
946     return;
947   }
948 
949   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
950       tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
951   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
952     oldBuf->reset();
953     checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
954   } else {
955     sys::fs::remove(tmpName);
956   }
957 }
958 
959 static void parseModuleDefs(StringRef path) {
960   std::unique_ptr<MemoryBuffer> mb =
961       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
962                                   /*RequiresNullTerminator=*/false,
963                                   /*IsVolatile=*/true),
964             "could not open " + path);
965   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
966       mb->getMemBufferRef(), config->machine, config->mingw));
967 
968   // Include in /reproduce: output if applicable.
969   driver->takeBuffer(std::move(mb));
970 
971   if (config->outputFile.empty())
972     config->outputFile = std::string(saver().save(m.OutputFile));
973   config->importName = std::string(saver().save(m.ImportName));
974   if (m.ImageBase)
975     config->imageBase = m.ImageBase;
976   if (m.StackReserve)
977     config->stackReserve = m.StackReserve;
978   if (m.StackCommit)
979     config->stackCommit = m.StackCommit;
980   if (m.HeapReserve)
981     config->heapReserve = m.HeapReserve;
982   if (m.HeapCommit)
983     config->heapCommit = m.HeapCommit;
984   if (m.MajorImageVersion)
985     config->majorImageVersion = m.MajorImageVersion;
986   if (m.MinorImageVersion)
987     config->minorImageVersion = m.MinorImageVersion;
988   if (m.MajorOSVersion)
989     config->majorOSVersion = m.MajorOSVersion;
990   if (m.MinorOSVersion)
991     config->minorOSVersion = m.MinorOSVersion;
992 
993   for (COFFShortExport e1 : m.Exports) {
994     Export e2;
995     // In simple cases, only Name is set. Renamed exports are parsed
996     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
997     // it shouldn't be a normal exported function but a forward to another
998     // DLL instead. This is supported by both MS and GNU linkers.
999     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
1000         StringRef(e1.Name).contains('.')) {
1001       e2.name = saver().save(e1.ExtName);
1002       e2.forwardTo = saver().save(e1.Name);
1003       config->exports.push_back(e2);
1004       continue;
1005     }
1006     e2.name = saver().save(e1.Name);
1007     e2.extName = saver().save(e1.ExtName);
1008     e2.aliasTarget = saver().save(e1.AliasTarget);
1009     e2.ordinal = e1.Ordinal;
1010     e2.noname = e1.Noname;
1011     e2.data = e1.Data;
1012     e2.isPrivate = e1.Private;
1013     e2.constant = e1.Constant;
1014     config->exports.push_back(e2);
1015   }
1016 }
1017 
1018 void LinkerDriver::enqueueTask(std::function<void()> task) {
1019   taskQueue.push_back(std::move(task));
1020 }
1021 
1022 bool LinkerDriver::run() {
1023   ScopedTimer t(ctx.inputFileTimer);
1024 
1025   bool didWork = !taskQueue.empty();
1026   while (!taskQueue.empty()) {
1027     taskQueue.front()();
1028     taskQueue.pop_front();
1029   }
1030   return didWork;
1031 }
1032 
1033 // Parse an /order file. If an option is given, the linker places
1034 // COMDAT sections in the same order as their names appear in the
1035 // given file.
1036 static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) {
1037   // For some reason, the MSVC linker requires a filename to be
1038   // preceded by "@".
1039   if (!arg.startswith("@")) {
1040     error("malformed /order option: '@' missing");
1041     return;
1042   }
1043 
1044   // Get a list of all comdat sections for error checking.
1045   DenseSet<StringRef> set;
1046   for (Chunk *c : ctx.symtab.getChunks())
1047     if (auto *sec = dyn_cast<SectionChunk>(c))
1048       if (sec->sym)
1049         set.insert(sec->sym->getName());
1050 
1051   // Open a file.
1052   StringRef path = arg.substr(1);
1053   std::unique_ptr<MemoryBuffer> mb =
1054       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1055                                   /*RequiresNullTerminator=*/false,
1056                                   /*IsVolatile=*/true),
1057             "could not open " + path);
1058 
1059   // Parse a file. An order file contains one symbol per line.
1060   // All symbols that were not present in a given order file are
1061   // considered to have the lowest priority 0 and are placed at
1062   // end of an output section.
1063   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
1064     std::string s(arg);
1065     if (config->machine == I386 && !isDecorated(s))
1066       s = "_" + s;
1067 
1068     if (set.count(s) == 0) {
1069       if (config->warnMissingOrderSymbol)
1070         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
1071     }
1072     else
1073       config->order[s] = INT_MIN + config->order.size();
1074   }
1075 
1076   // Include in /reproduce: output if applicable.
1077   driver->takeBuffer(std::move(mb));
1078 }
1079 
1080 static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) {
1081   std::unique_ptr<MemoryBuffer> mb =
1082       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1083                                   /*RequiresNullTerminator=*/false,
1084                                   /*IsVolatile=*/true),
1085             "could not open " + path);
1086 
1087   // Build a map from symbol name to section.
1088   DenseMap<StringRef, Symbol *> map;
1089   for (ObjFile *file : ctx.objFileInstances)
1090     for (Symbol *sym : file->getSymbols())
1091       if (sym)
1092         map[sym->getName()] = sym;
1093 
1094   auto findSection = [&](StringRef name) -> SectionChunk * {
1095     Symbol *sym = map.lookup(name);
1096     if (!sym) {
1097       if (config->warnMissingOrderSymbol)
1098         warn(path + ": no such symbol: " + name);
1099       return nullptr;
1100     }
1101 
1102     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1103       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1104     return nullptr;
1105   };
1106 
1107   for (StringRef line : args::getLines(*mb)) {
1108     SmallVector<StringRef, 3> fields;
1109     line.split(fields, ' ');
1110     uint64_t count;
1111 
1112     if (fields.size() != 3 || !to_integer(fields[2], count)) {
1113       error(path + ": parse error");
1114       return;
1115     }
1116 
1117     if (SectionChunk *from = findSection(fields[0]))
1118       if (SectionChunk *to = findSection(fields[1]))
1119         config->callGraphProfile[{from, to}] += count;
1120   }
1121 
1122   // Include in /reproduce: output if applicable.
1123   driver->takeBuffer(std::move(mb));
1124 }
1125 
1126 static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1127   for (ObjFile *obj : ctx.objFileInstances) {
1128     if (obj->callgraphSec) {
1129       ArrayRef<uint8_t> contents;
1130       cantFail(
1131           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1132       BinaryStreamReader reader(contents, support::little);
1133       while (!reader.empty()) {
1134         uint32_t fromIndex, toIndex;
1135         uint64_t count;
1136         if (Error err = reader.readInteger(fromIndex))
1137           fatal(toString(obj) + ": Expected 32-bit integer");
1138         if (Error err = reader.readInteger(toIndex))
1139           fatal(toString(obj) + ": Expected 32-bit integer");
1140         if (Error err = reader.readInteger(count))
1141           fatal(toString(obj) + ": Expected 64-bit integer");
1142         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1143         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1144         if (!fromSym || !toSym)
1145           continue;
1146         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1147         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1148         if (from && to)
1149           config->callGraphProfile[{from, to}] += count;
1150       }
1151     }
1152   }
1153 }
1154 
1155 static void markAddrsig(Symbol *s) {
1156   if (auto *d = dyn_cast_or_null<Defined>(s))
1157     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1158       c->keepUnique = true;
1159 }
1160 
1161 static void findKeepUniqueSections(COFFLinkerContext &ctx) {
1162   // Exported symbols could be address-significant in other executables or DSOs,
1163   // so we conservatively mark them as address-significant.
1164   for (Export &r : config->exports)
1165     markAddrsig(r.sym);
1166 
1167   // Visit the address-significance table in each object file and mark each
1168   // referenced symbol as address-significant.
1169   for (ObjFile *obj : ctx.objFileInstances) {
1170     ArrayRef<Symbol *> syms = obj->getSymbols();
1171     if (obj->addrsigSec) {
1172       ArrayRef<uint8_t> contents;
1173       cantFail(
1174           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1175       const uint8_t *cur = contents.begin();
1176       while (cur != contents.end()) {
1177         unsigned size;
1178         const char *err;
1179         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1180         if (err)
1181           fatal(toString(obj) + ": could not decode addrsig section: " + err);
1182         if (symIndex >= syms.size())
1183           fatal(toString(obj) + ": invalid symbol index in addrsig section");
1184         markAddrsig(syms[symIndex]);
1185         cur += size;
1186       }
1187     } else {
1188       // If an object file does not have an address-significance table,
1189       // conservatively mark all of its symbols as address-significant.
1190       for (Symbol *s : syms)
1191         markAddrsig(s);
1192     }
1193   }
1194 }
1195 
1196 // link.exe replaces each %foo% in altPath with the contents of environment
1197 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1198 // of pdb's output path) and _EXT (expands to the extension of the output
1199 // binary).
1200 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1201 // vars.
1202 static void parsePDBAltPath(StringRef altPath) {
1203   SmallString<128> buf;
1204   StringRef pdbBasename =
1205       sys::path::filename(config->pdbPath, sys::path::Style::windows);
1206   StringRef binaryExtension =
1207       sys::path::extension(config->outputFile, sys::path::Style::windows);
1208   if (!binaryExtension.empty())
1209     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1210 
1211   // Invariant:
1212   //   +--------- cursor ('a...' might be the empty string).
1213   //   |   +----- firstMark
1214   //   |   |   +- secondMark
1215   //   v   v   v
1216   //   a...%...%...
1217   size_t cursor = 0;
1218   while (cursor < altPath.size()) {
1219     size_t firstMark, secondMark;
1220     if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
1221         (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
1222       // Didn't find another full fragment, treat rest of string as literal.
1223       buf.append(altPath.substr(cursor));
1224       break;
1225     }
1226 
1227     // Found a full fragment. Append text in front of first %, and interpret
1228     // text between first and second % as variable name.
1229     buf.append(altPath.substr(cursor, firstMark - cursor));
1230     StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1231     if (var.equals_insensitive("%_pdb%"))
1232       buf.append(pdbBasename);
1233     else if (var.equals_insensitive("%_ext%"))
1234       buf.append(binaryExtension);
1235     else {
1236       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1237            var + " as literal");
1238       buf.append(var);
1239     }
1240 
1241     cursor = secondMark + 1;
1242   }
1243 
1244   config->pdbAltPath = buf;
1245 }
1246 
1247 /// Convert resource files and potentially merge input resource object
1248 /// trees into one resource tree.
1249 /// Call after ObjFile::Instances is complete.
1250 void LinkerDriver::convertResources() {
1251   std::vector<ObjFile *> resourceObjFiles;
1252 
1253   for (ObjFile *f : ctx.objFileInstances) {
1254     if (f->isResourceObjFile())
1255       resourceObjFiles.push_back(f);
1256   }
1257 
1258   if (!config->mingw &&
1259       (resourceObjFiles.size() > 1 ||
1260        (resourceObjFiles.size() == 1 && !resources.empty()))) {
1261     error((!resources.empty() ? "internal .obj file created from .res files"
1262                               : toString(resourceObjFiles[1])) +
1263           ": more than one resource obj file not allowed, already got " +
1264           toString(resourceObjFiles.front()));
1265     return;
1266   }
1267 
1268   if (resources.empty() && resourceObjFiles.size() <= 1) {
1269     // No resources to convert, and max one resource object file in
1270     // the input. Keep that preconverted resource section as is.
1271     for (ObjFile *f : resourceObjFiles)
1272       f->includeResourceChunks();
1273     return;
1274   }
1275   ObjFile *f =
1276       make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1277   ctx.symtab.addFile(f);
1278   f->includeResourceChunks();
1279 }
1280 
1281 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1282 // automatically exported by default. This behavior can be forced by the
1283 // -export-all-symbols option, so that it happens even when exports are
1284 // explicitly specified. The automatic behavior can be disabled using the
1285 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1286 // than MinGW in the case that nothing is explicitly exported.
1287 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1288   if (!args.hasArg(OPT_export_all_symbols)) {
1289     if (!config->dll)
1290       return;
1291 
1292     if (!config->exports.empty())
1293       return;
1294     if (args.hasArg(OPT_exclude_all_symbols))
1295       return;
1296   }
1297 
1298   AutoExporter exporter;
1299 
1300   for (auto *arg : args.filtered(OPT_wholearchive_file))
1301     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1302       exporter.addWholeArchive(*path);
1303 
1304   ctx.symtab.forEachSymbol([&](Symbol *s) {
1305     auto *def = dyn_cast<Defined>(s);
1306     if (!exporter.shouldExport(ctx, def))
1307       return;
1308 
1309     if (!def->isGCRoot) {
1310       def->isGCRoot = true;
1311       config->gcroot.push_back(def);
1312     }
1313 
1314     Export e;
1315     e.name = def->getName();
1316     e.sym = def;
1317     if (Chunk *c = def->getChunk())
1318       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1319         e.data = true;
1320     s->isUsedInRegularObj = true;
1321     config->exports.push_back(e);
1322   });
1323 }
1324 
1325 // lld has a feature to create a tar file containing all input files as well as
1326 // all command line options, so that other people can run lld again with exactly
1327 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1328 //
1329 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1330 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1331 // with Microsoft link.exe.
1332 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1333   if (auto *arg = args.getLastArg(OPT_reproduce))
1334     return std::string(arg->getValue());
1335 
1336   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1337     SmallString<64> path = StringRef(arg->getValue());
1338     sys::path::append(path, "repro.tar");
1339     return std::string(path);
1340   }
1341 
1342   // This is intentionally not guarded by OPT_lldignoreenv since writing
1343   // a repro tar file doesn't affect the main output.
1344   if (auto *path = getenv("LLD_REPRODUCE"))
1345     return std::string(path);
1346 
1347   return None;
1348 }
1349 
1350 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1351   ScopedTimer rootTimer(ctx.rootTimer);
1352 
1353   // Needed for LTO.
1354   InitializeAllTargetInfos();
1355   InitializeAllTargets();
1356   InitializeAllTargetMCs();
1357   InitializeAllAsmParsers();
1358   InitializeAllAsmPrinters();
1359 
1360   // If the first command line argument is "/lib", link.exe acts like lib.exe.
1361   // We call our own implementation of lib.exe that understands bitcode files.
1362   if (argsArr.size() > 1 &&
1363       (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1364        StringRef(argsArr[1]).equals_insensitive("-lib"))) {
1365     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1366       fatal("lib failed");
1367     return;
1368   }
1369 
1370   // Parse command line options.
1371   ArgParser parser;
1372   opt::InputArgList args = parser.parse(argsArr);
1373 
1374   // Parse and evaluate -mllvm options.
1375   std::vector<const char *> v;
1376   v.push_back("lld-link (LLVM option parsing)");
1377   for (auto *arg : args.filtered(OPT_mllvm))
1378     v.push_back(arg->getValue());
1379   cl::ResetAllOptionOccurrences();
1380   cl::ParseCommandLineOptions(v.size(), v.data());
1381 
1382   // Handle /errorlimit early, because error() depends on it.
1383   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1384     int n = 20;
1385     StringRef s = arg->getValue();
1386     if (s.getAsInteger(10, n))
1387       error(arg->getSpelling() + " number expected, but got " + s);
1388     errorHandler().errorLimit = n;
1389   }
1390 
1391   // Handle /help
1392   if (args.hasArg(OPT_help)) {
1393     printHelp(argsArr[0]);
1394     return;
1395   }
1396 
1397   // /threads: takes a positive integer and provides the default value for
1398   // /opt:lldltojobs=.
1399   if (auto *arg = args.getLastArg(OPT_threads)) {
1400     StringRef v(arg->getValue());
1401     unsigned threads = 0;
1402     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1403       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1404             arg->getValue() + "'");
1405     parallel::strategy = hardware_concurrency(threads);
1406     config->thinLTOJobs = v.str();
1407   }
1408 
1409   if (args.hasArg(OPT_show_timing))
1410     config->showTiming = true;
1411 
1412   config->showSummary = args.hasArg(OPT_summary);
1413 
1414   // Handle --version, which is an lld extension. This option is a bit odd
1415   // because it doesn't start with "/", but we deliberately chose "--" to
1416   // avoid conflict with /version and for compatibility with clang-cl.
1417   if (args.hasArg(OPT_dash_dash_version)) {
1418     message(getLLDVersion());
1419     return;
1420   }
1421 
1422   // Handle /lldmingw early, since it can potentially affect how other
1423   // options are handled.
1424   config->mingw = args.hasArg(OPT_lldmingw);
1425 
1426   // Handle /linkrepro and /reproduce.
1427   if (Optional<std::string> path = getReproduceFile(args)) {
1428     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1429         TarWriter::create(*path, sys::path::stem(*path));
1430 
1431     if (errOrWriter) {
1432       tar = std::move(*errOrWriter);
1433     } else {
1434       error("/linkrepro: failed to open " + *path + ": " +
1435             toString(errOrWriter.takeError()));
1436     }
1437   }
1438 
1439   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1440     if (args.hasArg(OPT_deffile))
1441       config->noEntry = true;
1442     else
1443       fatal("no input files");
1444   }
1445 
1446   // Construct search path list.
1447   searchPaths.push_back("");
1448   for (auto *arg : args.filtered(OPT_libpath))
1449     searchPaths.push_back(arg->getValue());
1450   detectWinSysRoot(args);
1451   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
1452     addLibSearchPaths();
1453 
1454   // Handle /ignore
1455   for (auto *arg : args.filtered(OPT_ignore)) {
1456     SmallVector<StringRef, 8> vec;
1457     StringRef(arg->getValue()).split(vec, ',');
1458     for (StringRef s : vec) {
1459       if (s == "4037")
1460         config->warnMissingOrderSymbol = false;
1461       else if (s == "4099")
1462         config->warnDebugInfoUnusable = false;
1463       else if (s == "4217")
1464         config->warnLocallyDefinedImported = false;
1465       else if (s == "longsections")
1466         config->warnLongSectionNames = false;
1467       // Other warning numbers are ignored.
1468     }
1469   }
1470 
1471   // Handle /out
1472   if (auto *arg = args.getLastArg(OPT_out))
1473     config->outputFile = arg->getValue();
1474 
1475   // Handle /verbose
1476   if (args.hasArg(OPT_verbose))
1477     config->verbose = true;
1478   errorHandler().verbose = config->verbose;
1479 
1480   // Handle /force or /force:unresolved
1481   if (args.hasArg(OPT_force, OPT_force_unresolved))
1482     config->forceUnresolved = true;
1483 
1484   // Handle /force or /force:multiple
1485   if (args.hasArg(OPT_force, OPT_force_multiple))
1486     config->forceMultiple = true;
1487 
1488   // Handle /force or /force:multipleres
1489   if (args.hasArg(OPT_force, OPT_force_multipleres))
1490     config->forceMultipleRes = true;
1491 
1492   // Handle /debug
1493   DebugKind debug = parseDebugKind(args);
1494   if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1495       debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
1496     config->debug = true;
1497     config->incremental = true;
1498   }
1499 
1500   // Handle /demangle
1501   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1502 
1503   // Handle /debugtype
1504   config->debugTypes = parseDebugTypes(args);
1505 
1506   // Handle /driver[:uponly|:wdm].
1507   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1508                          args.hasArg(OPT_driver_uponly_wdm) ||
1509                          args.hasArg(OPT_driver_wdm_uponly);
1510   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1511                       args.hasArg(OPT_driver_uponly_wdm) ||
1512                       args.hasArg(OPT_driver_wdm_uponly);
1513   config->driver =
1514       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1515 
1516   // Handle /pdb
1517   bool shouldCreatePDB =
1518       (debug == DebugKind::Full || debug == DebugKind::GHash ||
1519        debug == DebugKind::NoGHash);
1520   if (shouldCreatePDB) {
1521     if (auto *arg = args.getLastArg(OPT_pdb))
1522       config->pdbPath = arg->getValue();
1523     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1524       config->pdbAltPath = arg->getValue();
1525     if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1526       parsePDBPageSize(arg->getValue());
1527     if (args.hasArg(OPT_natvis))
1528       config->natvisFiles = args.getAllArgValues(OPT_natvis);
1529     if (args.hasArg(OPT_pdbstream)) {
1530       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1531         const std::pair<StringRef, StringRef> nameFile = value.split("=");
1532         const StringRef name = nameFile.first;
1533         const std::string file = nameFile.second.str();
1534         config->namedStreams[name] = file;
1535       }
1536     }
1537 
1538     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1539       config->pdbSourcePath = arg->getValue();
1540   }
1541 
1542   // Handle /pdbstripped
1543   if (args.hasArg(OPT_pdbstripped))
1544     warn("ignoring /pdbstripped flag, it is not yet supported");
1545 
1546   // Handle /noentry
1547   if (args.hasArg(OPT_noentry)) {
1548     if (args.hasArg(OPT_dll))
1549       config->noEntry = true;
1550     else
1551       error("/noentry must be specified with /dll");
1552   }
1553 
1554   // Handle /dll
1555   if (args.hasArg(OPT_dll)) {
1556     config->dll = true;
1557     config->manifestID = 2;
1558   }
1559 
1560   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1561   // because we need to explicitly check whether that option or its inverse was
1562   // present in the argument list in order to handle /fixed.
1563   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1564   if (dynamicBaseArg &&
1565       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1566     config->dynamicBase = false;
1567 
1568   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1569   // default setting for any other project type.", but link.exe defaults to
1570   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1571   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1572   if (fixed) {
1573     if (dynamicBaseArg &&
1574         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1575       error("/fixed must not be specified with /dynamicbase");
1576     } else {
1577       config->relocatable = false;
1578       config->dynamicBase = false;
1579     }
1580   }
1581 
1582   // Handle /appcontainer
1583   config->appContainer =
1584       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1585 
1586   // Handle /machine
1587   if (auto *arg = args.getLastArg(OPT_machine)) {
1588     config->machine = getMachineType(arg->getValue());
1589     if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1590       fatal(Twine("unknown /machine argument: ") + arg->getValue());
1591     addWinSysRootLibSearchPaths();
1592   }
1593 
1594   // Handle /nodefaultlib:<filename>
1595   for (auto *arg : args.filtered(OPT_nodefaultlib))
1596     config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1597 
1598   // Handle /nodefaultlib
1599   if (args.hasArg(OPT_nodefaultlib_all))
1600     config->noDefaultLibAll = true;
1601 
1602   // Handle /base
1603   if (auto *arg = args.getLastArg(OPT_base))
1604     parseNumbers(arg->getValue(), &config->imageBase);
1605 
1606   // Handle /filealign
1607   if (auto *arg = args.getLastArg(OPT_filealign)) {
1608     parseNumbers(arg->getValue(), &config->fileAlign);
1609     if (!isPowerOf2_64(config->fileAlign))
1610       error("/filealign: not a power of two: " + Twine(config->fileAlign));
1611   }
1612 
1613   // Handle /stack
1614   if (auto *arg = args.getLastArg(OPT_stack))
1615     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1616 
1617   // Handle /guard:cf
1618   if (auto *arg = args.getLastArg(OPT_guard))
1619     parseGuard(arg->getValue());
1620 
1621   // Handle /heap
1622   if (auto *arg = args.getLastArg(OPT_heap))
1623     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1624 
1625   // Handle /version
1626   if (auto *arg = args.getLastArg(OPT_version))
1627     parseVersion(arg->getValue(), &config->majorImageVersion,
1628                  &config->minorImageVersion);
1629 
1630   // Handle /subsystem
1631   if (auto *arg = args.getLastArg(OPT_subsystem))
1632     parseSubsystem(arg->getValue(), &config->subsystem,
1633                    &config->majorSubsystemVersion,
1634                    &config->minorSubsystemVersion);
1635 
1636   // Handle /osversion
1637   if (auto *arg = args.getLastArg(OPT_osversion)) {
1638     parseVersion(arg->getValue(), &config->majorOSVersion,
1639                  &config->minorOSVersion);
1640   } else {
1641     config->majorOSVersion = config->majorSubsystemVersion;
1642     config->minorOSVersion = config->minorSubsystemVersion;
1643   }
1644 
1645   // Handle /timestamp
1646   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1647     if (arg->getOption().getID() == OPT_repro) {
1648       config->timestamp = 0;
1649       config->repro = true;
1650     } else {
1651       config->repro = false;
1652       StringRef value(arg->getValue());
1653       if (value.getAsInteger(0, config->timestamp))
1654         fatal(Twine("invalid timestamp: ") + value +
1655               ".  Expected 32-bit integer");
1656     }
1657   } else {
1658     config->repro = false;
1659     config->timestamp = time(nullptr);
1660   }
1661 
1662   // Handle /alternatename
1663   for (auto *arg : args.filtered(OPT_alternatename))
1664     parseAlternateName(arg->getValue());
1665 
1666   // Handle /include
1667   for (auto *arg : args.filtered(OPT_incl))
1668     addUndefined(arg->getValue());
1669 
1670   // Handle /implib
1671   if (auto *arg = args.getLastArg(OPT_implib))
1672     config->implib = arg->getValue();
1673 
1674   // Handle /opt.
1675   bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1676   Optional<ICFLevel> icfLevel = None;
1677   if (args.hasArg(OPT_profile))
1678     icfLevel = ICFLevel::None;
1679   unsigned tailMerge = 1;
1680   bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER;
1681   bool ltoDebugPM = false;
1682   for (auto *arg : args.filtered(OPT_opt)) {
1683     std::string str = StringRef(arg->getValue()).lower();
1684     SmallVector<StringRef, 1> vec;
1685     StringRef(str).split(vec, ',');
1686     for (StringRef s : vec) {
1687       if (s == "ref") {
1688         doGC = true;
1689       } else if (s == "noref") {
1690         doGC = false;
1691       } else if (s == "icf" || s.startswith("icf=")) {
1692         icfLevel = ICFLevel::All;
1693       } else if (s == "safeicf") {
1694         icfLevel = ICFLevel::Safe;
1695       } else if (s == "noicf") {
1696         icfLevel = ICFLevel::None;
1697       } else if (s == "lldtailmerge") {
1698         tailMerge = 2;
1699       } else if (s == "nolldtailmerge") {
1700         tailMerge = 0;
1701       } else if (s == "ltonewpassmanager") {
1702         ltoNewPM = true;
1703       } else if (s == "noltonewpassmanager") {
1704         ltoNewPM = false;
1705       } else if (s == "ltodebugpassmanager") {
1706         ltoDebugPM = true;
1707       } else if (s == "noltodebugpassmanager") {
1708         ltoDebugPM = false;
1709       } else if (s.startswith("lldlto=")) {
1710         StringRef optLevel = s.substr(7);
1711         if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1712           error("/opt:lldlto: invalid optimization level: " + optLevel);
1713       } else if (s.startswith("lldltojobs=")) {
1714         StringRef jobs = s.substr(11);
1715         if (!get_threadpool_strategy(jobs))
1716           error("/opt:lldltojobs: invalid job count: " + jobs);
1717         config->thinLTOJobs = jobs.str();
1718       } else if (s.startswith("lldltopartitions=")) {
1719         StringRef n = s.substr(17);
1720         if (n.getAsInteger(10, config->ltoPartitions) ||
1721             config->ltoPartitions == 0)
1722           error("/opt:lldltopartitions: invalid partition count: " + n);
1723       } else if (s != "lbr" && s != "nolbr")
1724         error("/opt: unknown option: " + s);
1725     }
1726   }
1727 
1728   if (!icfLevel)
1729     icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
1730   config->doGC = doGC;
1731   config->doICF = icfLevel.getValue();
1732   config->tailMerge =
1733       (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1734   config->ltoNewPassManager = ltoNewPM;
1735   config->ltoDebugPassManager = ltoDebugPM;
1736 
1737   // Handle /lldsavetemps
1738   if (args.hasArg(OPT_lldsavetemps))
1739     config->saveTemps = true;
1740 
1741   // Handle /kill-at
1742   if (args.hasArg(OPT_kill_at))
1743     config->killAt = true;
1744 
1745   // Handle /lldltocache
1746   if (auto *arg = args.getLastArg(OPT_lldltocache))
1747     config->ltoCache = arg->getValue();
1748 
1749   // Handle /lldsavecachepolicy
1750   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1751     config->ltoCachePolicy = CHECK(
1752         parseCachePruningPolicy(arg->getValue()),
1753         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1754 
1755   // Handle /failifmismatch
1756   for (auto *arg : args.filtered(OPT_failifmismatch))
1757     checkFailIfMismatch(arg->getValue(), nullptr);
1758 
1759   // Handle /merge
1760   for (auto *arg : args.filtered(OPT_merge))
1761     parseMerge(arg->getValue());
1762 
1763   // Add default section merging rules after user rules. User rules take
1764   // precedence, but we will emit a warning if there is a conflict.
1765   parseMerge(".idata=.rdata");
1766   parseMerge(".didat=.rdata");
1767   parseMerge(".edata=.rdata");
1768   parseMerge(".xdata=.rdata");
1769   parseMerge(".bss=.data");
1770 
1771   if (config->mingw) {
1772     parseMerge(".ctors=.rdata");
1773     parseMerge(".dtors=.rdata");
1774     parseMerge(".CRT=.rdata");
1775   }
1776 
1777   // Handle /section
1778   for (auto *arg : args.filtered(OPT_section))
1779     parseSection(arg->getValue());
1780 
1781   // Handle /align
1782   if (auto *arg = args.getLastArg(OPT_align)) {
1783     parseNumbers(arg->getValue(), &config->align);
1784     if (!isPowerOf2_64(config->align))
1785       error("/align: not a power of two: " + StringRef(arg->getValue()));
1786     if (!args.hasArg(OPT_driver))
1787       warn("/align specified without /driver; image may not run");
1788   }
1789 
1790   // Handle /aligncomm
1791   for (auto *arg : args.filtered(OPT_aligncomm))
1792     parseAligncomm(arg->getValue());
1793 
1794   // Handle /manifestdependency.
1795   for (auto *arg : args.filtered(OPT_manifestdependency))
1796     config->manifestDependencies.insert(arg->getValue());
1797 
1798   // Handle /manifest and /manifest:
1799   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1800     if (arg->getOption().getID() == OPT_manifest)
1801       config->manifest = Configuration::SideBySide;
1802     else
1803       parseManifest(arg->getValue());
1804   }
1805 
1806   // Handle /manifestuac
1807   if (auto *arg = args.getLastArg(OPT_manifestuac))
1808     parseManifestUAC(arg->getValue());
1809 
1810   // Handle /manifestfile
1811   if (auto *arg = args.getLastArg(OPT_manifestfile))
1812     config->manifestFile = arg->getValue();
1813 
1814   // Handle /manifestinput
1815   for (auto *arg : args.filtered(OPT_manifestinput))
1816     config->manifestInput.push_back(arg->getValue());
1817 
1818   if (!config->manifestInput.empty() &&
1819       config->manifest != Configuration::Embed) {
1820     fatal("/manifestinput: requires /manifest:embed");
1821   }
1822 
1823   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1824   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1825                              args.hasArg(OPT_thinlto_index_only_arg);
1826   config->thinLTOIndexOnlyArg =
1827       args.getLastArgValue(OPT_thinlto_index_only_arg);
1828   config->thinLTOPrefixReplace =
1829       getOldNewOptions(args, OPT_thinlto_prefix_replace);
1830   config->thinLTOObjectSuffixReplace =
1831       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1832   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1833   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1834   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1835   // Handle miscellaneous boolean flags.
1836   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1837                                             OPT_lto_pgo_warn_mismatch_no, true);
1838   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1839   config->allowIsolation =
1840       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1841   config->incremental =
1842       args.hasFlag(OPT_incremental, OPT_incremental_no,
1843                    !config->doGC && config->doICF == ICFLevel::None &&
1844                        !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
1845   config->integrityCheck =
1846       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1847   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1848   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1849   for (auto *arg : args.filtered(OPT_swaprun))
1850     parseSwaprun(arg->getValue());
1851   config->terminalServerAware =
1852       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1853   config->debugDwarf = debug == DebugKind::Dwarf;
1854   config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
1855   config->debugSymtab = debug == DebugKind::Symtab;
1856   config->autoImport =
1857       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1858   config->pseudoRelocs = args.hasFlag(
1859       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1860   config->callGraphProfileSort = args.hasFlag(
1861       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1862   config->stdcallFixup =
1863       args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
1864   config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
1865 
1866   // Don't warn about long section names, such as .debug_info, for mingw or
1867   // when -debug:dwarf is requested.
1868   if (config->mingw || config->debugDwarf)
1869     config->warnLongSectionNames = false;
1870 
1871   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
1872   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
1873 
1874   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
1875     warn("/lldmap and /map have the same output file '" + config->mapFile +
1876          "'.\n>>> ignoring /lldmap");
1877     config->lldmapFile.clear();
1878   }
1879 
1880   if (config->incremental && args.hasArg(OPT_profile)) {
1881     warn("ignoring '/incremental' due to '/profile' specification");
1882     config->incremental = false;
1883   }
1884 
1885   if (config->incremental && args.hasArg(OPT_order)) {
1886     warn("ignoring '/incremental' due to '/order' specification");
1887     config->incremental = false;
1888   }
1889 
1890   if (config->incremental && config->doGC) {
1891     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1892          "disable");
1893     config->incremental = false;
1894   }
1895 
1896   if (config->incremental && config->doICF != ICFLevel::None) {
1897     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1898          "disable");
1899     config->incremental = false;
1900   }
1901 
1902   if (errorCount())
1903     return;
1904 
1905   std::set<sys::fs::UniqueID> wholeArchives;
1906   for (auto *arg : args.filtered(OPT_wholearchive_file))
1907     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1908       if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1909         wholeArchives.insert(*id);
1910 
1911   // A predicate returning true if a given path is an argument for
1912   // /wholearchive:, or /wholearchive is enabled globally.
1913   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1914   // needs to be handled as "/wholearchive:foo.obj foo.obj".
1915   auto isWholeArchive = [&](StringRef path) -> bool {
1916     if (args.hasArg(OPT_wholearchive_flag))
1917       return true;
1918     if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1919       return wholeArchives.count(*id);
1920     return false;
1921   };
1922 
1923   // Create a list of input files. These can be given as OPT_INPUT options
1924   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1925   // and OPT_end_lib.
1926   bool inLib = false;
1927   for (auto *arg : args) {
1928     switch (arg->getOption().getID()) {
1929     case OPT_end_lib:
1930       if (!inLib)
1931         error("stray " + arg->getSpelling());
1932       inLib = false;
1933       break;
1934     case OPT_start_lib:
1935       if (inLib)
1936         error("nested " + arg->getSpelling());
1937       inLib = true;
1938       break;
1939     case OPT_wholearchive_file:
1940       if (Optional<StringRef> path = findFile(arg->getValue()))
1941         enqueuePath(*path, true, inLib);
1942       break;
1943     case OPT_INPUT:
1944       if (Optional<StringRef> path = findFile(arg->getValue()))
1945         enqueuePath(*path, isWholeArchive(*path), inLib);
1946       break;
1947     default:
1948       // Ignore other options.
1949       break;
1950     }
1951   }
1952 
1953   // Read all input files given via the command line.
1954   run();
1955   if (errorCount())
1956     return;
1957 
1958   // We should have inferred a machine type by now from the input files, but if
1959   // not we assume x64.
1960   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1961     warn("/machine is not specified. x64 is assumed");
1962     config->machine = AMD64;
1963     addWinSysRootLibSearchPaths();
1964   }
1965   config->wordsize = config->is64() ? 8 : 4;
1966 
1967   // Process files specified as /defaultlib. These must be processed after
1968   // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
1969   for (auto *arg : args.filtered(OPT_defaultlib))
1970     if (Optional<StringRef> path = findLib(arg->getValue()))
1971       enqueuePath(*path, false, false);
1972   run();
1973   if (errorCount())
1974     return;
1975 
1976   // Handle /safeseh, x86 only, on by default, except for mingw.
1977   if (config->machine == I386) {
1978     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
1979     config->noSEH = args.hasArg(OPT_noseh);
1980   }
1981 
1982   // Handle /functionpadmin
1983   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1984     parseFunctionPadMin(arg, config->machine);
1985 
1986   if (tar) {
1987     tar->append("response.txt",
1988                 createResponseFile(args, filePaths,
1989                                    ArrayRef<StringRef>(searchPaths).slice(1)));
1990   }
1991 
1992   // Handle /largeaddressaware
1993   config->largeAddressAware = args.hasFlag(
1994       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1995 
1996   // Handle /highentropyva
1997   config->highEntropyVA =
1998       config->is64() &&
1999       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
2000 
2001   if (!config->dynamicBase &&
2002       (config->machine == ARMNT || config->machine == ARM64))
2003     error("/dynamicbase:no is not compatible with " +
2004           machineToStr(config->machine));
2005 
2006   // Handle /export
2007   for (auto *arg : args.filtered(OPT_export)) {
2008     Export e = parseExport(arg->getValue());
2009     if (config->machine == I386) {
2010       if (!isDecorated(e.name))
2011         e.name = saver().save("_" + e.name);
2012       if (!e.extName.empty() && !isDecorated(e.extName))
2013         e.extName = saver().save("_" + e.extName);
2014     }
2015     config->exports.push_back(e);
2016   }
2017 
2018   // Handle /def
2019   if (auto *arg = args.getLastArg(OPT_deffile)) {
2020     // parseModuleDefs mutates Config object.
2021     parseModuleDefs(arg->getValue());
2022   }
2023 
2024   // Handle generation of import library from a def file.
2025   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
2026     fixupExports();
2027     createImportLibrary(/*asLib=*/true);
2028     return;
2029   }
2030 
2031   // Windows specific -- if no /subsystem is given, we need to infer
2032   // that from entry point name.  Must happen before /entry handling,
2033   // and after the early return when just writing an import library.
2034   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
2035     config->subsystem = inferSubsystem();
2036     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
2037       fatal("subsystem must be defined");
2038   }
2039 
2040   // Handle /entry and /dll
2041   if (auto *arg = args.getLastArg(OPT_entry)) {
2042     config->entry = addUndefined(mangle(arg->getValue()));
2043   } else if (!config->entry && !config->noEntry) {
2044     if (args.hasArg(OPT_dll)) {
2045       StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
2046                                               : "_DllMainCRTStartup";
2047       config->entry = addUndefined(s);
2048     } else if (config->driverWdm) {
2049       // /driver:wdm implies /entry:_NtProcessStartup
2050       config->entry = addUndefined(mangle("_NtProcessStartup"));
2051     } else {
2052       // Windows specific -- If entry point name is not given, we need to
2053       // infer that from user-defined entry name.
2054       StringRef s = findDefaultEntry();
2055       if (s.empty())
2056         fatal("entry point must be defined");
2057       config->entry = addUndefined(s);
2058       log("Entry name inferred: " + s);
2059     }
2060   }
2061 
2062   // Handle /delayload
2063   for (auto *arg : args.filtered(OPT_delayload)) {
2064     config->delayLoads.insert(StringRef(arg->getValue()).lower());
2065     if (config->machine == I386) {
2066       config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
2067     } else {
2068       config->delayLoadHelper = addUndefined("__delayLoadHelper2");
2069     }
2070   }
2071 
2072   // Set default image name if neither /out or /def set it.
2073   if (config->outputFile.empty()) {
2074     config->outputFile = getOutputPath(
2075         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
2076   }
2077 
2078   // Fail early if an output file is not writable.
2079   if (auto e = tryCreateFile(config->outputFile)) {
2080     error("cannot open output file " + config->outputFile + ": " + e.message());
2081     return;
2082   }
2083 
2084   if (shouldCreatePDB) {
2085     // Put the PDB next to the image if no /pdb flag was passed.
2086     if (config->pdbPath.empty()) {
2087       config->pdbPath = config->outputFile;
2088       sys::path::replace_extension(config->pdbPath, ".pdb");
2089     }
2090 
2091     // The embedded PDB path should be the absolute path to the PDB if no
2092     // /pdbaltpath flag was passed.
2093     if (config->pdbAltPath.empty()) {
2094       config->pdbAltPath = config->pdbPath;
2095 
2096       // It's important to make the path absolute and remove dots.  This path
2097       // will eventually be written into the PE header, and certain Microsoft
2098       // tools won't work correctly if these assumptions are not held.
2099       sys::fs::make_absolute(config->pdbAltPath);
2100       sys::path::remove_dots(config->pdbAltPath);
2101     } else {
2102       // Don't do this earlier, so that Config->OutputFile is ready.
2103       parsePDBAltPath(config->pdbAltPath);
2104     }
2105   }
2106 
2107   // Set default image base if /base is not given.
2108   if (config->imageBase == uint64_t(-1))
2109     config->imageBase = getDefaultImageBase();
2110 
2111   ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
2112   if (config->machine == I386) {
2113     ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2114     ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
2115   }
2116 
2117   ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2118   ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2119   ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2120   ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2121   ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2122   ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2123   ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
2124   // Needed for MSVC 2017 15.5 CRT.
2125   ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2126   // Needed for MSVC 2019 16.8 CRT.
2127   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2128   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2129 
2130   if (config->pseudoRelocs) {
2131     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2132     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2133   }
2134   if (config->mingw) {
2135     ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2136     ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
2137   }
2138 
2139   // This code may add new undefined symbols to the link, which may enqueue more
2140   // symbol resolution tasks, so we need to continue executing tasks until we
2141   // converge.
2142   do {
2143     // Windows specific -- if entry point is not found,
2144     // search for its mangled names.
2145     if (config->entry)
2146       mangleMaybe(config->entry);
2147 
2148     // Windows specific -- Make sure we resolve all dllexported symbols.
2149     for (Export &e : config->exports) {
2150       if (!e.forwardTo.empty())
2151         continue;
2152       e.sym = addUndefined(e.name);
2153       if (!e.directives)
2154         e.symbolName = mangleMaybe(e.sym);
2155     }
2156 
2157     // Add weak aliases. Weak aliases is a mechanism to give remaining
2158     // undefined symbols final chance to be resolved successfully.
2159     for (auto pair : config->alternateNames) {
2160       StringRef from = pair.first;
2161       StringRef to = pair.second;
2162       Symbol *sym = ctx.symtab.find(from);
2163       if (!sym)
2164         continue;
2165       if (auto *u = dyn_cast<Undefined>(sym))
2166         if (!u->weakAlias)
2167           u->weakAlias = ctx.symtab.addUndefined(to);
2168     }
2169 
2170     // If any inputs are bitcode files, the LTO code generator may create
2171     // references to library functions that are not explicit in the bitcode
2172     // file's symbol table. If any of those library functions are defined in a
2173     // bitcode file in an archive member, we need to arrange to use LTO to
2174     // compile those archive members by adding them to the link beforehand.
2175     if (!ctx.bitcodeFileInstances.empty())
2176       for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2177         ctx.symtab.addLibcall(s);
2178 
2179     // Windows specific -- if __load_config_used can be resolved, resolve it.
2180     if (ctx.symtab.findUnderscore("_load_config_used"))
2181       addUndefined(mangle("_load_config_used"));
2182   } while (run());
2183 
2184   if (args.hasArg(OPT_include_optional)) {
2185     // Handle /includeoptional
2186     for (auto *arg : args.filtered(OPT_include_optional))
2187       if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
2188         addUndefined(arg->getValue());
2189     while (run());
2190   }
2191 
2192   // Create wrapped symbols for -wrap option.
2193   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2194   // Load more object files that might be needed for wrapped symbols.
2195   if (!wrapped.empty())
2196     while (run());
2197 
2198   if (config->autoImport || config->stdcallFixup) {
2199     // MinGW specific.
2200     // Load any further object files that might be needed for doing automatic
2201     // imports, and do stdcall fixups.
2202     //
2203     // For cases with no automatically imported symbols, this iterates once
2204     // over the symbol table and doesn't do anything.
2205     //
2206     // For the normal case with a few automatically imported symbols, this
2207     // should only need to be run once, since each new object file imported
2208     // is an import library and wouldn't add any new undefined references,
2209     // but there's nothing stopping the __imp_ symbols from coming from a
2210     // normal object file as well (although that won't be used for the
2211     // actual autoimport later on). If this pass adds new undefined references,
2212     // we won't iterate further to resolve them.
2213     //
2214     // If stdcall fixups only are needed for loading import entries from
2215     // a DLL without import library, this also just needs running once.
2216     // If it ends up pulling in more object files from static libraries,
2217     // (and maybe doing more stdcall fixups along the way), this would need
2218     // to loop these two calls.
2219     ctx.symtab.loadMinGWSymbols();
2220     run();
2221   }
2222 
2223   // At this point, we should not have any symbols that cannot be resolved.
2224   // If we are going to do codegen for link-time optimization, check for
2225   // unresolvable symbols first, so we don't spend time generating code that
2226   // will fail to link anyway.
2227   if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2228     ctx.symtab.reportUnresolvable();
2229   if (errorCount())
2230     return;
2231 
2232   config->hadExplicitExports = !config->exports.empty();
2233   if (config->mingw) {
2234     // In MinGW, all symbols are automatically exported if no symbols
2235     // are chosen to be exported.
2236     maybeExportMinGWSymbols(args);
2237   }
2238 
2239   // Do LTO by compiling bitcode input files to a set of native COFF files then
2240   // link those files (unless -thinlto-index-only was given, in which case we
2241   // resolve symbols and write indices, but don't generate native code or link).
2242   ctx.symtab.compileBitcodeFiles();
2243 
2244   // If -thinlto-index-only is given, we should create only "index
2245   // files" and not object files. Index file creation is already done
2246   // in compileBitcodeFiles, so we are done if that's the case.
2247   if (config->thinLTOIndexOnly)
2248     return;
2249 
2250   // If we generated native object files from bitcode files, this resolves
2251   // references to the symbols we use from them.
2252   run();
2253 
2254   // Apply symbol renames for -wrap.
2255   if (!wrapped.empty())
2256     wrapSymbols(ctx, wrapped);
2257 
2258   // Resolve remaining undefined symbols and warn about imported locals.
2259   ctx.symtab.resolveRemainingUndefines();
2260   if (errorCount())
2261     return;
2262 
2263   if (config->mingw) {
2264     // Make sure the crtend.o object is the last object file. This object
2265     // file can contain terminating section chunks that need to be placed
2266     // last. GNU ld processes files and static libraries explicitly in the
2267     // order provided on the command line, while lld will pull in needed
2268     // files from static libraries only after the last object file on the
2269     // command line.
2270     for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
2271          i != e; i++) {
2272       ObjFile *file = *i;
2273       if (isCrtend(file->getName())) {
2274         ctx.objFileInstances.erase(i);
2275         ctx.objFileInstances.push_back(file);
2276         break;
2277       }
2278     }
2279   }
2280 
2281   // Windows specific -- when we are creating a .dll file, we also
2282   // need to create a .lib file. In MinGW mode, we only do that when the
2283   // -implib option is given explicitly, for compatibility with GNU ld.
2284   if (!config->exports.empty() || config->dll) {
2285     fixupExports();
2286     if (!config->mingw || !config->implib.empty())
2287       createImportLibrary(/*asLib=*/false);
2288     assignExportOrdinals();
2289   }
2290 
2291   // Handle /output-def (MinGW specific).
2292   if (auto *arg = args.getLastArg(OPT_output_def))
2293     writeDefFile(arg->getValue());
2294 
2295   // Set extra alignment for .comm symbols
2296   for (auto pair : config->alignComm) {
2297     StringRef name = pair.first;
2298     uint32_t alignment = pair.second;
2299 
2300     Symbol *sym = ctx.symtab.find(name);
2301     if (!sym) {
2302       warn("/aligncomm symbol " + name + " not found");
2303       continue;
2304     }
2305 
2306     // If the symbol isn't common, it must have been replaced with a regular
2307     // symbol, which will carry its own alignment.
2308     auto *dc = dyn_cast<DefinedCommon>(sym);
2309     if (!dc)
2310       continue;
2311 
2312     CommonChunk *c = dc->getChunk();
2313     c->setAlignment(std::max(c->getAlignment(), alignment));
2314   }
2315 
2316   // Windows specific -- Create an embedded or side-by-side manifest.
2317   // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2318   // also passed.
2319   if (config->manifest == Configuration::Embed)
2320     addBuffer(createManifestRes(), false, false);
2321   else if (config->manifest == Configuration::SideBySide ||
2322            (config->manifest == Configuration::Default &&
2323             !config->manifestDependencies.empty()))
2324     createSideBySideManifest();
2325 
2326   // Handle /order. We want to do this at this moment because we
2327   // need a complete list of comdat sections to warn on nonexistent
2328   // functions.
2329   if (auto *arg = args.getLastArg(OPT_order)) {
2330     if (args.hasArg(OPT_call_graph_ordering_file))
2331       error("/order and /call-graph-order-file may not be used together");
2332     parseOrderFile(ctx, arg->getValue());
2333     config->callGraphProfileSort = false;
2334   }
2335 
2336   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2337   if (config->callGraphProfileSort) {
2338     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2339       parseCallGraphFile(ctx, arg->getValue());
2340     }
2341     readCallGraphsFromObjectFiles(ctx);
2342   }
2343 
2344   // Handle /print-symbol-order.
2345   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2346     config->printSymbolOrder = arg->getValue();
2347 
2348   // Identify unreferenced COMDAT sections.
2349   if (config->doGC) {
2350     if (config->mingw) {
2351       // markLive doesn't traverse .eh_frame, but the personality function is
2352       // only reached that way. The proper solution would be to parse and
2353       // traverse the .eh_frame section, like the ELF linker does.
2354       // For now, just manually try to retain the known possible personality
2355       // functions. This doesn't bring in more object files, but only marks
2356       // functions that already have been included to be retained.
2357       for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) {
2358         Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2359         if (d && !d->isGCRoot) {
2360           d->isGCRoot = true;
2361           config->gcroot.push_back(d);
2362         }
2363       }
2364     }
2365 
2366     markLive(ctx);
2367   }
2368 
2369   // Needs to happen after the last call to addFile().
2370   convertResources();
2371 
2372   // Identify identical COMDAT sections to merge them.
2373   if (config->doICF != ICFLevel::None) {
2374     findKeepUniqueSections(ctx);
2375     doICF(ctx, config->doICF);
2376   }
2377 
2378   // Write the result.
2379   writeResult(ctx);
2380 
2381   // Stop early so we can print the results.
2382   rootTimer.stop();
2383   if (config->showTiming)
2384     ctx.rootTimer.print();
2385 }
2386 
2387 } // namespace coff
2388 } // namespace lld
2389