]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/Driver.cpp
Merge llvm, clang, lld and lldb release_40 branch r292009. Also update
[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 "Error.h"
13 #include "InputFiles.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "Writer.h"
18 #include "lld/Driver/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/LibDriver/LibDriver.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Process.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <memory>
33
34 #ifdef _MSC_VER
35 // <future> depends on <eh.h> for __uncaught_exception.
36 #include <eh.h>
37 #endif
38
39 #include <future>
40
41 using namespace llvm;
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
44 using llvm::sys::fs::OpenFlags;
45 using llvm::sys::fs::file_magic;
46 using llvm::sys::fs::identify_magic;
47
48 namespace lld {
49 namespace coff {
50
51 Configuration *Config;
52 LinkerDriver *Driver;
53
54 BumpPtrAllocator BAlloc;
55 StringSaver Saver{BAlloc};
56 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
57
58 bool link(ArrayRef<const char *> Args) {
59   Config = make<Configuration>();
60   Driver = make<LinkerDriver>();
61   Driver->link(Args);
62   return true;
63 }
64
65 // Drop directory components and replace extension with ".exe" or ".dll".
66 static std::string getOutputPath(StringRef Path) {
67   auto P = Path.find_last_of("\\/");
68   StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
69   const char* E = Config->DLL ? ".dll" : ".exe";
70   return (S.substr(0, S.rfind('.')) + E).str();
71 }
72
73 // ErrorOr is not default constructible, so it cannot be used as the type
74 // parameter of a future.
75 // FIXME: We could open the file in createFutureForFile and avoid needing to
76 // return an error here, but for the moment that would cost us a file descriptor
77 // (a limited resource on Windows) for the duration that the future is pending.
78 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
79
80 // Create a std::future that opens and maps a file using the best strategy for
81 // the host platform.
82 static std::future<MBErrPair> createFutureForFile(std::string Path) {
83 #if LLVM_ON_WIN32
84   // On Windows, file I/O is relatively slow so it is best to do this
85   // asynchronously.
86   auto Strategy = std::launch::async;
87 #else
88   auto Strategy = std::launch::deferred;
89 #endif
90   return std::async(Strategy, [=]() {
91     auto MBOrErr = MemoryBuffer::getFile(Path);
92     if (!MBOrErr)
93       return MBErrPair{nullptr, MBOrErr.getError()};
94     return MBErrPair{std::move(*MBOrErr), std::error_code()};
95   });
96 }
97
98 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
99   MemoryBufferRef MBRef = *MB;
100   OwningMBs.push_back(std::move(MB));
101
102   if (Driver->Tar)
103     Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
104                         MBRef.getBuffer());
105
106   return MBRef;
107 }
108
109 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
110   MemoryBufferRef MBRef = takeBuffer(std::move(MB));
111
112   // File type is detected by contents, not by file extension.
113   file_magic Magic = identify_magic(MBRef.getBuffer());
114   if (Magic == file_magic::windows_resource) {
115     Resources.push_back(MBRef);
116     return;
117   }
118
119   FilePaths.push_back(MBRef.getBufferIdentifier());
120   if (Magic == file_magic::archive)
121     return Symtab.addFile(make<ArchiveFile>(MBRef));
122   if (Magic == file_magic::bitcode)
123     return Symtab.addFile(make<BitcodeFile>(MBRef));
124   if (Magic == file_magic::coff_cl_gl_object)
125     fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
126           "Recompile without /GL");
127   Symtab.addFile(make<ObjectFile>(MBRef));
128 }
129
130 void LinkerDriver::enqueuePath(StringRef Path) {
131   auto Future =
132       std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
133   std::string PathStr = Path;
134   enqueueTask([=]() {
135     auto MBOrErr = Future->get();
136     if (MBOrErr.second)
137       fatal(MBOrErr.second, "could not open " + PathStr);
138     Driver->addBuffer(std::move(MBOrErr.first));
139   });
140
141   if (Config->OutputFile == "")
142     Config->OutputFile = getOutputPath(Path);
143 }
144
145 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
146                                     StringRef ParentName) {
147   file_magic Magic = identify_magic(MB.getBuffer());
148   if (Magic == file_magic::coff_import_library) {
149     Symtab.addFile(make<ImportFile>(MB));
150     return;
151   }
152
153   InputFile *Obj;
154   if (Magic == file_magic::coff_object)
155     Obj = make<ObjectFile>(MB);
156   else if (Magic == file_magic::bitcode)
157     Obj = make<BitcodeFile>(MB);
158   else
159     fatal("unknown file type: " + MB.getBufferIdentifier());
160
161   Obj->ParentName = ParentName;
162   Symtab.addFile(Obj);
163   if (Config->Verbose)
164     outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
165 }
166
167 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
168                                         StringRef SymName,
169                                         StringRef ParentName) {
170   if (!C.getParent()->isThin()) {
171     MemoryBufferRef MB = check(
172         C.getMemoryBufferRef(),
173         "could not get the buffer for the member defining symbol " + SymName);
174     enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
175     return;
176   }
177
178   auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
179       check(C.getFullName(),
180             "could not get the filename for the member defining symbol " +
181                 SymName)));
182   enqueueTask([=]() {
183     auto MBOrErr = Future->get();
184     if (MBOrErr.second)
185       fatal(MBOrErr.second,
186             "could not get the buffer for the member defining " + SymName);
187     Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
188                              ParentName);
189   });
190 }
191
192 static bool isDecorated(StringRef Sym) {
193   return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
194 }
195
196 // Parses .drectve section contents and returns a list of files
197 // specified by /defaultlib.
198 void LinkerDriver::parseDirectives(StringRef S) {
199   opt::InputArgList Args = Parser.parse(S);
200
201   for (auto *Arg : Args) {
202     switch (Arg->getOption().getID()) {
203     case OPT_alternatename:
204       parseAlternateName(Arg->getValue());
205       break;
206     case OPT_defaultlib:
207       if (Optional<StringRef> Path = findLib(Arg->getValue()))
208         enqueuePath(*Path);
209       break;
210     case OPT_export: {
211       Export E = parseExport(Arg->getValue());
212       E.Directives = true;
213       Config->Exports.push_back(E);
214       break;
215     }
216     case OPT_failifmismatch:
217       checkFailIfMismatch(Arg->getValue());
218       break;
219     case OPT_incl:
220       addUndefined(Arg->getValue());
221       break;
222     case OPT_merge:
223       parseMerge(Arg->getValue());
224       break;
225     case OPT_nodefaultlib:
226       Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
227       break;
228     case OPT_section:
229       parseSection(Arg->getValue());
230       break;
231     case OPT_editandcontinue:
232     case OPT_fastfail:
233     case OPT_guardsym:
234     case OPT_throwingnew:
235       break;
236     default:
237       fatal(Arg->getSpelling() + " is not allowed in .drectve");
238     }
239   }
240 }
241
242 // Find file from search paths. You can omit ".obj", this function takes
243 // care of that. Note that the returned path is not guaranteed to exist.
244 StringRef LinkerDriver::doFindFile(StringRef Filename) {
245   bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
246   if (HasPathSep)
247     return Filename;
248   bool HasExt = (Filename.find('.') != StringRef::npos);
249   for (StringRef Dir : SearchPaths) {
250     SmallString<128> Path = Dir;
251     sys::path::append(Path, Filename);
252     if (sys::fs::exists(Path.str()))
253       return Saver.save(Path.str());
254     if (!HasExt) {
255       Path.append(".obj");
256       if (sys::fs::exists(Path.str()))
257         return Saver.save(Path.str());
258     }
259   }
260   return Filename;
261 }
262
263 // Resolves a file path. This never returns the same path
264 // (in that case, it returns None).
265 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
266   StringRef Path = doFindFile(Filename);
267   bool Seen = !VisitedFiles.insert(Path.lower()).second;
268   if (Seen)
269     return None;
270   return Path;
271 }
272
273 // Find library file from search path.
274 StringRef LinkerDriver::doFindLib(StringRef Filename) {
275   // Add ".lib" to Filename if that has no file extension.
276   bool HasExt = (Filename.find('.') != StringRef::npos);
277   if (!HasExt)
278     Filename = Saver.save(Filename + ".lib");
279   return doFindFile(Filename);
280 }
281
282 // Resolves a library path. /nodefaultlib options are taken into
283 // consideration. This never returns the same path (in that case,
284 // it returns None).
285 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
286   if (Config->NoDefaultLibAll)
287     return None;
288   if (!VisitedLibs.insert(Filename.lower()).second)
289     return None;
290   StringRef Path = doFindLib(Filename);
291   if (Config->NoDefaultLibs.count(Path))
292     return None;
293   if (!VisitedFiles.insert(Path.lower()).second)
294     return None;
295   return Path;
296 }
297
298 // Parses LIB environment which contains a list of search paths.
299 void LinkerDriver::addLibSearchPaths() {
300   Optional<std::string> EnvOpt = Process::GetEnv("LIB");
301   if (!EnvOpt.hasValue())
302     return;
303   StringRef Env = Saver.save(*EnvOpt);
304   while (!Env.empty()) {
305     StringRef Path;
306     std::tie(Path, Env) = Env.split(';');
307     SearchPaths.push_back(Path);
308   }
309 }
310
311 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
312   SymbolBody *B = Symtab.addUndefined(Name);
313   Config->GCRoot.insert(B);
314   return B;
315 }
316
317 // Symbol names are mangled by appending "_" prefix on x86.
318 StringRef LinkerDriver::mangle(StringRef Sym) {
319   assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
320   if (Config->Machine == I386)
321     return Saver.save("_" + Sym);
322   return Sym;
323 }
324
325 // Windows specific -- find default entry point name.
326 StringRef LinkerDriver::findDefaultEntry() {
327   // User-defined main functions and their corresponding entry points.
328   static const char *Entries[][2] = {
329       {"main", "mainCRTStartup"},
330       {"wmain", "wmainCRTStartup"},
331       {"WinMain", "WinMainCRTStartup"},
332       {"wWinMain", "wWinMainCRTStartup"},
333   };
334   for (auto E : Entries) {
335     StringRef Entry = Symtab.findMangle(mangle(E[0]));
336     if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
337       return mangle(E[1]);
338   }
339   return "";
340 }
341
342 WindowsSubsystem LinkerDriver::inferSubsystem() {
343   if (Config->DLL)
344     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
345   if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
346     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
347   if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
348     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
349   return IMAGE_SUBSYSTEM_UNKNOWN;
350 }
351
352 static uint64_t getDefaultImageBase() {
353   if (Config->is64())
354     return Config->DLL ? 0x180000000 : 0x140000000;
355   return Config->DLL ? 0x10000000 : 0x400000;
356 }
357
358 static std::string createResponseFile(const opt::InputArgList &Args,
359                                       ArrayRef<StringRef> FilePaths,
360                                       ArrayRef<StringRef> SearchPaths) {
361   SmallString<0> Data;
362   raw_svector_ostream OS(Data);
363
364   for (auto *Arg : Args) {
365     switch (Arg->getOption().getID()) {
366     case OPT_linkrepro:
367     case OPT_INPUT:
368     case OPT_defaultlib:
369     case OPT_libpath:
370       break;
371     default:
372       OS << toString(Arg) << "\n";
373     }
374   }
375
376   for (StringRef Path : SearchPaths) {
377     std::string RelPath = relativeToRoot(Path);
378     OS << "/libpath:" << quote(RelPath) << "\n";
379   }
380
381   for (StringRef Path : FilePaths)
382     OS << quote(relativeToRoot(Path)) << "\n";
383
384   return Data.str();
385 }
386
387 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
388   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
389   if (Args.hasArg(OPT_driver))
390     DebugTypes |= static_cast<unsigned>(DebugType::PData);
391   if (Args.hasArg(OPT_profile))
392     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
393   return DebugTypes;
394 }
395
396 static unsigned parseDebugType(StringRef Arg) {
397   SmallVector<StringRef, 3> Types;
398   Arg.split(Types, ',', /*KeepEmpty=*/false);
399
400   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
401   for (StringRef Type : Types)
402     DebugTypes |= StringSwitch<unsigned>(Type.lower())
403                       .Case("cv", static_cast<unsigned>(DebugType::CV))
404                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
405                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
406   return DebugTypes;
407 }
408
409 static std::string getMapFile(const opt::InputArgList &Args) {
410   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
411   if (!Arg)
412     return "";
413   if (Arg->getOption().getID() == OPT_lldmap_file)
414     return Arg->getValue();
415
416   assert(Arg->getOption().getID() == OPT_lldmap);
417   StringRef OutFile = Config->OutputFile;
418   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
419 }
420
421 void LinkerDriver::enqueueTask(std::function<void()> Task) {
422   TaskQueue.push_back(std::move(Task));
423 }
424
425 bool LinkerDriver::run() {
426   bool DidWork = !TaskQueue.empty();
427   while (!TaskQueue.empty()) {
428     TaskQueue.front()();
429     TaskQueue.pop_front();
430   }
431   return DidWork;
432 }
433
434 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
435   // If the first command line argument is "/lib", link.exe acts like lib.exe.
436   // We call our own implementation of lib.exe that understands bitcode files.
437   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
438     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
439       fatal("lib failed");
440     return;
441   }
442
443   // Needed for LTO.
444   InitializeAllTargetInfos();
445   InitializeAllTargets();
446   InitializeAllTargetMCs();
447   InitializeAllAsmParsers();
448   InitializeAllAsmPrinters();
449   InitializeAllDisassemblers();
450
451   // Parse command line options.
452   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
453
454   // Handle /help
455   if (Args.hasArg(OPT_help)) {
456     printHelp(ArgsArr[0]);
457     return;
458   }
459
460   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
461     SmallString<64> Path = StringRef(Arg->getValue());
462     sys::path::append(Path, "repro.tar");
463
464     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
465         TarWriter::create(Path, "repro");
466
467     if (ErrOrWriter) {
468       Tar = std::move(*ErrOrWriter);
469     } else {
470       errs() << "/linkrepro: failed to open " << Path << ": "
471              << toString(ErrOrWriter.takeError()) << '\n';
472     }
473   }
474
475   if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
476     fatal("no input files");
477
478   // Construct search path list.
479   SearchPaths.push_back("");
480   for (auto *Arg : Args.filtered(OPT_libpath))
481     SearchPaths.push_back(Arg->getValue());
482   addLibSearchPaths();
483
484   // Handle /out
485   if (auto *Arg = Args.getLastArg(OPT_out))
486     Config->OutputFile = Arg->getValue();
487
488   // Handle /verbose
489   if (Args.hasArg(OPT_verbose))
490     Config->Verbose = true;
491
492   // Handle /force or /force:unresolved
493   if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
494     Config->Force = true;
495
496   // Handle /debug
497   if (Args.hasArg(OPT_debug)) {
498     Config->Debug = true;
499     Config->DebugTypes =
500         Args.hasArg(OPT_debugtype)
501             ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
502             : getDefaultDebugType(Args);
503   }
504
505   // Create a dummy PDB file to satisfy build sytem rules.
506   if (auto *Arg = Args.getLastArg(OPT_pdb))
507     Config->PDBPath = Arg->getValue();
508
509   // Handle /noentry
510   if (Args.hasArg(OPT_noentry)) {
511     if (!Args.hasArg(OPT_dll))
512       fatal("/noentry must be specified with /dll");
513     Config->NoEntry = true;
514   }
515
516   // Handle /dll
517   if (Args.hasArg(OPT_dll)) {
518     Config->DLL = true;
519     Config->ManifestID = 2;
520   }
521
522   // Handle /fixed
523   if (Args.hasArg(OPT_fixed)) {
524     if (Args.hasArg(OPT_dynamicbase))
525       fatal("/fixed must not be specified with /dynamicbase");
526     Config->Relocatable = false;
527     Config->DynamicBase = false;
528   }
529
530   // Handle /machine
531   if (auto *Arg = Args.getLastArg(OPT_machine))
532     Config->Machine = getMachineType(Arg->getValue());
533
534   // Handle /nodefaultlib:<filename>
535   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
536     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
537
538   // Handle /nodefaultlib
539   if (Args.hasArg(OPT_nodefaultlib_all))
540     Config->NoDefaultLibAll = true;
541
542   // Handle /base
543   if (auto *Arg = Args.getLastArg(OPT_base))
544     parseNumbers(Arg->getValue(), &Config->ImageBase);
545
546   // Handle /stack
547   if (auto *Arg = Args.getLastArg(OPT_stack))
548     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
549
550   // Handle /heap
551   if (auto *Arg = Args.getLastArg(OPT_heap))
552     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
553
554   // Handle /version
555   if (auto *Arg = Args.getLastArg(OPT_version))
556     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
557                  &Config->MinorImageVersion);
558
559   // Handle /subsystem
560   if (auto *Arg = Args.getLastArg(OPT_subsystem))
561     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
562                    &Config->MinorOSVersion);
563
564   // Handle /alternatename
565   for (auto *Arg : Args.filtered(OPT_alternatename))
566     parseAlternateName(Arg->getValue());
567
568   // Handle /include
569   for (auto *Arg : Args.filtered(OPT_incl))
570     addUndefined(Arg->getValue());
571
572   // Handle /implib
573   if (auto *Arg = Args.getLastArg(OPT_implib))
574     Config->Implib = Arg->getValue();
575
576   // Handle /opt
577   for (auto *Arg : Args.filtered(OPT_opt)) {
578     std::string Str = StringRef(Arg->getValue()).lower();
579     SmallVector<StringRef, 1> Vec;
580     StringRef(Str).split(Vec, ',');
581     for (StringRef S : Vec) {
582       if (S == "noref") {
583         Config->DoGC = false;
584         Config->DoICF = false;
585         continue;
586       }
587       if (S == "icf" || StringRef(S).startswith("icf=")) {
588         Config->DoICF = true;
589         continue;
590       }
591       if (S == "noicf") {
592         Config->DoICF = false;
593         continue;
594       }
595       if (StringRef(S).startswith("lldlto=")) {
596         StringRef OptLevel = StringRef(S).substr(7);
597         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
598             Config->LTOOptLevel > 3)
599           fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
600         continue;
601       }
602       if (StringRef(S).startswith("lldltojobs=")) {
603         StringRef Jobs = StringRef(S).substr(11);
604         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
605           fatal("/opt:lldltojobs: invalid job count: " + Jobs);
606         continue;
607       }
608       if (S != "ref" && S != "lbr" && S != "nolbr")
609         fatal("/opt: unknown option: " + S);
610     }
611   }
612
613   // Handle /failifmismatch
614   for (auto *Arg : Args.filtered(OPT_failifmismatch))
615     checkFailIfMismatch(Arg->getValue());
616
617   // Handle /merge
618   for (auto *Arg : Args.filtered(OPT_merge))
619     parseMerge(Arg->getValue());
620
621   // Handle /section
622   for (auto *Arg : Args.filtered(OPT_section))
623     parseSection(Arg->getValue());
624
625   // Handle /manifest
626   if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
627     parseManifest(Arg->getValue());
628
629   // Handle /manifestuac
630   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
631     parseManifestUAC(Arg->getValue());
632
633   // Handle /manifestdependency
634   if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
635     Config->ManifestDependency = Arg->getValue();
636
637   // Handle /manifestfile
638   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
639     Config->ManifestFile = Arg->getValue();
640
641   // Handle /manifestinput
642   for (auto *Arg : Args.filtered(OPT_manifestinput))
643     Config->ManifestInput.push_back(Arg->getValue());
644
645   // Handle miscellaneous boolean flags.
646   if (Args.hasArg(OPT_allowbind_no))
647     Config->AllowBind = false;
648   if (Args.hasArg(OPT_allowisolation_no))
649     Config->AllowIsolation = false;
650   if (Args.hasArg(OPT_dynamicbase_no))
651     Config->DynamicBase = false;
652   if (Args.hasArg(OPT_nxcompat_no))
653     Config->NxCompat = false;
654   if (Args.hasArg(OPT_tsaware_no))
655     Config->TerminalServerAware = false;
656   if (Args.hasArg(OPT_nosymtab))
657     Config->WriteSymtab = false;
658   Config->DumpPdb = Args.hasArg(OPT_dumppdb);
659   Config->DebugPdb = Args.hasArg(OPT_debugpdb);
660
661   // Create a list of input files. Files can be given as arguments
662   // for /defaultlib option.
663   std::vector<MemoryBufferRef> MBs;
664   for (auto *Arg : Args.filtered(OPT_INPUT))
665     if (Optional<StringRef> Path = findFile(Arg->getValue()))
666       enqueuePath(*Path);
667   for (auto *Arg : Args.filtered(OPT_defaultlib))
668     if (Optional<StringRef> Path = findLib(Arg->getValue()))
669       enqueuePath(*Path);
670
671   // Windows specific -- Create a resource file containing a manifest file.
672   if (Config->Manifest == Configuration::Embed)
673     addBuffer(createManifestRes());
674
675   // Read all input files given via the command line.
676   run();
677
678   // We should have inferred a machine type by now from the input files, but if
679   // not we assume x64.
680   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
681     errs() << "warning: /machine is not specified. x64 is assumed.\n";
682     Config->Machine = AMD64;
683   }
684
685   // Windows specific -- Input files can be Windows resource files (.res files).
686   // We invoke cvtres.exe to convert resource files to a regular COFF file
687   // then link the result file normally.
688   if (!Resources.empty())
689     addBuffer(convertResToCOFF(Resources));
690
691   if (Tar)
692     Tar->append("response.txt",
693                 createResponseFile(Args, FilePaths,
694                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
695
696   // Handle /largeaddressaware
697   if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
698     Config->LargeAddressAware = true;
699
700   // Handle /highentropyva
701   if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
702     Config->HighEntropyVA = true;
703
704   // Handle /entry and /dll
705   if (auto *Arg = Args.getLastArg(OPT_entry)) {
706     Config->Entry = addUndefined(mangle(Arg->getValue()));
707   } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
708     StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
709                                             : "_DllMainCRTStartup";
710     Config->Entry = addUndefined(S);
711   } else if (!Config->NoEntry) {
712     // Windows specific -- If entry point name is not given, we need to
713     // infer that from user-defined entry name.
714     StringRef S = findDefaultEntry();
715     if (S.empty())
716       fatal("entry point must be defined");
717     Config->Entry = addUndefined(S);
718     if (Config->Verbose)
719       outs() << "Entry name inferred: " << S << "\n";
720   }
721
722   // Handle /export
723   for (auto *Arg : Args.filtered(OPT_export)) {
724     Export E = parseExport(Arg->getValue());
725     if (Config->Machine == I386) {
726       if (!isDecorated(E.Name))
727         E.Name = Saver.save("_" + E.Name);
728       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
729         E.ExtName = Saver.save("_" + E.ExtName);
730     }
731     Config->Exports.push_back(E);
732   }
733
734   // Handle /def
735   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
736     // parseModuleDefs mutates Config object.
737     parseModuleDefs(
738         takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
739                          Twine("could not open ") + Arg->getValue())));
740   }
741
742   // Handle /delayload
743   for (auto *Arg : Args.filtered(OPT_delayload)) {
744     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
745     if (Config->Machine == I386) {
746       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
747     } else {
748       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
749     }
750   }
751
752   // Set default image base if /base is not given.
753   if (Config->ImageBase == uint64_t(-1))
754     Config->ImageBase = getDefaultImageBase();
755
756   Symtab.addRelative(mangle("__ImageBase"), 0);
757   if (Config->Machine == I386) {
758     Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
759     Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
760   }
761
762   // We do not support /guard:cf (control flow protection) yet.
763   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
764   Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
765   Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
766   Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
767
768   // This code may add new undefined symbols to the link, which may enqueue more
769   // symbol resolution tasks, so we need to continue executing tasks until we
770   // converge.
771   do {
772     // Windows specific -- if entry point is not found,
773     // search for its mangled names.
774     if (Config->Entry)
775       Symtab.mangleMaybe(Config->Entry);
776
777     // Windows specific -- Make sure we resolve all dllexported symbols.
778     for (Export &E : Config->Exports) {
779       if (!E.ForwardTo.empty())
780         continue;
781       E.Sym = addUndefined(E.Name);
782       if (!E.Directives)
783         Symtab.mangleMaybe(E.Sym);
784     }
785
786     // Add weak aliases. Weak aliases is a mechanism to give remaining
787     // undefined symbols final chance to be resolved successfully.
788     for (auto Pair : Config->AlternateNames) {
789       StringRef From = Pair.first;
790       StringRef To = Pair.second;
791       Symbol *Sym = Symtab.find(From);
792       if (!Sym)
793         continue;
794       if (auto *U = dyn_cast<Undefined>(Sym->body()))
795         if (!U->WeakAlias)
796           U->WeakAlias = Symtab.addUndefined(To);
797     }
798
799     // Windows specific -- if __load_config_used can be resolved, resolve it.
800     if (Symtab.findUnderscore("_load_config_used"))
801       addUndefined(mangle("_load_config_used"));
802   } while (run());
803
804   // Do LTO by compiling bitcode input files to a set of native COFF files then
805   // link those files.
806   Symtab.addCombinedLTOObjects();
807   run();
808
809   // Make sure we have resolved all symbols.
810   Symtab.reportRemainingUndefines();
811
812   // Windows specific -- if no /subsystem is given, we need to infer
813   // that from entry point name.
814   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
815     Config->Subsystem = inferSubsystem();
816     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
817       fatal("subsystem must be defined");
818   }
819
820   // Handle /safeseh.
821   if (Args.hasArg(OPT_safeseh))
822     for (ObjectFile *File : Symtab.ObjectFiles)
823       if (!File->SEHCompat)
824         fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
825
826   // Windows specific -- when we are creating a .dll file, we also
827   // need to create a .lib file.
828   if (!Config->Exports.empty() || Config->DLL) {
829     fixupExports();
830     writeImportLibrary();
831     assignExportOrdinals();
832   }
833
834   // Windows specific -- Create a side-by-side manifest file.
835   if (Config->Manifest == Configuration::SideBySide)
836     createSideBySideManifest();
837
838   // Identify unreferenced COMDAT sections.
839   if (Config->DoGC)
840     markLive(Symtab.getChunks());
841
842   // Identify identical COMDAT sections to merge them.
843   if (Config->DoICF)
844     doICF(Symtab.getChunks());
845
846   // Write the result.
847   writeResult(&Symtab);
848
849   // Create a symbol map file containing symbol VAs and their names
850   // to help debugging.
851   std::string MapFile = getMapFile(Args);
852   if (!MapFile.empty()) {
853     std::error_code EC;
854     raw_fd_ostream Out(MapFile, EC, OpenFlags::F_Text);
855     if (EC)
856       fatal(EC, "could not create the symbol map " + MapFile);
857     Symtab.printMap(Out);
858   }
859
860   // Call exit to avoid calling destructors.
861   exit(0);
862 }
863
864 } // namespace coff
865 } // namespace lld