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