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