]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/Driver.cpp
Upgrade our copies of clang, llvm, lld, lldb, compiler-rt and libc++ to
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / COFF / Driver.cpp
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Driver.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "MinGW.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "Writer.h"
17 #include "lld/Common/Driver.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "lld/Common/Version.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/BinaryFormat/Magic.h"
24 #include "llvm/Object/ArchiveWriter.h"
25 #include "llvm/Object/COFFImportFile.h"
26 #include "llvm/Object/COFFModuleDefinition.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Option/Option.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/TarWriter.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
37 #include <algorithm>
38 #include <memory>
39
40 #include <future>
41
42 using namespace llvm;
43 using namespace llvm::object;
44 using namespace llvm::COFF;
45 using llvm::sys::Process;
46
47 namespace lld {
48 namespace coff {
49
50 Configuration *Config;
51 LinkerDriver *Driver;
52
53 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
54   errorHandler().LogName = Args[0];
55   errorHandler().ErrorOS = &Diag;
56   errorHandler().ColorDiagnostics = Diag.has_colors();
57   errorHandler().ErrorLimitExceededMsg =
58       "too many errors emitted, stopping now"
59       " (use /ERRORLIMIT:0 to see all errors)";
60   errorHandler().ExitEarly = CanExitEarly;
61   Config = make<Configuration>();
62   Config->Argv = {Args.begin(), Args.end()};
63   Config->CanExitEarly = CanExitEarly;
64
65   Symtab = make<SymbolTable>();
66
67   Driver = make<LinkerDriver>();
68   Driver->link(Args);
69
70   // Call exit() if we can to avoid calling destructors.
71   if (CanExitEarly)
72     exitLld(errorCount() ? 1 : 0);
73
74   freeArena();
75   return !errorCount();
76 }
77
78 // Drop directory components and replace extension with ".exe" or ".dll".
79 static std::string getOutputPath(StringRef Path) {
80   auto P = Path.find_last_of("\\/");
81   StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
82   const char* E = Config->DLL ? ".dll" : ".exe";
83   return (S.substr(0, S.rfind('.')) + E).str();
84 }
85
86 // ErrorOr is not default constructible, so it cannot be used as the type
87 // parameter of a future.
88 // FIXME: We could open the file in createFutureForFile and avoid needing to
89 // return an error here, but for the moment that would cost us a file descriptor
90 // (a limited resource on Windows) for the duration that the future is pending.
91 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
92
93 // Create a std::future that opens and maps a file using the best strategy for
94 // the host platform.
95 static std::future<MBErrPair> createFutureForFile(std::string Path) {
96 #if LLVM_ON_WIN32
97   // On Windows, file I/O is relatively slow so it is best to do this
98   // asynchronously.
99   auto Strategy = std::launch::async;
100 #else
101   auto Strategy = std::launch::deferred;
102 #endif
103   return std::async(Strategy, [=]() {
104     auto MBOrErr = MemoryBuffer::getFile(Path);
105     if (!MBOrErr)
106       return MBErrPair{nullptr, MBOrErr.getError()};
107     return MBErrPair{std::move(*MBOrErr), std::error_code()};
108   });
109 }
110
111 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
112   MemoryBufferRef MBRef = *MB;
113   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
114
115   if (Driver->Tar)
116     Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
117                         MBRef.getBuffer());
118   return MBRef;
119 }
120
121 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
122                              bool WholeArchive) {
123   MemoryBufferRef MBRef = takeBuffer(std::move(MB));
124   FilePaths.push_back(MBRef.getBufferIdentifier());
125
126   // File type is detected by contents, not by file extension.
127   switch (identify_magic(MBRef.getBuffer())) {
128   case file_magic::windows_resource:
129     Resources.push_back(MBRef);
130     break;
131
132   case file_magic::archive:
133     if (WholeArchive) {
134       std::unique_ptr<Archive> File =
135           CHECK(Archive::create(MBRef),
136                 MBRef.getBufferIdentifier() + ": failed to parse archive");
137
138       for (MemoryBufferRef M : getArchiveMembers(File.get()))
139         addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
140       return;
141     }
142     Symtab->addFile(make<ArchiveFile>(MBRef));
143     break;
144
145   case file_magic::bitcode:
146     Symtab->addFile(make<BitcodeFile>(MBRef));
147     break;
148
149   case file_magic::coff_cl_gl_object:
150     error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
151           "Recompile without /GL");
152     break;
153
154   default:
155     Symtab->addFile(make<ObjFile>(MBRef));
156     break;
157   }
158 }
159
160 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
161   auto Future =
162       std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
163   std::string PathStr = Path;
164   enqueueTask([=]() {
165     auto MBOrErr = Future->get();
166     if (MBOrErr.second)
167       error("could not open " + PathStr + ": " + MBOrErr.second.message());
168     else
169       Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
170   });
171 }
172
173 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
174                                     StringRef ParentName) {
175   file_magic Magic = identify_magic(MB.getBuffer());
176   if (Magic == file_magic::coff_import_library) {
177     Symtab->addFile(make<ImportFile>(MB));
178     return;
179   }
180
181   InputFile *Obj;
182   if (Magic == file_magic::coff_object) {
183     Obj = make<ObjFile>(MB);
184   } else if (Magic == file_magic::bitcode) {
185     Obj = make<BitcodeFile>(MB);
186   } else {
187     error("unknown file type: " + MB.getBufferIdentifier());
188     return;
189   }
190
191   Obj->ParentName = ParentName;
192   Symtab->addFile(Obj);
193   log("Loaded " + toString(Obj) + " for " + SymName);
194 }
195
196 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
197                                         StringRef SymName,
198                                         StringRef ParentName) {
199   if (!C.getParent()->isThin()) {
200     MemoryBufferRef MB = CHECK(
201         C.getMemoryBufferRef(),
202         "could not get the buffer for the member defining symbol " + SymName);
203     enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
204     return;
205   }
206
207   auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
208       CHECK(C.getFullName(),
209             "could not get the filename for the member defining symbol " +
210                 SymName)));
211   enqueueTask([=]() {
212     auto MBOrErr = Future->get();
213     if (MBOrErr.second)
214       fatal("could not get the buffer for the member defining " + SymName +
215             ": " + MBOrErr.second.message());
216     Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
217                              ParentName);
218   });
219 }
220
221 static bool isDecorated(StringRef Sym) {
222   return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
223          (!Config->MinGW && Sym.contains('@'));
224 }
225
226 // Parses .drectve section contents and returns a list of files
227 // specified by /defaultlib.
228 void LinkerDriver::parseDirectives(StringRef S) {
229   ArgParser Parser;
230   // .drectve is always tokenized using Windows shell rules.
231   opt::InputArgList Args = Parser.parseDirectives(S);
232
233   for (auto *Arg : Args) {
234     switch (Arg->getOption().getUnaliasedOption().getID()) {
235     case OPT_aligncomm:
236       parseAligncomm(Arg->getValue());
237       break;
238     case OPT_alternatename:
239       parseAlternateName(Arg->getValue());
240       break;
241     case OPT_defaultlib:
242       if (Optional<StringRef> Path = findLib(Arg->getValue()))
243         enqueuePath(*Path, false);
244       break;
245     case OPT_entry:
246       Config->Entry = addUndefined(mangle(Arg->getValue()));
247       break;
248     case OPT_export: {
249       // If a common header file contains dllexported function
250       // declarations, many object files may end up with having the
251       // same /EXPORT options. In order to save cost of parsing them,
252       // we dedup them first.
253       if (!DirectivesExports.insert(Arg->getValue()).second)
254         break;
255
256       Export E = parseExport(Arg->getValue());
257       if (Config->Machine == I386 && Config->MinGW) {
258         if (!isDecorated(E.Name))
259           E.Name = Saver.save("_" + E.Name);
260         if (!E.ExtName.empty() && !isDecorated(E.ExtName))
261           E.ExtName = Saver.save("_" + E.ExtName);
262       }
263       E.Directives = true;
264       Config->Exports.push_back(E);
265       break;
266     }
267     case OPT_failifmismatch:
268       checkFailIfMismatch(Arg->getValue());
269       break;
270     case OPT_incl:
271       addUndefined(Arg->getValue());
272       break;
273     case OPT_merge:
274       parseMerge(Arg->getValue());
275       break;
276     case OPT_nodefaultlib:
277       Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
278       break;
279     case OPT_section:
280       parseSection(Arg->getValue());
281       break;
282     case OPT_subsystem:
283       parseSubsystem(Arg->getValue(), &Config->Subsystem,
284                      &Config->MajorOSVersion, &Config->MinorOSVersion);
285       break;
286     case OPT_editandcontinue:
287     case OPT_fastfail:
288     case OPT_guardsym:
289     case OPT_natvis:
290     case OPT_throwingnew:
291       break;
292     default:
293       error(Arg->getSpelling() + " is not allowed in .drectve");
294     }
295   }
296 }
297
298 // Find file from search paths. You can omit ".obj", this function takes
299 // care of that. Note that the returned path is not guaranteed to exist.
300 StringRef LinkerDriver::doFindFile(StringRef Filename) {
301   bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
302   if (HasPathSep)
303     return Filename;
304   bool HasExt = Filename.contains('.');
305   for (StringRef Dir : SearchPaths) {
306     SmallString<128> Path = Dir;
307     sys::path::append(Path, Filename);
308     if (sys::fs::exists(Path.str()))
309       return Saver.save(Path.str());
310     if (!HasExt) {
311       Path.append(".obj");
312       if (sys::fs::exists(Path.str()))
313         return Saver.save(Path.str());
314     }
315   }
316   return Filename;
317 }
318
319 // Resolves a file path. This never returns the same path
320 // (in that case, it returns None).
321 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
322   StringRef Path = doFindFile(Filename);
323   bool Seen = !VisitedFiles.insert(Path.lower()).second;
324   if (Seen)
325     return None;
326   if (Path.endswith_lower(".lib"))
327     VisitedLibs.insert(sys::path::filename(Path));
328   return Path;
329 }
330
331 // Find library file from search path.
332 StringRef LinkerDriver::doFindLib(StringRef Filename) {
333   // Add ".lib" to Filename if that has no file extension.
334   bool HasExt = Filename.contains('.');
335   if (!HasExt)
336     Filename = Saver.save(Filename + ".lib");
337   return doFindFile(Filename);
338 }
339
340 // Resolves a library path. /nodefaultlib options are taken into
341 // consideration. This never returns the same path (in that case,
342 // it returns None).
343 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
344   if (Config->NoDefaultLibAll)
345     return None;
346   if (!VisitedLibs.insert(Filename.lower()).second)
347     return None;
348   StringRef Path = doFindLib(Filename);
349   if (Config->NoDefaultLibs.count(Path))
350     return None;
351   if (!VisitedFiles.insert(Path.lower()).second)
352     return None;
353   return Path;
354 }
355
356 // Parses LIB environment which contains a list of search paths.
357 void LinkerDriver::addLibSearchPaths() {
358   Optional<std::string> EnvOpt = Process::GetEnv("LIB");
359   if (!EnvOpt.hasValue())
360     return;
361   StringRef Env = Saver.save(*EnvOpt);
362   while (!Env.empty()) {
363     StringRef Path;
364     std::tie(Path, Env) = Env.split(';');
365     SearchPaths.push_back(Path);
366   }
367 }
368
369 Symbol *LinkerDriver::addUndefined(StringRef Name) {
370   Symbol *B = Symtab->addUndefined(Name);
371   if (!B->IsGCRoot) {
372     B->IsGCRoot = true;
373     Config->GCRoot.push_back(B);
374   }
375   return B;
376 }
377
378 // Symbol names are mangled by appending "_" prefix on x86.
379 StringRef LinkerDriver::mangle(StringRef Sym) {
380   assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
381   if (Config->Machine == I386)
382     return Saver.save("_" + Sym);
383   return Sym;
384 }
385
386 // Windows specific -- find default entry point name.
387 StringRef LinkerDriver::findDefaultEntry() {
388   // User-defined main functions and their corresponding entry points.
389   static const char *Entries[][2] = {
390       {"main", "mainCRTStartup"},
391       {"wmain", "wmainCRTStartup"},
392       {"WinMain", "WinMainCRTStartup"},
393       {"wWinMain", "wWinMainCRTStartup"},
394   };
395   for (auto E : Entries) {
396     StringRef Entry = Symtab->findMangle(mangle(E[0]));
397     if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
398       return mangle(E[1]);
399   }
400   return "";
401 }
402
403 WindowsSubsystem LinkerDriver::inferSubsystem() {
404   if (Config->DLL)
405     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
406   if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
407     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
408   if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
409     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
410   return IMAGE_SUBSYSTEM_UNKNOWN;
411 }
412
413 static uint64_t getDefaultImageBase() {
414   if (Config->is64())
415     return Config->DLL ? 0x180000000 : 0x140000000;
416   return Config->DLL ? 0x10000000 : 0x400000;
417 }
418
419 static std::string createResponseFile(const opt::InputArgList &Args,
420                                       ArrayRef<StringRef> FilePaths,
421                                       ArrayRef<StringRef> SearchPaths) {
422   SmallString<0> Data;
423   raw_svector_ostream OS(Data);
424
425   for (auto *Arg : Args) {
426     switch (Arg->getOption().getID()) {
427     case OPT_linkrepro:
428     case OPT_INPUT:
429     case OPT_defaultlib:
430     case OPT_libpath:
431     case OPT_manifest:
432     case OPT_manifest_colon:
433     case OPT_manifestdependency:
434     case OPT_manifestfile:
435     case OPT_manifestinput:
436     case OPT_manifestuac:
437       break;
438     default:
439       OS << toString(*Arg) << "\n";
440     }
441   }
442
443   for (StringRef Path : SearchPaths) {
444     std::string RelPath = relativeToRoot(Path);
445     OS << "/libpath:" << quote(RelPath) << "\n";
446   }
447
448   for (StringRef Path : FilePaths)
449     OS << quote(relativeToRoot(Path)) << "\n";
450
451   return Data.str();
452 }
453
454 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
455   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
456   if (Args.hasArg(OPT_driver))
457     DebugTypes |= static_cast<unsigned>(DebugType::PData);
458   if (Args.hasArg(OPT_profile))
459     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
460   return DebugTypes;
461 }
462
463 static unsigned parseDebugType(StringRef Arg) {
464   SmallVector<StringRef, 3> Types;
465   Arg.split(Types, ',', /*KeepEmpty=*/false);
466
467   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
468   for (StringRef Type : Types)
469     DebugTypes |= StringSwitch<unsigned>(Type.lower())
470                       .Case("cv", static_cast<unsigned>(DebugType::CV))
471                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
472                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
473                       .Default(0);
474   return DebugTypes;
475 }
476
477 static std::string getMapFile(const opt::InputArgList &Args) {
478   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
479   if (!Arg)
480     return "";
481   if (Arg->getOption().getID() == OPT_lldmap_file)
482     return Arg->getValue();
483
484   assert(Arg->getOption().getID() == OPT_lldmap);
485   StringRef OutFile = Config->OutputFile;
486   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
487 }
488
489 static std::string getImplibPath() {
490   if (!Config->Implib.empty())
491     return Config->Implib;
492   SmallString<128> Out = StringRef(Config->OutputFile);
493   sys::path::replace_extension(Out, ".lib");
494   return Out.str();
495 }
496
497 //
498 // The import name is caculated as the following:
499 //
500 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
501 //   -----+----------------+---------------------+------------------
502 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
503 //    LIB | {value}        | {value}.dll         | {output name}.dll
504 //
505 static std::string getImportName(bool AsLib) {
506   SmallString<128> Out;
507
508   if (Config->ImportName.empty()) {
509     Out.assign(sys::path::filename(Config->OutputFile));
510     if (AsLib)
511       sys::path::replace_extension(Out, ".dll");
512   } else {
513     Out.assign(Config->ImportName);
514     if (!sys::path::has_extension(Out))
515       sys::path::replace_extension(Out,
516                                    (Config->DLL || AsLib) ? ".dll" : ".exe");
517   }
518
519   return Out.str();
520 }
521
522 static void createImportLibrary(bool AsLib) {
523   std::vector<COFFShortExport> Exports;
524   for (Export &E1 : Config->Exports) {
525     COFFShortExport E2;
526     E2.Name = E1.Name;
527     E2.SymbolName = E1.SymbolName;
528     E2.ExtName = E1.ExtName;
529     E2.Ordinal = E1.Ordinal;
530     E2.Noname = E1.Noname;
531     E2.Data = E1.Data;
532     E2.Private = E1.Private;
533     E2.Constant = E1.Constant;
534     Exports.push_back(E2);
535   }
536
537   auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
538                               Config->Machine, false);
539   handleAllErrors(std::move(E),
540                   [&](ErrorInfoBase &EIB) { error(EIB.message()); });
541 }
542
543 static void parseModuleDefs(StringRef Path) {
544   std::unique_ptr<MemoryBuffer> MB = CHECK(
545       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
546   COFFModuleDefinition M = check(parseCOFFModuleDefinition(
547       MB->getMemBufferRef(), Config->Machine, Config->MinGW));
548
549   if (Config->OutputFile.empty())
550     Config->OutputFile = Saver.save(M.OutputFile);
551   Config->ImportName = Saver.save(M.ImportName);
552   if (M.ImageBase)
553     Config->ImageBase = M.ImageBase;
554   if (M.StackReserve)
555     Config->StackReserve = M.StackReserve;
556   if (M.StackCommit)
557     Config->StackCommit = M.StackCommit;
558   if (M.HeapReserve)
559     Config->HeapReserve = M.HeapReserve;
560   if (M.HeapCommit)
561     Config->HeapCommit = M.HeapCommit;
562   if (M.MajorImageVersion)
563     Config->MajorImageVersion = M.MajorImageVersion;
564   if (M.MinorImageVersion)
565     Config->MinorImageVersion = M.MinorImageVersion;
566   if (M.MajorOSVersion)
567     Config->MajorOSVersion = M.MajorOSVersion;
568   if (M.MinorOSVersion)
569     Config->MinorOSVersion = M.MinorOSVersion;
570
571   for (COFFShortExport E1 : M.Exports) {
572     Export E2;
573     E2.Name = Saver.save(E1.Name);
574     if (E1.isWeak())
575       E2.ExtName = Saver.save(E1.ExtName);
576     E2.Ordinal = E1.Ordinal;
577     E2.Noname = E1.Noname;
578     E2.Data = E1.Data;
579     E2.Private = E1.Private;
580     E2.Constant = E1.Constant;
581     Config->Exports.push_back(E2);
582   }
583 }
584
585 // A helper function for filterBitcodeFiles.
586 static bool needsRebuilding(MemoryBufferRef MB) {
587   // The MSVC linker doesn't support thin archives, so if it's a thin
588   // archive, we always need to rebuild it.
589   std::unique_ptr<Archive> File =
590       CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
591   if (File->isThin())
592     return true;
593
594   // Returns true if the archive contains at least one bitcode file.
595   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
596     if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
597       return true;
598   return false;
599 }
600
601 // Opens a given path as an archive file and removes bitcode files
602 // from them if exists. This function is to appease the MSVC linker as
603 // their linker doesn't like archive files containing non-native
604 // object files.
605 //
606 // If a given archive doesn't contain bitcode files, the archive path
607 // is returned as-is. Otherwise, a new temporary file is created and
608 // its path is returned.
609 static Optional<std::string>
610 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
611   std::unique_ptr<MemoryBuffer> MB = CHECK(
612       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
613   MemoryBufferRef MBRef = MB->getMemBufferRef();
614   file_magic Magic = identify_magic(MBRef.getBuffer());
615
616   if (Magic == file_magic::bitcode)
617     return None;
618   if (Magic != file_magic::archive)
619     return Path.str();
620   if (!needsRebuilding(MBRef))
621     return Path.str();
622
623   std::unique_ptr<Archive> File =
624       CHECK(Archive::create(MBRef),
625             MBRef.getBufferIdentifier() + ": failed to parse archive");
626
627   std::vector<NewArchiveMember> New;
628   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
629     if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
630       New.emplace_back(Member);
631
632   if (New.empty())
633     return None;
634
635   log("Creating a temporary archive for " + Path + " to remove bitcode files");
636
637   SmallString<128> S;
638   if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
639                                              ".lib", S))
640     fatal("cannot create a temporary file: " + EC.message());
641   std::string Temp = S.str();
642   TemporaryFiles.push_back(Temp);
643
644   Error E =
645       llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
646                          /*Deterministics=*/true,
647                          /*Thin=*/false);
648   handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
649     error("failed to create a new archive " + S.str() + ": " + EI.message());
650   });
651   return Temp;
652 }
653
654 // Create response file contents and invoke the MSVC linker.
655 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
656   std::string Rsp = "/nologo\n";
657   std::vector<std::string> Temps;
658
659   // Write out archive members that we used in symbol resolution and pass these
660   // to MSVC before any archives, so that MSVC uses the same objects to satisfy
661   // references.
662   for (ObjFile *Obj : ObjFile::Instances) {
663     if (Obj->ParentName.empty())
664       continue;
665     SmallString<128> S;
666     int Fd;
667     if (auto EC = sys::fs::createTemporaryFile(
668             "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
669       fatal("cannot create a temporary file: " + EC.message());
670     raw_fd_ostream OS(Fd, /*shouldClose*/ true);
671     OS << Obj->MB.getBuffer();
672     Temps.push_back(S.str());
673     Rsp += quote(S) + "\n";
674   }
675
676   for (auto *Arg : Args) {
677     switch (Arg->getOption().getID()) {
678     case OPT_linkrepro:
679     case OPT_lldmap:
680     case OPT_lldmap_file:
681     case OPT_lldsavetemps:
682     case OPT_msvclto:
683       // LLD-specific options are stripped.
684       break;
685     case OPT_opt:
686       if (!StringRef(Arg->getValue()).startswith("lld"))
687         Rsp += toString(*Arg) + " ";
688       break;
689     case OPT_INPUT: {
690       if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
691         if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
692           Rsp += quote(*S) + "\n";
693         continue;
694       }
695       Rsp += quote(Arg->getValue()) + "\n";
696       break;
697     }
698     default:
699       Rsp += toString(*Arg) + "\n";
700     }
701   }
702
703   std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
704   runMSVCLinker(Rsp, ObjFiles);
705
706   for (StringRef Path : Temps)
707     sys::fs::remove(Path);
708 }
709
710 void LinkerDriver::enqueueTask(std::function<void()> Task) {
711   TaskQueue.push_back(std::move(Task));
712 }
713
714 bool LinkerDriver::run() {
715   bool DidWork = !TaskQueue.empty();
716   while (!TaskQueue.empty()) {
717     TaskQueue.front()();
718     TaskQueue.pop_front();
719   }
720   return DidWork;
721 }
722
723 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
724   // If the first command line argument is "/lib", link.exe acts like lib.exe.
725   // We call our own implementation of lib.exe that understands bitcode files.
726   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
727     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
728       fatal("lib failed");
729     return;
730   }
731
732   // Needed for LTO.
733   InitializeAllTargetInfos();
734   InitializeAllTargets();
735   InitializeAllTargetMCs();
736   InitializeAllAsmParsers();
737   InitializeAllAsmPrinters();
738   InitializeAllDisassemblers();
739
740   // Parse command line options.
741   ArgParser Parser;
742   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
743
744   // Parse and evaluate -mllvm options.
745   std::vector<const char *> V;
746   V.push_back("lld-link (LLVM option parsing)");
747   for (auto *Arg : Args.filtered(OPT_mllvm))
748     V.push_back(Arg->getValue());
749   cl::ParseCommandLineOptions(V.size(), V.data());
750
751   // Handle /errorlimit early, because error() depends on it.
752   if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
753     int N = 20;
754     StringRef S = Arg->getValue();
755     if (S.getAsInteger(10, N))
756       error(Arg->getSpelling() + " number expected, but got " + S);
757     errorHandler().ErrorLimit = N;
758   }
759
760   // Handle /help
761   if (Args.hasArg(OPT_help)) {
762     printHelp(ArgsArr[0]);
763     return;
764   }
765
766   // Handle --version, which is an lld extension. This option is a bit odd
767   // because it doesn't start with "/", but we deliberately chose "--" to
768   // avoid conflict with /version and for compatibility with clang-cl.
769   if (Args.hasArg(OPT_dash_dash_version)) {
770     outs() << getLLDVersion() << "\n";
771     return;
772   }
773
774   // Handle /lldmingw early, since it can potentially affect how other
775   // options are handled.
776   Config->MinGW = Args.hasArg(OPT_lldmingw);
777
778   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
779     SmallString<64> Path = StringRef(Arg->getValue());
780     sys::path::append(Path, "repro.tar");
781
782     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
783         TarWriter::create(Path, "repro");
784
785     if (ErrOrWriter) {
786       Tar = std::move(*ErrOrWriter);
787     } else {
788       error("/linkrepro: failed to open " + Path + ": " +
789             toString(ErrOrWriter.takeError()));
790     }
791   }
792
793   if (!Args.hasArg(OPT_INPUT)) {
794     if (Args.hasArg(OPT_deffile))
795       Config->NoEntry = true;
796     else
797       fatal("no input files");
798   }
799
800   // Construct search path list.
801   SearchPaths.push_back("");
802   for (auto *Arg : Args.filtered(OPT_libpath))
803     SearchPaths.push_back(Arg->getValue());
804   addLibSearchPaths();
805
806   // Handle /ignore
807   for (auto *Arg : Args.filtered(OPT_ignore)) {
808     if (StringRef(Arg->getValue()) == "4217")
809       Config->WarnLocallyDefinedImported = false;
810     // Other warning numbers are ignored.
811   }
812
813   // Handle /out
814   if (auto *Arg = Args.getLastArg(OPT_out))
815     Config->OutputFile = Arg->getValue();
816
817   // Handle /verbose
818   if (Args.hasArg(OPT_verbose))
819     Config->Verbose = true;
820   errorHandler().Verbose = Config->Verbose;
821
822   // Handle /force or /force:unresolved
823   if (Args.hasArg(OPT_force, OPT_force_unresolved))
824     Config->Force = true;
825
826   // Handle /debug
827   if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
828     Config->Debug = true;
829     if (auto *Arg = Args.getLastArg(OPT_debugtype))
830       Config->DebugTypes = parseDebugType(Arg->getValue());
831     else
832       Config->DebugTypes = getDefaultDebugType(Args);
833   }
834
835   // Handle /pdb
836   bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
837   if (ShouldCreatePDB)
838     if (auto *Arg = Args.getLastArg(OPT_pdb))
839       Config->PDBPath = Arg->getValue();
840
841   // Handle /noentry
842   if (Args.hasArg(OPT_noentry)) {
843     if (Args.hasArg(OPT_dll))
844       Config->NoEntry = true;
845     else
846       error("/noentry must be specified with /dll");
847   }
848
849   // Handle /dll
850   if (Args.hasArg(OPT_dll)) {
851     Config->DLL = true;
852     Config->ManifestID = 2;
853   }
854
855   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
856   // because we need to explicitly check whether that option or its inverse was
857   // present in the argument list in order to handle /fixed.
858   auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
859   if (DynamicBaseArg &&
860       DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
861     Config->DynamicBase = false;
862
863   bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
864   if (Fixed) {
865     if (DynamicBaseArg &&
866         DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
867       error("/fixed must not be specified with /dynamicbase");
868     } else {
869       Config->Relocatable = false;
870       Config->DynamicBase = false;
871     }
872   }
873
874   // Handle /appcontainer
875   Config->AppContainer =
876       Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
877
878   // Handle /machine
879   if (auto *Arg = Args.getLastArg(OPT_machine))
880     Config->Machine = getMachineType(Arg->getValue());
881
882   // Handle /nodefaultlib:<filename>
883   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
884     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
885
886   // Handle /nodefaultlib
887   if (Args.hasArg(OPT_nodefaultlib_all))
888     Config->NoDefaultLibAll = true;
889
890   // Handle /base
891   if (auto *Arg = Args.getLastArg(OPT_base))
892     parseNumbers(Arg->getValue(), &Config->ImageBase);
893
894   // Handle /stack
895   if (auto *Arg = Args.getLastArg(OPT_stack))
896     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
897
898   // Handle /heap
899   if (auto *Arg = Args.getLastArg(OPT_heap))
900     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
901
902   // Handle /version
903   if (auto *Arg = Args.getLastArg(OPT_version))
904     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
905                  &Config->MinorImageVersion);
906
907   // Handle /subsystem
908   if (auto *Arg = Args.getLastArg(OPT_subsystem))
909     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
910                    &Config->MinorOSVersion);
911
912   // Handle /alternatename
913   for (auto *Arg : Args.filtered(OPT_alternatename))
914     parseAlternateName(Arg->getValue());
915
916   // Handle /include
917   for (auto *Arg : Args.filtered(OPT_incl))
918     addUndefined(Arg->getValue());
919
920   // Handle /implib
921   if (auto *Arg = Args.getLastArg(OPT_implib))
922     Config->Implib = Arg->getValue();
923
924   // Handle /opt.
925   bool DoGC = !Args.hasArg(OPT_debug);
926   unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on
927   for (auto *Arg : Args.filtered(OPT_opt)) {
928     std::string Str = StringRef(Arg->getValue()).lower();
929     SmallVector<StringRef, 1> Vec;
930     StringRef(Str).split(Vec, ',');
931     for (StringRef S : Vec) {
932       if (S == "ref") {
933         DoGC = true;
934       } else if (S == "noref") {
935         DoGC = false;
936       } else if (S == "icf" || S.startswith("icf=")) {
937         ICFLevel = 2;
938       } else if (S == "noicf") {
939         ICFLevel = 0;
940       } else if (S.startswith("lldlto=")) {
941         StringRef OptLevel = S.substr(7);
942         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
943             Config->LTOOptLevel > 3)
944           error("/opt:lldlto: invalid optimization level: " + OptLevel);
945       } else if (S.startswith("lldltojobs=")) {
946         StringRef Jobs = S.substr(11);
947         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
948           error("/opt:lldltojobs: invalid job count: " + Jobs);
949       } else if (S.startswith("lldltopartitions=")) {
950         StringRef N = S.substr(17);
951         if (N.getAsInteger(10, Config->LTOPartitions) ||
952             Config->LTOPartitions == 0)
953           error("/opt:lldltopartitions: invalid partition count: " + N);
954       } else if (S != "lbr" && S != "nolbr")
955         error("/opt: unknown option: " + S);
956     }
957   }
958
959   // Limited ICF is enabled if GC is enabled and ICF was never mentioned
960   // explicitly.
961   // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
962   // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
963   // comdat readonly data.
964   if (ICFLevel == 1 && !DoGC)
965     ICFLevel = 0;
966   Config->DoGC = DoGC;
967   Config->DoICF = ICFLevel > 0;
968
969   // Handle /lldsavetemps
970   if (Args.hasArg(OPT_lldsavetemps))
971     Config->SaveTemps = true;
972
973   // Handle /kill-at
974   if (Args.hasArg(OPT_kill_at))
975     Config->KillAt = true;
976
977   // Handle /lldltocache
978   if (auto *Arg = Args.getLastArg(OPT_lldltocache))
979     Config->LTOCache = Arg->getValue();
980
981   // Handle /lldsavecachepolicy
982   if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
983     Config->LTOCachePolicy = CHECK(
984         parseCachePruningPolicy(Arg->getValue()),
985         Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
986
987   // Handle /failifmismatch
988   for (auto *Arg : Args.filtered(OPT_failifmismatch))
989     checkFailIfMismatch(Arg->getValue());
990
991   // Handle /merge
992   for (auto *Arg : Args.filtered(OPT_merge))
993     parseMerge(Arg->getValue());
994
995   // Handle /section
996   for (auto *Arg : Args.filtered(OPT_section))
997     parseSection(Arg->getValue());
998
999   // Handle /aligncomm
1000   for (auto *Arg : Args.filtered(OPT_aligncomm))
1001     parseAligncomm(Arg->getValue());
1002
1003   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1004   // also passed.
1005   if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1006     Config->ManifestDependency = Arg->getValue();
1007     Config->Manifest = Configuration::SideBySide;
1008   }
1009
1010   // Handle /manifest and /manifest:
1011   if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1012     if (Arg->getOption().getID() == OPT_manifest)
1013       Config->Manifest = Configuration::SideBySide;
1014     else
1015       parseManifest(Arg->getValue());
1016   }
1017
1018   // Handle /manifestuac
1019   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1020     parseManifestUAC(Arg->getValue());
1021
1022   // Handle /manifestfile
1023   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1024     Config->ManifestFile = Arg->getValue();
1025
1026   // Handle /manifestinput
1027   for (auto *Arg : Args.filtered(OPT_manifestinput))
1028     Config->ManifestInput.push_back(Arg->getValue());
1029
1030   if (!Config->ManifestInput.empty() &&
1031       Config->Manifest != Configuration::Embed) {
1032     fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1033   }
1034
1035   // Handle miscellaneous boolean flags.
1036   Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1037   Config->AllowIsolation =
1038       Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1039   Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1040   Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1041   Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1042   Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1043
1044   Config->MapFile = getMapFile(Args);
1045
1046   if (errorCount())
1047     return;
1048
1049   bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
1050   // Create a list of input files. Files can be given as arguments
1051   // for /defaultlib option.
1052   std::vector<MemoryBufferRef> MBs;
1053   for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1054     switch (Arg->getOption().getID()) {
1055     case OPT_INPUT:
1056       if (Optional<StringRef> Path = findFile(Arg->getValue()))
1057         enqueuePath(*Path, WholeArchiveFlag);
1058       break;
1059     case OPT_wholearchive_file:
1060       if (Optional<StringRef> Path = findFile(Arg->getValue()))
1061         enqueuePath(*Path, true);
1062       break;
1063     }
1064   }
1065   for (auto *Arg : Args.filtered(OPT_defaultlib))
1066     if (Optional<StringRef> Path = findLib(Arg->getValue()))
1067       enqueuePath(*Path, false);
1068
1069   // Windows specific -- Create a resource file containing a manifest file.
1070   if (Config->Manifest == Configuration::Embed)
1071     addBuffer(createManifestRes(), false);
1072
1073   // Read all input files given via the command line.
1074   run();
1075
1076   // We should have inferred a machine type by now from the input files, but if
1077   // not we assume x64.
1078   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1079     warn("/machine is not specified. x64 is assumed");
1080     Config->Machine = AMD64;
1081   }
1082
1083   // Input files can be Windows resource files (.res files). We use
1084   // WindowsResource to convert resource files to a regular COFF file,
1085   // then link the resulting file normally.
1086   if (!Resources.empty())
1087     Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1088
1089   if (Tar)
1090     Tar->append("response.txt",
1091                 createResponseFile(Args, FilePaths,
1092                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
1093
1094   // Handle /largeaddressaware
1095   Config->LargeAddressAware = Args.hasFlag(
1096       OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1097
1098   // Handle /highentropyva
1099   Config->HighEntropyVA =
1100       Config->is64() &&
1101       Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1102
1103   if (!Config->DynamicBase &&
1104       (Config->Machine == ARMNT || Config->Machine == ARM64))
1105     error("/dynamicbase:no is not compatible with " +
1106           machineToStr(Config->Machine));
1107
1108   // Handle /entry and /dll
1109   if (auto *Arg = Args.getLastArg(OPT_entry)) {
1110     Config->Entry = addUndefined(mangle(Arg->getValue()));
1111   } else if (!Config->Entry && !Config->NoEntry) {
1112     if (Args.hasArg(OPT_dll)) {
1113       StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1114                                               : "_DllMainCRTStartup";
1115       Config->Entry = addUndefined(S);
1116     } else {
1117       // Windows specific -- If entry point name is not given, we need to
1118       // infer that from user-defined entry name.
1119       StringRef S = findDefaultEntry();
1120       if (S.empty())
1121         fatal("entry point must be defined");
1122       Config->Entry = addUndefined(S);
1123       log("Entry name inferred: " + S);
1124     }
1125   }
1126
1127   // Handle /export
1128   for (auto *Arg : Args.filtered(OPT_export)) {
1129     Export E = parseExport(Arg->getValue());
1130     if (Config->Machine == I386) {
1131       if (!isDecorated(E.Name))
1132         E.Name = Saver.save("_" + E.Name);
1133       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1134         E.ExtName = Saver.save("_" + E.ExtName);
1135     }
1136     Config->Exports.push_back(E);
1137   }
1138
1139   // Handle /def
1140   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1141     // parseModuleDefs mutates Config object.
1142     parseModuleDefs(Arg->getValue());
1143   }
1144
1145   // Handle generation of import library from a def file.
1146   if (!Args.hasArg(OPT_INPUT)) {
1147     fixupExports();
1148     createImportLibrary(/*AsLib=*/true);
1149     return;
1150   }
1151
1152   // Handle /delayload
1153   for (auto *Arg : Args.filtered(OPT_delayload)) {
1154     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1155     if (Config->Machine == I386) {
1156       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1157     } else {
1158       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1159     }
1160   }
1161
1162   // Set default image name if neither /out or /def set it.
1163   if (Config->OutputFile.empty()) {
1164     Config->OutputFile =
1165         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1166   }
1167
1168   // Put the PDB next to the image if no /pdb flag was passed.
1169   if (ShouldCreatePDB && Config->PDBPath.empty()) {
1170     Config->PDBPath = Config->OutputFile;
1171     sys::path::replace_extension(Config->PDBPath, ".pdb");
1172   }
1173
1174   // Set default image base if /base is not given.
1175   if (Config->ImageBase == uint64_t(-1))
1176     Config->ImageBase = getDefaultImageBase();
1177
1178   Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1179   if (Config->Machine == I386) {
1180     Symtab->addAbsolute("___safe_se_handler_table", 0);
1181     Symtab->addAbsolute("___safe_se_handler_count", 0);
1182   }
1183
1184   // We do not support /guard:cf (control flow protection) yet.
1185   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1186   Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1187   Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1188   Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1189   Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1190   Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1191   Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1192   Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1193   // Needed for MSVC 2017 15.5 CRT.
1194   Symtab->addAbsolute(mangle("__enclave_config"), 0);
1195
1196   // This code may add new undefined symbols to the link, which may enqueue more
1197   // symbol resolution tasks, so we need to continue executing tasks until we
1198   // converge.
1199   do {
1200     // Windows specific -- if entry point is not found,
1201     // search for its mangled names.
1202     if (Config->Entry)
1203       Symtab->mangleMaybe(Config->Entry);
1204
1205     // Windows specific -- Make sure we resolve all dllexported symbols.
1206     for (Export &E : Config->Exports) {
1207       if (!E.ForwardTo.empty())
1208         continue;
1209       E.Sym = addUndefined(E.Name);
1210       if (!E.Directives)
1211         Symtab->mangleMaybe(E.Sym);
1212     }
1213
1214     // Add weak aliases. Weak aliases is a mechanism to give remaining
1215     // undefined symbols final chance to be resolved successfully.
1216     for (auto Pair : Config->AlternateNames) {
1217       StringRef From = Pair.first;
1218       StringRef To = Pair.second;
1219       Symbol *Sym = Symtab->find(From);
1220       if (!Sym)
1221         continue;
1222       if (auto *U = dyn_cast<Undefined>(Sym))
1223         if (!U->WeakAlias)
1224           U->WeakAlias = Symtab->addUndefined(To);
1225     }
1226
1227     // Windows specific -- if __load_config_used can be resolved, resolve it.
1228     if (Symtab->findUnderscore("_load_config_used"))
1229       addUndefined(mangle("_load_config_used"));
1230   } while (run());
1231
1232   if (errorCount())
1233     return;
1234
1235   // If /msvclto is given, we use the MSVC linker to link LTO output files.
1236   // This is useful because MSVC link.exe can generate complete PDBs.
1237   if (Args.hasArg(OPT_msvclto)) {
1238     invokeMSVC(Args);
1239     return;
1240   }
1241
1242   // Do LTO by compiling bitcode input files to a set of native COFF files then
1243   // link those files.
1244   Symtab->addCombinedLTOObjects();
1245   run();
1246
1247   // Make sure we have resolved all symbols.
1248   Symtab->reportRemainingUndefines();
1249   if (errorCount())
1250     return;
1251
1252   // Windows specific -- if no /subsystem is given, we need to infer
1253   // that from entry point name.
1254   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1255     Config->Subsystem = inferSubsystem();
1256     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1257       fatal("subsystem must be defined");
1258   }
1259
1260   // Handle /safeseh.
1261   if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1262     for (ObjFile *File : ObjFile::Instances)
1263       if (!File->SEHCompat)
1264         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1265     if (errorCount())
1266       return;
1267   }
1268
1269   // In MinGW, all symbols are automatically exported if no symbols
1270   // are chosen to be exported.
1271   if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1272                       Args.hasArg(OPT_export_all_symbols))) {
1273     AutoExporter Exporter;
1274
1275     Symtab->forEachSymbol([=](Symbol *S) {
1276       auto *Def = dyn_cast<Defined>(S);
1277       if (!Exporter.shouldExport(Def))
1278         return;
1279       Export E;
1280       E.Name = Def->getName();
1281       E.Sym = Def;
1282       if (Def->getChunk() &&
1283           !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
1284         E.Data = true;
1285       Config->Exports.push_back(E);
1286     });
1287   }
1288
1289   // Windows specific -- when we are creating a .dll file, we also
1290   // need to create a .lib file.
1291   if (!Config->Exports.empty() || Config->DLL) {
1292     fixupExports();
1293     createImportLibrary(/*AsLib=*/false);
1294     assignExportOrdinals();
1295   }
1296
1297   // Handle /output-def (MinGW specific).
1298   if (auto *Arg = Args.getLastArg(OPT_output_def))
1299     writeDefFile(Arg->getValue());
1300
1301   // Set extra alignment for .comm symbols
1302   for (auto Pair : Config->AlignComm) {
1303     StringRef Name = Pair.first;
1304     uint32_t Alignment = Pair.second;
1305
1306     Symbol *Sym = Symtab->find(Name);
1307     if (!Sym) {
1308       warn("/aligncomm symbol " + Name + " not found");
1309       continue;
1310     }
1311
1312     auto *DC = dyn_cast<DefinedCommon>(Sym);
1313     if (!DC) {
1314       warn("/aligncomm symbol " + Name + " of wrong kind");
1315       continue;
1316     }
1317
1318     CommonChunk *C = DC->getChunk();
1319     C->Alignment = std::max(C->Alignment, Alignment);
1320   }
1321
1322   // Windows specific -- Create a side-by-side manifest file.
1323   if (Config->Manifest == Configuration::SideBySide)
1324     createSideBySideManifest();
1325
1326   // Identify unreferenced COMDAT sections.
1327   if (Config->DoGC)
1328     markLive(Symtab->getChunks());
1329
1330   // Identify identical COMDAT sections to merge them.
1331   if (Config->DoICF)
1332     doICF(Symtab->getChunks());
1333
1334   // Write the result.
1335   writeResult();
1336 }
1337
1338 } // namespace coff
1339 } // namespace lld