Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lld / MinGW / Driver.cpp
blob19bf2d1617057eb1dd0dea62d5f562fef8fd077a
1 //===- MinGW/Driver.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // MinGW is a GNU development environment for Windows. It consists of GNU
10 // tools such as GCC and GNU ld. Unlike Cygwin, there's no POSIX-compatible
11 // layer, as it aims to be a native development toolchain.
13 // lld/MinGW is a drop-in replacement for GNU ld/MinGW.
15 // Being a native development tool, a MinGW linker is not very different from
16 // Microsoft link.exe, so a MinGW linker can be implemented as a thin wrapper
17 // for lld/COFF. This driver takes Unix-ish command line options, translates
18 // them to Windows-ish ones, and then passes them to lld/COFF.
20 // When this driver calls the lld/COFF driver, it passes a hidden option
21 // "-lldmingw" along with other user-supplied options, to run the lld/COFF
22 // linker in "MinGW mode".
24 // There are subtle differences between MS link.exe and GNU ld/MinGW, and GNU
25 // ld/MinGW implements a few GNU-specific features. Such features are directly
26 // implemented in lld/COFF and enabled only when the linker is running in MinGW
27 // mode.
29 //===----------------------------------------------------------------------===//
31 #include "lld/Common/Driver.h"
32 #include "lld/Common/CommonLinkerContext.h"
33 #include "lld/Common/ErrorHandler.h"
34 #include "lld/Common/Memory.h"
35 #include "lld/Common/Version.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/TargetParser/Host.h"
46 #include "llvm/TargetParser/Triple.h"
47 #include <optional>
49 #if !defined(_MSC_VER) && !defined(__MINGW32__)
50 #include <unistd.h>
51 #endif
53 using namespace lld;
54 using namespace llvm::opt;
55 using namespace llvm;
57 // Create OptTable
58 enum {
59 OPT_INVALID = 0,
60 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
61 #include "Options.inc"
62 #undef OPTION
65 // Create prefix string literals used in Options.td
66 #define PREFIX(NAME, VALUE) \
67 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
68 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
69 NAME##_init, std::size(NAME##_init) - 1);
70 #include "Options.inc"
71 #undef PREFIX
73 // Create table mapping all options defined in Options.td
74 static constexpr opt::OptTable::Info infoTable[] = {
75 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
76 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES) \
77 {PREFIX, NAME, HELPTEXT, \
78 METAVAR, OPT_##ID, opt::Option::KIND##Class, \
79 PARAM, FLAGS, VISIBILITY, \
80 OPT_##GROUP, OPT_##ALIAS, ALIASARGS, \
81 VALUES},
82 #include "Options.inc"
83 #undef OPTION
86 namespace {
87 class MinGWOptTable : public opt::GenericOptTable {
88 public:
89 MinGWOptTable() : opt::GenericOptTable(infoTable, false) {}
90 opt::InputArgList parse(ArrayRef<const char *> argv);
92 } // namespace
94 static void printHelp(const char *argv0) {
95 MinGWOptTable().printHelp(
96 lld::outs(), (std::string(argv0) + " [options] file...").c_str(), "lld",
97 false /*ShowHidden*/, true /*ShowAllAliases*/);
98 lld::outs() << "\n";
101 static cl::TokenizerCallback getQuotingStyle() {
102 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
103 return cl::TokenizeWindowsCommandLine;
104 return cl::TokenizeGNUCommandLine;
107 opt::InputArgList MinGWOptTable::parse(ArrayRef<const char *> argv) {
108 unsigned missingIndex;
109 unsigned missingCount;
111 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
112 cl::ExpandResponseFiles(saver(), getQuotingStyle(), vec);
113 opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
115 if (missingCount)
116 error(StringRef(args.getArgString(missingIndex)) + ": missing argument");
117 for (auto *arg : args.filtered(OPT_UNKNOWN))
118 error("unknown argument: " + arg->getAsString(args));
119 return args;
122 // Find a file by concatenating given paths.
123 static std::optional<std::string> findFile(StringRef path1,
124 const Twine &path2) {
125 SmallString<128> s;
126 sys::path::append(s, path1, path2);
127 if (sys::fs::exists(s))
128 return std::string(s);
129 return std::nullopt;
132 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
133 static std::string
134 searchLibrary(StringRef name, ArrayRef<StringRef> searchPaths, bool bStatic) {
135 if (name.starts_with(":")) {
136 for (StringRef dir : searchPaths)
137 if (std::optional<std::string> s = findFile(dir, name.substr(1)))
138 return *s;
139 error("unable to find library -l" + name);
140 return "";
143 for (StringRef dir : searchPaths) {
144 if (!bStatic) {
145 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll.a"))
146 return *s;
147 if (std::optional<std::string> s = findFile(dir, name + ".dll.a"))
148 return *s;
150 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))
151 return *s;
152 if (std::optional<std::string> s = findFile(dir, name + ".lib"))
153 return *s;
154 if (!bStatic) {
155 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll"))
156 return *s;
157 if (std::optional<std::string> s = findFile(dir, name + ".dll"))
158 return *s;
161 error("unable to find library -l" + name);
162 return "";
165 namespace lld {
166 namespace coff {
167 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
168 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
171 namespace mingw {
172 // Convert Unix-ish command line arguments to Windows-ish ones and
173 // then call coff::link.
174 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
175 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
176 auto *ctx = new CommonLinkerContext;
177 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
179 MinGWOptTable parser;
180 opt::InputArgList args = parser.parse(argsArr.slice(1));
182 if (errorCount())
183 return false;
185 if (args.hasArg(OPT_help)) {
186 printHelp(argsArr[0]);
187 return true;
190 // A note about "compatible with GNU linkers" message: this is a hack for
191 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
192 // still the newest version in March 2017) or earlier to recognize LLD as
193 // a GNU compatible linker. As long as an output for the -v option
194 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
195 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
196 message(getLLDVersion() + " (compatible with GNU linkers)");
198 // The behavior of -v or --version is a bit strange, but this is
199 // needed for compatibility with GNU linkers.
200 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l))
201 return true;
202 if (args.hasArg(OPT_version))
203 return true;
205 if (!args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l)) {
206 error("no input files");
207 return false;
210 std::vector<std::string> linkArgs;
211 auto add = [&](const Twine &s) { linkArgs.push_back(s.str()); };
213 add("lld-link");
214 add("-lldmingw");
216 if (auto *a = args.getLastArg(OPT_entry)) {
217 StringRef s = a->getValue();
218 if (args.getLastArgValue(OPT_m) == "i386pe" && s.starts_with("_"))
219 add("-entry:" + s.substr(1));
220 else
221 add("-entry:" + s);
224 if (args.hasArg(OPT_major_os_version, OPT_minor_os_version,
225 OPT_major_subsystem_version, OPT_minor_subsystem_version)) {
226 StringRef majOSVer = args.getLastArgValue(OPT_major_os_version, "6");
227 StringRef minOSVer = args.getLastArgValue(OPT_minor_os_version, "0");
228 StringRef majSubSysVer = "6";
229 StringRef minSubSysVer = "0";
230 StringRef subSysName = "default";
231 StringRef subSysVer;
232 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
233 // the version number components from the last one of them that specifies
234 // a version.
235 for (auto *a : args.filtered(OPT_major_subsystem_version,
236 OPT_minor_subsystem_version, OPT_subs)) {
237 switch (a->getOption().getID()) {
238 case OPT_major_subsystem_version:
239 majSubSysVer = a->getValue();
240 break;
241 case OPT_minor_subsystem_version:
242 minSubSysVer = a->getValue();
243 break;
244 case OPT_subs:
245 std::tie(subSysName, subSysVer) = StringRef(a->getValue()).split(':');
246 if (!subSysVer.empty()) {
247 if (subSysVer.contains('.'))
248 std::tie(majSubSysVer, minSubSysVer) = subSysVer.split('.');
249 else
250 majSubSysVer = subSysVer;
252 break;
255 add("-osversion:" + majOSVer + "." + minOSVer);
256 add("-subsystem:" + subSysName + "," + majSubSysVer + "." + minSubSysVer);
257 } else if (args.hasArg(OPT_subs)) {
258 StringRef subSys = args.getLastArgValue(OPT_subs, "default");
259 StringRef subSysName, subSysVer;
260 std::tie(subSysName, subSysVer) = subSys.split(':');
261 StringRef sep = subSysVer.empty() ? "" : ",";
262 add("-subsystem:" + subSysName + sep + subSysVer);
265 if (auto *a = args.getLastArg(OPT_out_implib))
266 add("-implib:" + StringRef(a->getValue()));
267 if (auto *a = args.getLastArg(OPT_stack))
268 add("-stack:" + StringRef(a->getValue()));
269 if (auto *a = args.getLastArg(OPT_output_def))
270 add("-output-def:" + StringRef(a->getValue()));
271 if (auto *a = args.getLastArg(OPT_image_base))
272 add("-base:" + StringRef(a->getValue()));
273 if (auto *a = args.getLastArg(OPT_map))
274 add("-lldmap:" + StringRef(a->getValue()));
275 if (auto *a = args.getLastArg(OPT_reproduce))
276 add("-reproduce:" + StringRef(a->getValue()));
277 if (auto *a = args.getLastArg(OPT_thinlto_cache_dir))
278 add("-lldltocache:" + StringRef(a->getValue()));
279 if (auto *a = args.getLastArg(OPT_file_alignment))
280 add("-filealign:" + StringRef(a->getValue()));
281 if (auto *a = args.getLastArg(OPT_section_alignment))
282 add("-align:" + StringRef(a->getValue()));
283 if (auto *a = args.getLastArg(OPT_heap))
284 add("-heap:" + StringRef(a->getValue()));
285 if (auto *a = args.getLastArg(OPT_threads))
286 add("-threads:" + StringRef(a->getValue()));
288 if (auto *a = args.getLastArg(OPT_o))
289 add("-out:" + StringRef(a->getValue()));
290 else if (args.hasArg(OPT_shared))
291 add("-out:a.dll");
292 else
293 add("-out:a.exe");
295 if (auto *a = args.getLastArg(OPT_pdb)) {
296 add("-debug");
297 StringRef v = a->getValue();
298 if (!v.empty())
299 add("-pdb:" + v);
300 } else if (args.hasArg(OPT_strip_debug)) {
301 add("-debug:symtab");
302 } else if (!args.hasArg(OPT_strip_all)) {
303 add("-debug:dwarf");
306 if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false))
307 add("-WX");
308 else
309 add("-WX:no");
311 if (args.hasFlag(OPT_enable_stdcall_fixup, OPT_disable_stdcall_fixup, false))
312 add("-stdcall-fixup");
313 else if (args.hasArg(OPT_disable_stdcall_fixup))
314 add("-stdcall-fixup:no");
316 if (args.hasArg(OPT_shared))
317 add("-dll");
318 if (args.hasArg(OPT_verbose))
319 add("-verbose");
320 if (args.hasArg(OPT_exclude_all_symbols))
321 add("-exclude-all-symbols");
322 if (args.hasArg(OPT_export_all_symbols))
323 add("-export-all-symbols");
324 if (args.hasArg(OPT_large_address_aware))
325 add("-largeaddressaware");
326 if (args.hasArg(OPT_kill_at))
327 add("-kill-at");
328 if (args.hasArg(OPT_appcontainer))
329 add("-appcontainer");
330 if (args.hasFlag(OPT_no_seh, OPT_disable_no_seh, false))
331 add("-noseh");
333 if (args.getLastArgValue(OPT_m) != "thumb2pe" &&
334 args.getLastArgValue(OPT_m) != "arm64pe" &&
335 args.hasFlag(OPT_disable_dynamicbase, OPT_dynamicbase, false))
336 add("-dynamicbase:no");
337 if (args.hasFlag(OPT_disable_high_entropy_va, OPT_high_entropy_va, false))
338 add("-highentropyva:no");
339 if (args.hasFlag(OPT_disable_nxcompat, OPT_nxcompat, false))
340 add("-nxcompat:no");
341 if (args.hasFlag(OPT_disable_tsaware, OPT_tsaware, false))
342 add("-tsaware:no");
344 if (args.hasFlag(OPT_disable_reloc_section, OPT_enable_reloc_section, false))
345 add("-fixed");
347 if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false))
348 add("-timestamp:0");
350 if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false))
351 add("-opt:ref");
352 else
353 add("-opt:noref");
355 if (args.hasFlag(OPT_demangle, OPT_no_demangle, true))
356 add("-demangle");
357 else
358 add("-demangle:no");
360 if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true))
361 add("-auto-import");
362 else
363 add("-auto-import:no");
364 if (args.hasFlag(OPT_enable_runtime_pseudo_reloc,
365 OPT_disable_runtime_pseudo_reloc, true))
366 add("-runtime-pseudo-reloc");
367 else
368 add("-runtime-pseudo-reloc:no");
370 if (args.hasFlag(OPT_allow_multiple_definition,
371 OPT_no_allow_multiple_definition, false))
372 add("-force:multiple");
374 if (auto *a = args.getLastArg(OPT_icf)) {
375 StringRef s = a->getValue();
376 if (s == "all")
377 add("-opt:icf");
378 else if (s == "safe")
379 add("-opt:safeicf");
380 else if (s == "none")
381 add("-opt:noicf");
382 else
383 error("unknown parameter: --icf=" + s);
384 } else {
385 add("-opt:noicf");
388 if (auto *a = args.getLastArg(OPT_m)) {
389 StringRef s = a->getValue();
390 if (s == "i386pe")
391 add("-machine:x86");
392 else if (s == "i386pep")
393 add("-machine:x64");
394 else if (s == "thumb2pe")
395 add("-machine:arm");
396 else if (s == "arm64pe")
397 add("-machine:arm64");
398 else
399 error("unknown parameter: -m" + s);
402 if (args.hasFlag(OPT_guard_cf, OPT_no_guard_cf, false)) {
403 if (args.hasFlag(OPT_guard_longjmp, OPT_no_guard_longjmp, true))
404 add("-guard:cf,longjmp");
405 else
406 add("-guard:cf,nolongjmp");
407 } else if (args.hasFlag(OPT_guard_longjmp, OPT_no_guard_longjmp, false)) {
408 auto *a = args.getLastArg(OPT_guard_longjmp);
409 warn("parameter " + a->getSpelling() +
410 " only takes effect when used with --guard-cf");
413 if (auto *a = args.getLastArg(OPT_error_limit)) {
414 int n;
415 StringRef s = a->getValue();
416 if (s.getAsInteger(10, n))
417 error(a->getSpelling() + ": number expected, but got " + s);
418 else
419 add("-errorlimit:" + s);
422 for (auto *a : args.filtered(OPT_mllvm))
423 add("-mllvm:" + StringRef(a->getValue()));
425 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
426 add("-mllvm:-mcpu=" + StringRef(arg->getValue()));
427 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
428 add("-opt:lldltojobs=" + StringRef(arg->getValue()));
429 if (auto *arg = args.getLastArg(OPT_lto_O))
430 add("-opt:lldlto=" + StringRef(arg->getValue()));
431 if (auto *arg = args.getLastArg(OPT_lto_CGO))
432 add("-opt:lldltocgo=" + StringRef(arg->getValue()));
433 if (auto *arg = args.getLastArg(OPT_plugin_opt_dwo_dir_eq))
434 add("-dwodir:" + StringRef(arg->getValue()));
435 if (args.hasArg(OPT_lto_cs_profile_generate))
436 add("-lto-cs-profile-generate");
437 if (auto *arg = args.getLastArg(OPT_lto_cs_profile_file))
438 add("-lto-cs-profile-file:" + StringRef(arg->getValue()));
440 for (auto *a : args.filtered(OPT_plugin_opt_eq_minus))
441 add("-mllvm:-" + StringRef(a->getValue()));
443 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
444 // relative path. Just ignore. If not ended with "lto-wrapper" (or
445 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
446 // unsupported LLVMgold.so option and error.
447 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
448 StringRef v(arg->getValue());
449 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
450 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
451 "'");
454 for (auto *a : args.filtered(OPT_Xlink))
455 add(a->getValue());
457 if (args.getLastArgValue(OPT_m) == "i386pe")
458 add("-alternatename:__image_base__=___ImageBase");
459 else
460 add("-alternatename:__image_base__=__ImageBase");
462 for (auto *a : args.filtered(OPT_require_defined))
463 add("-include:" + StringRef(a->getValue()));
464 for (auto *a : args.filtered(OPT_undefined))
465 add("-includeoptional:" + StringRef(a->getValue()));
466 for (auto *a : args.filtered(OPT_delayload))
467 add("-delayload:" + StringRef(a->getValue()));
468 for (auto *a : args.filtered(OPT_wrap))
469 add("-wrap:" + StringRef(a->getValue()));
470 for (auto *a : args.filtered(OPT_exclude_symbols))
471 add("-exclude-symbols:" + StringRef(a->getValue()));
473 std::vector<StringRef> searchPaths;
474 for (auto *a : args.filtered(OPT_L)) {
475 searchPaths.push_back(a->getValue());
476 add("-libpath:" + StringRef(a->getValue()));
479 StringRef prefix = "";
480 bool isStatic = false;
481 for (auto *a : args) {
482 switch (a->getOption().getID()) {
483 case OPT_INPUT:
484 if (StringRef(a->getValue()).ends_with_insensitive(".def"))
485 add("-def:" + StringRef(a->getValue()));
486 else
487 add(prefix + StringRef(a->getValue()));
488 break;
489 case OPT_l:
490 add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic));
491 break;
492 case OPT_whole_archive:
493 prefix = "-wholearchive:";
494 break;
495 case OPT_no_whole_archive:
496 prefix = "";
497 break;
498 case OPT_Bstatic:
499 isStatic = true;
500 break;
501 case OPT_Bdynamic:
502 isStatic = false;
503 break;
507 if (errorCount())
508 return false;
510 if (args.hasArg(OPT_verbose) || args.hasArg(OPT__HASH_HASH_HASH))
511 lld::errs() << llvm::join(linkArgs, " ") << "\n";
513 if (args.hasArg(OPT__HASH_HASH_HASH))
514 return true;
516 // Repack vector of strings to vector of const char pointers for coff::link.
517 std::vector<const char *> vec;
518 for (const std::string &s : linkArgs)
519 vec.push_back(s.c_str());
520 // Pass the actual binary name, to make error messages be printed with
521 // the right prefix.
522 vec[0] = argsArr[0];
524 // The context will be re-created in the COFF driver.
525 lld::CommonLinkerContext::destroy();
527 return coff::link(vec, stdoutOS, stderrOS, exitEarly, disableOutput);
529 } // namespace mingw
530 } // namespace lld