blob: 86a769002fd2d59ae04874e7fe6a92f24d19d07d [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- 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
Rui Ueyama411c63602015-05-28 19:09:30 +000010#include "Driver.h"
Rui Ueyama1d99ab32016-09-15 22:24:51 +000011#include "Config.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000012#include "ICF.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000014#include "MarkLive.h"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000015#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000017#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000018#include "Writer.h"
Rui Ueyama57175aa2018-01-27 00:34:46 +000019#include "lld/Common/Args.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000020#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000021#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000022#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000023#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000024#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000026#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000027#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000028#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000029#include "llvm/Object/COFFImportFile.h"
30#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Option/Arg.h"
32#include "llvm/Option/ArgList.h"
33#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000034#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000036#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000037#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000038#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000039#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000040#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000041#include <algorithm>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000042#include <future>
Sam Cleggf187c4d2018-02-20 22:09:59 +000043#include <memory>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000044
Rui Ueyama411c63602015-05-28 19:09:30 +000045using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000046using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000047using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000048using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050namespace lld {
51namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Zachary Turner727f1532018-01-17 19:16:26 +000053static Timer InputFileTimer("Input File Reading", Timer::root());
54
Rui Ueyama3500f662015-05-28 20:30:06 +000055Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000056LinkerDriver *Driver;
57
Rui Ueyama6f4e2552017-10-23 20:03:32 +000058bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Bob Haarmanb8a59c82017-10-25 22:28:38 +000059 errorHandler().LogName = Args[0];
60 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
64 " (use /ERRORLIMIT:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000065 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000066 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000067 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyamacbf969e2017-08-28 21:51:07 +000068
69 Symtab = make<SymbolTable>();
70
Rui Ueyama7fed58c2016-12-08 19:10:28 +000071 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000072 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000073
74 // Call exit() if we can to avoid calling destructors.
75 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000076 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000077
78 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000079 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000080}
Rui Ueyama411c63602015-05-28 19:09:30 +000081
Nico Weber5660de72016-04-20 22:34:15 +000082// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000083static std::string getOutputPath(StringRef Path) {
84 auto P = Path.find_last_of("\\/");
85 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000086 const char* E = Config->DLL ? ".dll" : ".exe";
87 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000088}
89
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000090// ErrorOr is not default constructible, so it cannot be used as the type
91// parameter of a future.
92// FIXME: We could open the file in createFutureForFile and avoid needing to
93// return an error here, but for the moment that would cost us a file descriptor
94// (a limited resource on Windows) for the duration that the future is pending.
95typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
96
97// Create a std::future that opens and maps a file using the best strategy for
98// the host platform.
99static std::future<MBErrPair> createFutureForFile(std::string Path) {
100#if LLVM_ON_WIN32
101 // On Windows, file I/O is relatively slow so it is best to do this
102 // asynchronously.
103 auto Strategy = std::launch::async;
104#else
105 auto Strategy = std::launch::deferred;
106#endif
107 return std::async(Strategy, [=]() {
108 auto MBOrErr = MemoryBuffer::getFile(Path);
109 if (!MBOrErr)
110 return MBErrPair{nullptr, MBOrErr.getError()};
111 return MBErrPair{std::move(*MBOrErr), std::error_code()};
112 });
113}
114
115MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
116 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000117 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000118
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000119 if (Driver->Tar)
120 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
121 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000122 return MBRef;
123}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000124
Martin Storsjo8278ba52017-09-13 07:28:03 +0000125void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
126 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000127 StringRef Filename = MB->getBufferIdentifier();
128
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000129 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000130 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000131
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000132 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000133 switch (identify_magic(MBRef.getBuffer())) {
134 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000135 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000136 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000137 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000138 if (WholeArchive) {
139 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000140 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000141
142 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000143 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000144 return;
145 }
146 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000147 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000148 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000149 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000151 case file_magic::coff_object:
152 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000153 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000154 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000155 case file_magic::coff_cl_gl_object:
156 error(Filename + ": is not a native COFF file. Recompile without /GL");
157 break;
158 case file_magic::pecoff_executable:
159 if (Filename.endswith_lower(".dll")) {
160 error(Filename + ": bad file type. Did you specify a DLL instead of an "
161 "import library?");
162 break;
163 }
164 LLVM_FALLTHROUGH;
165 default:
166 error(MBRef.getBufferIdentifier() + ": unknown file type");
167 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000168 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000169}
170
Martin Storsjo8278ba52017-09-13 07:28:03 +0000171void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000172 auto Future =
173 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
174 std::string PathStr = Path;
175 enqueueTask([=]() {
176 auto MBOrErr = Future->get();
177 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000178 error("could not open " + PathStr + ": " + MBOrErr.second.message());
179 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000180 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000181 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000182}
183
184void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
185 StringRef ParentName) {
186 file_magic Magic = identify_magic(MB.getBuffer());
187 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000188 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000189 return;
190 }
191
192 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000193 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000194 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000195 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000196 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000197 } else {
198 error("unknown file type: " + MB.getBufferIdentifier());
199 return;
200 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000201
202 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000203 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000204 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000205}
206
207void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
208 StringRef SymName,
209 StringRef ParentName) {
210 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000211 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000212 C.getMemoryBufferRef(),
213 "could not get the buffer for the member defining symbol " + SymName);
214 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
215 return;
216 }
217
218 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000219 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000220 "could not get the filename for the member defining symbol " +
221 SymName)));
222 enqueueTask([=]() {
223 auto MBOrErr = Future->get();
224 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000225 fatal("could not get the buffer for the member defining " + SymName +
226 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000227 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
228 ParentName);
229 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000230}
231
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000232static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000233 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
234 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000235}
236
Rui Ueyama411c63602015-05-28 19:09:30 +0000237// Parses .drectve section contents and returns a list of files
238// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000239void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000240 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000241 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000242 // /EXPORT: option can appear too many times, processing in fastpath.
243 opt::InputArgList Args;
244 std::vector<StringRef> Exports;
245 std::tie(Args, Exports) = Parser.parseDirectives(S);
246
247 for (StringRef E : Exports) {
248 // If a common header file contains dllexported function
249 // declarations, many object files may end up with having the
250 // same /EXPORT options. In order to save cost of parsing them,
251 // we dedup them first.
252 if (!DirectivesExports.insert(E).second)
253 continue;
254
255 Export Exp = parseExport(E);
256 if (Config->Machine == I386 && Config->MinGW) {
257 if (!isDecorated(Exp.Name))
258 Exp.Name = Saver.save("_" + Exp.Name);
259 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
260 Exp.ExtName = Saver.save("_" + Exp.ExtName);
261 }
262 Exp.Directives = true;
263 Config->Exports.push_back(Exp);
264 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000265
David Blaikie6521ed92015-06-22 22:06:52 +0000266 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000267 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000268 case OPT_aligncomm:
269 parseAligncomm(Arg->getValue());
270 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000271 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000272 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000273 break;
274 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000275 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000276 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000277 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000278 case OPT_entry:
279 Config->Entry = addUndefined(mangle(Arg->getValue()));
280 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000281 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000282 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000283 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000284 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000285 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000286 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000287 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000288 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000289 break;
290 case OPT_nodefaultlib:
291 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
292 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000293 case OPT_section:
294 parseSection(Arg->getValue());
295 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000296 case OPT_subsystem:
297 parseSubsystem(Arg->getValue(), &Config->Subsystem,
298 &Config->MajorOSVersion, &Config->MinorOSVersion);
299 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000300 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000301 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000302 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000303 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000304 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000305 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000306 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000307 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000308 }
309 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000310}
311
Rui Ueyama54b71da2015-05-31 19:17:12 +0000312// Find file from search paths. You can omit ".obj", this function takes
313// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000314StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000315 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
316 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000317 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000318 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000319 for (StringRef Dir : SearchPaths) {
320 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000321 sys::path::append(Path, Filename);
322 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000323 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000324 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000325 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000326 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000327 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000328 }
329 }
330 return Filename;
331}
332
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000333// Resolves a file path. This never returns the same path
334// (in that case, it returns None).
335Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
336 StringRef Path = doFindFile(Filename);
337 bool Seen = !VisitedFiles.insert(Path.lower()).second;
338 if (Seen)
339 return None;
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000340 if (Path.endswith_lower(".lib"))
341 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000342 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000343}
344
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000345// Find library file from search path.
346StringRef LinkerDriver::doFindLib(StringRef Filename) {
347 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000348 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000349 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000350 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000351 return doFindFile(Filename);
352}
353
354// Resolves a library path. /nodefaultlib options are taken into
355// consideration. This never returns the same path (in that case,
356// it returns None).
357Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
358 if (Config->NoDefaultLibAll)
359 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000360 if (!VisitedLibs.insert(Filename.lower()).second)
361 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000362 StringRef Path = doFindLib(Filename);
363 if (Config->NoDefaultLibs.count(Path))
364 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000365 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000366 return None;
367 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000368}
369
370// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000371void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000372 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
373 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000374 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000375 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000376 while (!Env.empty()) {
377 StringRef Path;
378 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000379 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000380 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000381}
382
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000383Symbol *LinkerDriver::addUndefined(StringRef Name) {
384 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000385 if (!B->IsGCRoot) {
386 B->IsGCRoot = true;
387 Config->GCRoot.push_back(B);
388 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000389 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000390}
391
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000392// Symbol names are mangled by appending "_" prefix on x86.
393StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000394 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
395 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000396 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000397 return Sym;
398}
399
Rui Ueyama45044f42015-06-29 01:03:53 +0000400// Windows specific -- find default entry point name.
401StringRef LinkerDriver::findDefaultEntry() {
402 // User-defined main functions and their corresponding entry points.
403 static const char *Entries[][2] = {
404 {"main", "mainCRTStartup"},
405 {"wmain", "wmainCRTStartup"},
406 {"WinMain", "WinMainCRTStartup"},
407 {"wWinMain", "wWinMainCRTStartup"},
408 };
409 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000410 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000411 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000412 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000413 }
414 return "";
415}
416
417WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000418 if (Config->DLL)
419 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000420 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000421 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000422 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000423 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
424 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000425}
426
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000427static uint64_t getDefaultImageBase() {
428 if (Config->is64())
429 return Config->DLL ? 0x180000000 : 0x140000000;
430 return Config->DLL ? 0x10000000 : 0x400000;
431}
432
Rui Ueyama8fe17672016-12-08 20:50:47 +0000433static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000434 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000435 ArrayRef<StringRef> SearchPaths) {
436 SmallString<0> Data;
437 raw_svector_ostream OS(Data);
438
439 for (auto *Arg : Args) {
440 switch (Arg->getOption().getID()) {
441 case OPT_linkrepro:
442 case OPT_INPUT:
443 case OPT_defaultlib:
444 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000445 case OPT_manifest:
446 case OPT_manifest_colon:
447 case OPT_manifestdependency:
448 case OPT_manifestfile:
449 case OPT_manifestinput:
450 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000451 break;
452 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000453 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000454 }
455 }
456
457 for (StringRef Path : SearchPaths) {
458 std::string RelPath = relativeToRoot(Path);
459 OS << "/libpath:" << quote(RelPath) << "\n";
460 }
461
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000462 for (StringRef Path : FilePaths)
463 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000464
465 return Data.str();
466}
467
Rui Ueyama8fe17672016-12-08 20:50:47 +0000468static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000469 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
470 if (Args.hasArg(OPT_driver))
471 DebugTypes |= static_cast<unsigned>(DebugType::PData);
472 if (Args.hasArg(OPT_profile))
473 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
474 return DebugTypes;
475}
476
477static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000478 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000479 Arg.split(Types, ',', /*KeepEmpty=*/false);
480
481 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
482 for (StringRef Type : Types)
483 DebugTypes |= StringSwitch<unsigned>(Type.lower())
484 .Case("cv", static_cast<unsigned>(DebugType::CV))
485 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000486 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
487 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000488 return DebugTypes;
489}
490
Hans Wennborg1818e652016-12-09 20:54:44 +0000491static std::string getMapFile(const opt::InputArgList &Args) {
492 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
493 if (!Arg)
494 return "";
495 if (Arg->getOption().getID() == OPT_lldmap_file)
496 return Arg->getValue();
497
498 assert(Arg->getOption().getID() == OPT_lldmap);
499 StringRef OutFile = Config->OutputFile;
500 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
501}
502
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000503static std::string getImplibPath() {
504 if (!Config->Implib.empty())
505 return Config->Implib;
506 SmallString<128> Out = StringRef(Config->OutputFile);
507 sys::path::replace_extension(Out, ".lib");
508 return Out.str();
509}
510
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000511//
512// The import name is caculated as the following:
513//
514// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
515// -----+----------------+---------------------+------------------
516// LINK | {value} | {value}.{.dll/.exe} | {output name}
517// LIB | {value} | {value}.dll | {output name}.dll
518//
519static std::string getImportName(bool AsLib) {
520 SmallString<128> Out;
521
522 if (Config->ImportName.empty()) {
523 Out.assign(sys::path::filename(Config->OutputFile));
524 if (AsLib)
525 sys::path::replace_extension(Out, ".dll");
526 } else {
527 Out.assign(Config->ImportName);
528 if (!sys::path::has_extension(Out))
529 sys::path::replace_extension(Out,
530 (Config->DLL || AsLib) ? ".dll" : ".exe");
531 }
532
533 return Out.str();
534}
535
536static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000537 std::vector<COFFShortExport> Exports;
538 for (Export &E1 : Config->Exports) {
539 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000540 E2.Name = E1.Name;
541 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000542 E2.ExtName = E1.ExtName;
543 E2.Ordinal = E1.Ordinal;
544 E2.Noname = E1.Noname;
545 E2.Data = E1.Data;
546 E2.Private = E1.Private;
547 E2.Constant = E1.Constant;
548 Exports.push_back(E2);
549 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000550
Bob Haarman4ce341f2018-01-23 00:36:42 +0000551 auto HandleError = [](Error &&E) {
552 handleAllErrors(std::move(E),
553 [](ErrorInfoBase &EIB) { error(EIB.message()); });
554 };
555 std::string LibName = getImportName(AsLib);
556 std::string Path = getImplibPath();
557
Bob Haarman5ec44852018-01-31 23:44:00 +0000558 if (!Config->Incremental) {
559 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
560 false, Config->MinGW));
561 return;
562 }
563
Bob Haarman4ce341f2018-01-23 00:36:42 +0000564 // If the import library already exists, replace it only if the contents
565 // have changed.
566 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(Path);
567 if (!OldBuf) {
568 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
569 false, Config->MinGW));
570 return;
571 }
572
573 SmallString<128> TmpName;
574 if (std::error_code EC =
575 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
576 fatal("cannot create temporary file for import library " + Path + ": " +
577 EC.message());
578
579 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
580 false, Config->MinGW)) {
581 HandleError(std::move(E));
582 return;
583 }
584
585 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(TmpName));
586 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
587 OldBuf->reset();
588 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000589 } else {
590 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000591 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000592}
593
594static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000595 std::unique_ptr<MemoryBuffer> MB = CHECK(
596 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000597 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
598 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000599
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000600 if (Config->OutputFile.empty())
601 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000602 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000603 if (M.ImageBase)
604 Config->ImageBase = M.ImageBase;
605 if (M.StackReserve)
606 Config->StackReserve = M.StackReserve;
607 if (M.StackCommit)
608 Config->StackCommit = M.StackCommit;
609 if (M.HeapReserve)
610 Config->HeapReserve = M.HeapReserve;
611 if (M.HeapCommit)
612 Config->HeapCommit = M.HeapCommit;
613 if (M.MajorImageVersion)
614 Config->MajorImageVersion = M.MajorImageVersion;
615 if (M.MinorImageVersion)
616 Config->MinorImageVersion = M.MinorImageVersion;
617 if (M.MajorOSVersion)
618 Config->MajorOSVersion = M.MajorOSVersion;
619 if (M.MinorOSVersion)
620 Config->MinorOSVersion = M.MinorOSVersion;
621
622 for (COFFShortExport E1 : M.Exports) {
623 Export E2;
624 E2.Name = Saver.save(E1.Name);
625 if (E1.isWeak())
626 E2.ExtName = Saver.save(E1.ExtName);
627 E2.Ordinal = E1.Ordinal;
628 E2.Noname = E1.Noname;
629 E2.Data = E1.Data;
630 E2.Private = E1.Private;
631 E2.Constant = E1.Constant;
632 Config->Exports.push_back(E2);
633 }
634}
635
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000636// A helper function for filterBitcodeFiles.
637static bool needsRebuilding(MemoryBufferRef MB) {
638 // The MSVC linker doesn't support thin archives, so if it's a thin
639 // archive, we always need to rebuild it.
640 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000641 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000642 if (File->isThin())
643 return true;
644
645 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000646 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000647 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
648 return true;
649 return false;
650}
651
652// Opens a given path as an archive file and removes bitcode files
653// from them if exists. This function is to appease the MSVC linker as
654// their linker doesn't like archive files containing non-native
655// object files.
656//
657// If a given archive doesn't contain bitcode files, the archive path
658// is returned as-is. Otherwise, a new temporary file is created and
659// its path is returned.
660static Optional<std::string>
661filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000662 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000663 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000664 MemoryBufferRef MBRef = MB->getMemBufferRef();
665 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000666
667 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000668 return None;
669 if (Magic != file_magic::archive)
670 return Path.str();
671 if (!needsRebuilding(MBRef))
672 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000673
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000674 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000675 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000676 MBRef.getBufferIdentifier() + ": failed to parse archive");
677
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000678 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000679 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000680 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
681 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000682
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000683 if (New.empty())
684 return None;
685
686 log("Creating a temporary archive for " + Path + " to remove bitcode files");
687
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000688 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000689 if (std::error_code EC = sys::fs::createTemporaryFile(
690 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000691 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000692 std::string Temp = S.str();
693 TemporaryFiles.push_back(Temp);
694
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000695 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000696 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
697 /*Deterministics=*/true,
698 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000699 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
700 error("failed to create a new archive " + S.str() + ": " + EI.message());
701 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000702 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000703}
704
705// Create response file contents and invoke the MSVC linker.
706void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000707 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000708 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000709
Bob Haarman41108162017-04-21 21:38:01 +0000710 // Write out archive members that we used in symbol resolution and pass these
711 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
712 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000713 for (ObjFile *Obj : ObjFile::Instances) {
714 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000715 continue;
716 SmallString<128> S;
717 int Fd;
718 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000719 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000720 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000721 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000722 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000723 Temps.push_back(S.str());
724 Rsp += quote(S) + "\n";
725 }
726
Rui Ueyama85d54b02017-02-23 00:26:42 +0000727 for (auto *Arg : Args) {
728 switch (Arg->getOption().getID()) {
729 case OPT_linkrepro:
730 case OPT_lldmap:
731 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000732 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000733 case OPT_msvclto:
734 // LLD-specific options are stripped.
735 break;
736 case OPT_opt:
737 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000738 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000739 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000740 case OPT_INPUT: {
741 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
742 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000743 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000744 continue;
745 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000746 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000747 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000748 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000749 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000750 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000751 }
752 }
753
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000754 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000755 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000756
757 for (StringRef Path : Temps)
758 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000759}
760
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000761void LinkerDriver::enqueueTask(std::function<void()> Task) {
762 TaskQueue.push_back(std::move(Task));
763}
764
765bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000766 ScopedTimer T(InputFileTimer);
767
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000768 bool DidWork = !TaskQueue.empty();
769 while (!TaskQueue.empty()) {
770 TaskQueue.front()();
771 TaskQueue.pop_front();
772 }
773 return DidWork;
774}
775
Rui Ueyama57175aa2018-01-27 00:34:46 +0000776// Parse an /order file. If an option is given, the linker places
777// COMDAT sections in the same order as their names appear in the
778// given file.
779static void parseOrderFile(StringRef Arg) {
780 // For some reason, the MSVC linker requires a filename to be
781 // preceded by "@".
782 if (!Arg.startswith("@")) {
783 error("malformed /order option: '@' missing");
784 return;
785 }
786
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000787 // Get a list of all comdat sections for error checking.
788 DenseSet<StringRef> Set;
789 for (Chunk *C : Symtab->getChunks())
790 if (auto *Sec = dyn_cast<SectionChunk>(C))
791 if (Sec->Sym)
792 Set.insert(Sec->Sym->getName());
793
Rui Ueyama57175aa2018-01-27 00:34:46 +0000794 // Open a file.
795 StringRef Path = Arg.substr(1);
796 std::unique_ptr<MemoryBuffer> MB = CHECK(
797 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
798
799 // Parse a file. An order file contains one symbol per line.
800 // All symbols that were not present in a given order file are
801 // considered to have the lowest priority 0 and are placed at
802 // end of an output section.
803 for (std::string S : args::getLines(MB->getMemBufferRef())) {
804 if (Config->Machine == I386 && !isDecorated(S))
805 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000806
Nico Weber0771c602018-03-09 12:41:04 +0000807 if (Set.count(S) == 0) {
808 if (Config->WarnMissingOrderSymbol)
809 warn("/order:" + Arg + ": missing symbol: " + S);
810 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000811 else
812 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000813 }
814}
815
Rui Ueyama8fe17672016-12-08 20:50:47 +0000816void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000817 // If the first command line argument is "/lib", link.exe acts like lib.exe.
818 // We call our own implementation of lib.exe that understands bitcode files.
819 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
820 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000821 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000822 return;
823 }
824
Peter Collingbourne60c16162015-06-01 20:10:10 +0000825 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000826 InitializeAllTargetInfos();
827 InitializeAllTargets();
828 InitializeAllTargetMCs();
829 InitializeAllAsmParsers();
830 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000831
Rui Ueyama411c63602015-05-28 19:09:30 +0000832 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000833 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000834 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000835
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000836 // Parse and evaluate -mllvm options.
837 std::vector<const char *> V;
838 V.push_back("lld-link (LLVM option parsing)");
839 for (auto *Arg : Args.filtered(OPT_mllvm))
840 V.push_back(Arg->getValue());
841 cl::ParseCommandLineOptions(V.size(), V.data());
842
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000843 // Handle /errorlimit early, because error() depends on it.
844 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
845 int N = 20;
846 StringRef S = Arg->getValue();
847 if (S.getAsInteger(10, N))
848 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000849 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000850 }
851
Rui Ueyama5c726432015-05-29 16:11:52 +0000852 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000853 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000854 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000855 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000856 }
857
Zachary Turner727f1532018-01-17 19:16:26 +0000858 if (Args.hasArg(OPT_show_timing))
859 Config->ShowTiming = true;
860
861 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000862 // Handle --version, which is an lld extension. This option is a bit odd
863 // because it doesn't start with "/", but we deliberately chose "--" to
864 // avoid conflict with /version and for compatibility with clang-cl.
865 if (Args.hasArg(OPT_dash_dash_version)) {
866 outs() << getLLDVersion() << "\n";
867 return;
868 }
869
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000870 // Handle /lldmingw early, since it can potentially affect how other
871 // options are handled.
872 Config->MinGW = Args.hasArg(OPT_lldmingw);
873
Peter Collingbournefeee2102016-07-26 02:00:42 +0000874 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
875 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000876 sys::path::append(Path, "repro.tar");
877
878 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
879 TarWriter::create(Path, "repro");
880
881 if (ErrOrWriter) {
882 Tar = std::move(*ErrOrWriter);
883 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000884 error("/linkrepro: failed to open " + Path + ": " +
885 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000886 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000887 }
888
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000889 if (!Args.hasArg(OPT_INPUT)) {
890 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000891 Config->NoEntry = true;
892 else
893 fatal("no input files");
894 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000895
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000896 // Construct search path list.
897 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000898 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000899 SearchPaths.push_back(Arg->getValue());
900 addLibSearchPaths();
901
Bob Haarmane90ac012017-12-28 07:02:13 +0000902 // Handle /ignore
903 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000904 if (StringRef(Arg->getValue()) == "4037")
905 Config->WarnMissingOrderSymbol = false;
906 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000907 Config->WarnLocallyDefinedImported = false;
908 // Other warning numbers are ignored.
909 }
910
Rui Ueyamaad660982015-06-07 00:20:32 +0000911 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000912 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000913 Config->OutputFile = Arg->getValue();
914
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000915 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000916 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000917 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000918 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000919
Rui Ueyama95925fd2015-06-28 19:35:15 +0000920 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000921 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000922 Config->Force = true;
923
Rui Ueyama6600eb12015-07-04 23:37:32 +0000924 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000925 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000926 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000927 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000928 if (auto *Arg = Args.getLastArg(OPT_debugtype))
929 Config->DebugTypes = parseDebugType(Arg->getValue());
930 else
931 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000932 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000933
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000934 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000935 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
936 if (ShouldCreatePDB)
937 if (auto *Arg = Args.getLastArg(OPT_pdb))
938 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000939
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000940 // Handle /noentry
941 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000942 if (Args.hasArg(OPT_dll))
943 Config->NoEntry = true;
944 else
945 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000946 }
947
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000948 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000949 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000950 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000951 Config->ManifestID = 2;
952 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000953
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000954 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
955 // because we need to explicitly check whether that option or its inverse was
956 // present in the argument list in order to handle /fixed.
957 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
958 if (DynamicBaseArg &&
959 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
960 Config->DynamicBase = false;
961
962 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
963 if (Fixed) {
964 if (DynamicBaseArg &&
965 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000966 error("/fixed must not be specified with /dynamicbase");
967 } else {
968 Config->Relocatable = false;
969 Config->DynamicBase = false;
970 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000971 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000972
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000973 // Handle /appcontainer
974 Config->AppContainer =
975 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000976
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000977 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000978 if (auto *Arg = Args.getLastArg(OPT_machine))
979 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000980
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000981 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000982 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000983 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
984
985 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000986 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000987 Config->NoDefaultLibAll = true;
988
Rui Ueyama804a8b62015-05-29 16:18:15 +0000989 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000990 if (auto *Arg = Args.getLastArg(OPT_base))
991 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000992
993 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000994 if (auto *Arg = Args.getLastArg(OPT_stack))
995 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000996
Reid Kleckneraf2f7da2018-02-06 01:58:26 +0000997 // Handle /guard:cf
998 if (auto *Arg = Args.getLastArg(OPT_guard))
999 parseGuard(Arg->getValue());
1000
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001001 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +00001002 if (auto *Arg = Args.getLastArg(OPT_heap))
1003 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001004
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001005 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +00001006 if (auto *Arg = Args.getLastArg(OPT_version))
1007 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1008 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001009
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001010 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +00001011 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1012 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1013 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001014
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001015 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001016 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001017 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001018
Rui Ueyama08d5e182015-06-18 23:20:11 +00001019 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001020 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001021 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001022
Rui Ueyamab95188c2015-06-18 20:27:09 +00001023 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001024 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001025 Config->Implib = Arg->getValue();
1026
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001027 // Handle /opt.
1028 bool DoGC = !Args.hasArg(OPT_debug);
1029 unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on
David Blaikie6521ed92015-06-22 22:06:52 +00001030 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001031 std::string Str = StringRef(Arg->getValue()).lower();
1032 SmallVector<StringRef, 1> Vec;
1033 StringRef(Str).split(Vec, ',');
1034 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001035 if (S == "ref") {
1036 DoGC = true;
1037 } else if (S == "noref") {
1038 DoGC = false;
1039 } else if (S == "icf" || S.startswith("icf=")) {
1040 ICFLevel = 2;
1041 } else if (S == "noicf") {
1042 ICFLevel = 0;
1043 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001044 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001045 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
1046 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001047 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001048 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001049 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001050 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001051 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001052 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001053 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001054 if (N.getAsInteger(10, Config->LTOPartitions) ||
1055 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001056 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001057 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001058 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001059 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001060 }
1061
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001062 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1063 // explicitly.
1064 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1065 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1066 // comdat readonly data.
1067 if (ICFLevel == 1 && !DoGC)
1068 ICFLevel = 0;
1069 Config->DoGC = DoGC;
1070 Config->DoICF = ICFLevel > 0;
1071
Bob Haarman69b196d2017-02-08 18:36:41 +00001072 // Handle /lldsavetemps
1073 if (Args.hasArg(OPT_lldsavetemps))
1074 Config->SaveTemps = true;
1075
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001076 // Handle /lldltocache
1077 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1078 Config->LTOCache = Arg->getValue();
1079
1080 // Handle /lldsavecachepolicy
1081 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001082 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001083 parseCachePruningPolicy(Arg->getValue()),
1084 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1085
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001086 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001087 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001088 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001089
Rui Ueyama6600eb12015-07-04 23:37:32 +00001090 // Handle /merge
1091 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001092 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001093
Rui Ueyama440138c2016-06-20 03:39:39 +00001094 // Handle /section
1095 for (auto *Arg : Args.filtered(OPT_section))
1096 parseSection(Arg->getValue());
1097
Martin Storsjod2752aa2017-08-14 19:07:27 +00001098 // Handle /aligncomm
1099 for (auto *Arg : Args.filtered(OPT_aligncomm))
1100 parseAligncomm(Arg->getValue());
1101
Nico Webera7a2c442017-07-25 18:08:03 +00001102 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1103 // also passed.
1104 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1105 Config->ManifestDependency = Arg->getValue();
1106 Config->Manifest = Configuration::SideBySide;
1107 }
1108
1109 // Handle /manifest and /manifest:
1110 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1111 if (Arg->getOption().getID() == OPT_manifest)
1112 Config->Manifest = Configuration::SideBySide;
1113 else
1114 parseManifest(Arg->getValue());
1115 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001116
1117 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001118 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1119 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001120
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001121 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001122 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001123 Config->ManifestFile = Arg->getValue();
1124
Rui Ueyamaafb19012016-04-19 01:21:58 +00001125 // Handle /manifestinput
1126 for (auto *Arg : Args.filtered(OPT_manifestinput))
1127 Config->ManifestInput.push_back(Arg->getValue());
1128
Nico Webera7a2c442017-07-25 18:08:03 +00001129 if (!Config->ManifestInput.empty() &&
1130 Config->Manifest != Configuration::Embed) {
1131 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1132 }
1133
Rui Ueyama6592ff82015-06-16 23:13:00 +00001134 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001135 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1136 Config->AllowIsolation =
1137 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001138 Config->Incremental =
1139 Args.hasFlag(OPT_incremental, OPT_incremental_no,
1140 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order));
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001141 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1142 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001143 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001144 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001145
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001146 Config->MapFile = getMapFile(Args);
1147
Bob Haarman5ec44852018-01-31 23:44:00 +00001148 if (Config->Incremental && Config->DoGC) {
1149 warn("ignoring '/INCREMENTAL' because REF is enabled; use '/OPT:NOREF' to "
1150 "disable");
1151 Config->Incremental = false;
1152 }
1153
1154 if (Config->Incremental && Config->DoICF) {
1155 warn("ignoring '/INCREMENTAL' because ICF is enabled; use '/OPT:NOICF' to "
1156 "disable");
1157 Config->Incremental = false;
1158 }
1159
1160 if (Config->Incremental && Args.hasArg(OPT_order)) {
1161 warn("ignoring '/INCREMENTAL' due to '/ORDER' specification");
1162 Config->Incremental = false;
1163 }
1164
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001165 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001166 return;
1167
Martin Storsjo8278ba52017-09-13 07:28:03 +00001168 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001169 // Create a list of input files. Files can be given as arguments
1170 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001171 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001172 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1173 switch (Arg->getOption().getID()) {
1174 case OPT_INPUT:
1175 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1176 enqueuePath(*Path, WholeArchiveFlag);
1177 break;
1178 case OPT_wholearchive_file:
1179 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1180 enqueuePath(*Path, true);
1181 break;
1182 }
1183 }
David Blaikie6521ed92015-06-22 22:06:52 +00001184 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001185 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001186 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001187
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001188 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001189 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001190 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001191
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001192 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001193 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001194
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001195 // We should have inferred a machine type by now from the input files, but if
1196 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001197 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001198 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001199 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001200 }
1201
Eric Beckmann9e19d792017-06-17 02:26:27 +00001202 // Input files can be Windows resource files (.res files). We use
1203 // WindowsResource to convert resource files to a regular COFF file,
1204 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001205 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001206 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001207
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001208 if (Tar)
1209 Tar->append("response.txt",
1210 createResponseFile(Args, FilePaths,
1211 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001212
Rui Ueyama4d545342015-07-28 03:12:00 +00001213 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001214 Config->LargeAddressAware = Args.hasFlag(
1215 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001216
Rui Ueyamad68e2112015-07-28 03:15:57 +00001217 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001218 Config->HighEntropyVA =
1219 Config->is64() &&
1220 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001221
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001222 if (!Config->DynamicBase &&
1223 (Config->Machine == ARMNT || Config->Machine == ARM64))
1224 error("/dynamicbase:no is not compatible with " +
1225 machineToStr(Config->Machine));
1226
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001227 // Handle /entry and /dll
1228 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1229 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001230 } else if (!Config->Entry && !Config->NoEntry) {
1231 if (Args.hasArg(OPT_dll)) {
1232 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1233 : "_DllMainCRTStartup";
1234 Config->Entry = addUndefined(S);
1235 } else {
1236 // Windows specific -- If entry point name is not given, we need to
1237 // infer that from user-defined entry name.
1238 StringRef S = findDefaultEntry();
1239 if (S.empty())
1240 fatal("entry point must be defined");
1241 Config->Entry = addUndefined(S);
1242 log("Entry name inferred: " + S);
1243 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001244 }
1245
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001246 // Handle /export
1247 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001248 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001249 if (Config->Machine == I386) {
1250 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001251 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001252 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001253 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001254 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001255 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001256 }
1257
1258 // Handle /def
1259 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001260 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001261 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001262 }
1263
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001264 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001265 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001266 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001267 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001268 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001269 }
1270
Rui Ueyama6d249082015-07-13 22:31:45 +00001271 // Handle /delayload
1272 for (auto *Arg : Args.filtered(OPT_delayload)) {
1273 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001274 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001275 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001276 } else {
1277 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001278 }
1279 }
1280
Reid Kleckner7668182e2017-03-21 00:12:51 +00001281 // Set default image name if neither /out or /def set it.
1282 if (Config->OutputFile.empty()) {
1283 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001284 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001285 }
1286
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001287 // Put the PDB next to the image if no /pdb flag was passed.
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +00001288 if (ShouldCreatePDB && Config->PDBPath.empty()) {
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001289 Config->PDBPath = Config->OutputFile;
1290 sys::path::replace_extension(Config->PDBPath, ".pdb");
1291 }
1292
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001293 // Set default image base if /base is not given.
1294 if (Config->ImageBase == uint64_t(-1))
1295 Config->ImageBase = getDefaultImageBase();
1296
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001297 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001298 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001299 Symtab->addAbsolute("___safe_se_handler_table", 0);
1300 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001301 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001302
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001303 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1304 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001305 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001306 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1307 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1308 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1309 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001310 // Needed for MSVC 2017 15.5 CRT.
1311 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001312
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001313 // This code may add new undefined symbols to the link, which may enqueue more
1314 // symbol resolution tasks, so we need to continue executing tasks until we
1315 // converge.
1316 do {
1317 // Windows specific -- if entry point is not found,
1318 // search for its mangled names.
1319 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001320 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001321
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001322 // Windows specific -- Make sure we resolve all dllexported symbols.
1323 for (Export &E : Config->Exports) {
1324 if (!E.ForwardTo.empty())
1325 continue;
1326 E.Sym = addUndefined(E.Name);
1327 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001328 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001329 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001330
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001331 // Add weak aliases. Weak aliases is a mechanism to give remaining
1332 // undefined symbols final chance to be resolved successfully.
1333 for (auto Pair : Config->AlternateNames) {
1334 StringRef From = Pair.first;
1335 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001336 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001337 if (!Sym)
1338 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001339 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001340 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001341 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001342 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001343
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001344 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001345 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001346 addUndefined(mangle("_load_config_used"));
1347 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001348
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001349 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001350 return;
1351
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001352 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1353 // This is useful because MSVC link.exe can generate complete PDBs.
1354 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001355 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001356 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001357 }
1358
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001359 // Do LTO by compiling bitcode input files to a set of native COFF files then
1360 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001361 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001362 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001363
Peter Collingbourne2612a322015-07-04 05:28:41 +00001364 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001365 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001366 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001367 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001368
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001369 // Windows specific -- if no /subsystem is given, we need to infer
1370 // that from entry point name.
1371 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001372 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001373 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001374 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001375 }
1376
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001377 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001378 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001379 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001380 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001381 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001382 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001383 return;
1384 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001385
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001386 // In MinGW, all symbols are automatically exported if no symbols
1387 // are chosen to be exported.
1388 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1389 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001390 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001391
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001392 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001393 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001394 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001395 return;
1396 Export E;
1397 E.Name = Def->getName();
1398 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001399 if (Def->getChunk() &&
1400 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
1401 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001402 Config->Exports.push_back(E);
1403 });
1404 }
1405
Rui Ueyama151d8622015-06-17 20:40:43 +00001406 // Windows specific -- when we are creating a .dll file, we also
1407 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001408 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001409 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001410 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001411 assignExportOrdinals();
1412 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001413
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001414 // Handle /output-def (MinGW specific).
1415 if (auto *Arg = Args.getLastArg(OPT_output_def))
1416 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001417
Martin Storsjod2752aa2017-08-14 19:07:27 +00001418 // Set extra alignment for .comm symbols
1419 for (auto Pair : Config->AlignComm) {
1420 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001421 uint32_t Alignment = Pair.second;
1422
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001423 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001424 if (!Sym) {
1425 warn("/aligncomm symbol " + Name + " not found");
1426 continue;
1427 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001428
Rui Ueyama616cd992017-10-31 16:10:24 +00001429 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001430 if (!DC) {
1431 warn("/aligncomm symbol " + Name + " of wrong kind");
1432 continue;
1433 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001434
1435 CommonChunk *C = DC->getChunk();
1436 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001437 }
1438
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001439 // Windows specific -- Create a side-by-side manifest file.
1440 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001441 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001442
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001443 // Handle /order. We want to do this at this moment because we
1444 // need a complete list of comdat sections to warn on nonexistent
1445 // functions.
1446 if (auto *Arg = Args.getLastArg(OPT_order))
1447 parseOrderFile(Arg->getValue());
1448
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001449 // Identify unreferenced COMDAT sections.
1450 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001451 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001452
1453 // Identify identical COMDAT sections to merge them.
1454 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001455 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001456
Rui Ueyama411c63602015-05-28 19:09:30 +00001457 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001458 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001459
1460 // Stop early so we can print the results.
1461 Timer::root().stop();
1462 if (Config->ShowTiming)
1463 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001464}
1465
Rui Ueyama411c63602015-05-28 19:09:30 +00001466} // namespace coff
1467} // namespace lld