clang 20.0.0git
MinGW.cpp
Go to the documentation of this file.
1//===--- MinGW.cpp - MinGWToolChain Implementation ------------------------===//
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#include "MinGW.h"
10#include "CommonArgs.h"
11#include "clang/Config/config.h"
13#include "clang/Driver/Driver.h"
18#include "llvm/Config/llvm-config.h" // for LLVM_HOST_TRIPLE
19#include "llvm/Option/ArgList.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/VirtualFileSystem.h"
23#include <system_error>
24
25using namespace clang::diag;
26using namespace clang::driver;
27using namespace clang;
28using namespace llvm::opt;
29
30/// MinGW Tools
32 const InputInfo &Output,
33 const InputInfoList &Inputs,
34 const ArgList &Args,
35 const char *LinkingOutput) const {
36 claimNoWarnArgs(Args);
37 ArgStringList CmdArgs;
38
39 if (getToolChain().getArch() == llvm::Triple::x86) {
40 CmdArgs.push_back("--32");
41 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
42 CmdArgs.push_back("--64");
43 }
44
45 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
46
47 CmdArgs.push_back("-o");
48 CmdArgs.push_back(Output.getFilename());
49
50 for (const auto &II : Inputs)
51 CmdArgs.push_back(II.getFilename());
52
53 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
54 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
55 Exec, CmdArgs, Inputs, Output));
56
57 if (Args.hasArg(options::OPT_gsplit_dwarf))
58 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
59 SplitDebugName(JA, Args, Inputs[0], Output));
60}
61
62void tools::MinGW::Linker::AddLibGCC(const ArgList &Args,
63 ArgStringList &CmdArgs) const {
64 if (Args.hasArg(options::OPT_mthreads))
65 CmdArgs.push_back("-lmingwthrd");
66 CmdArgs.push_back("-lmingw32");
67
68 // Make use of compiler-rt if --rtlib option is used
69 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
70 if (RLT == ToolChain::RLT_Libgcc) {
71 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
72 Args.hasArg(options::OPT_static);
73 bool Shared = Args.hasArg(options::OPT_shared);
74 bool CXX = getToolChain().getDriver().CCCIsCXX();
75
76 if (Static || (!CXX && !Shared)) {
77 CmdArgs.push_back("-lgcc");
78 CmdArgs.push_back("-lgcc_eh");
79 } else {
80 CmdArgs.push_back("-lgcc_s");
81 CmdArgs.push_back("-lgcc");
82 }
83 } else {
84 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
85 }
86
87 CmdArgs.push_back("-lmoldname");
88 CmdArgs.push_back("-lmingwex");
89 for (auto Lib : Args.getAllArgValues(options::OPT_l))
90 if (StringRef(Lib).starts_with("msvcr") ||
91 StringRef(Lib).starts_with("ucrt") ||
92 StringRef(Lib).starts_with("crtdll"))
93 return;
94 CmdArgs.push_back("-lmsvcrt");
95}
96
98 const InputInfo &Output,
99 const InputInfoList &Inputs,
100 const ArgList &Args,
101 const char *LinkingOutput) const {
102 const ToolChain &TC = getToolChain();
103 const Driver &D = TC.getDriver();
104 const SanitizerArgs &Sanitize = TC.getSanitizerArgs(Args);
105
106 ArgStringList CmdArgs;
107
108 // Silence warning for "clang -g foo.o -o foo"
109 Args.ClaimAllArgs(options::OPT_g_Group);
110 // and "clang -emit-llvm foo.o -o foo"
111 Args.ClaimAllArgs(options::OPT_emit_llvm);
112 // and for "clang -w foo.o -o foo". Other warning options are already
113 // handled somewhere else.
114 Args.ClaimAllArgs(options::OPT_w);
115
116 if (!D.SysRoot.empty())
117 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
118
119 if (Args.hasArg(options::OPT_s))
120 CmdArgs.push_back("-s");
121
122 CmdArgs.push_back("-m");
123 switch (TC.getArch()) {
124 case llvm::Triple::x86:
125 CmdArgs.push_back("i386pe");
126 break;
127 case llvm::Triple::x86_64:
128 CmdArgs.push_back("i386pep");
129 break;
130 case llvm::Triple::arm:
131 case llvm::Triple::thumb:
132 // FIXME: this is incorrect for WinCE
133 CmdArgs.push_back("thumb2pe");
134 break;
135 case llvm::Triple::aarch64:
136 if (TC.getEffectiveTriple().isWindowsArm64EC())
137 CmdArgs.push_back("arm64ecpe");
138 else
139 CmdArgs.push_back("arm64pe");
140 break;
141 default:
142 D.Diag(diag::err_target_unknown_triple) << TC.getEffectiveTriple().str();
143 }
144
145 Arg *SubsysArg =
146 Args.getLastArg(options::OPT_mwindows, options::OPT_mconsole);
147 if (SubsysArg && SubsysArg->getOption().matches(options::OPT_mwindows)) {
148 CmdArgs.push_back("--subsystem");
149 CmdArgs.push_back("windows");
150 } else if (SubsysArg &&
151 SubsysArg->getOption().matches(options::OPT_mconsole)) {
152 CmdArgs.push_back("--subsystem");
153 CmdArgs.push_back("console");
154 }
155
156 if (Args.hasArg(options::OPT_mdll))
157 CmdArgs.push_back("--dll");
158 else if (Args.hasArg(options::OPT_shared))
159 CmdArgs.push_back("--shared");
160 if (Args.hasArg(options::OPT_static))
161 CmdArgs.push_back("-Bstatic");
162 else
163 CmdArgs.push_back("-Bdynamic");
164 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
165 CmdArgs.push_back("-e");
166 if (TC.getArch() == llvm::Triple::x86)
167 CmdArgs.push_back("_DllMainCRTStartup@12");
168 else
169 CmdArgs.push_back("DllMainCRTStartup");
170 CmdArgs.push_back("--enable-auto-image-base");
171 }
172
173 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
174 CmdArgs.push_back("--no-demangle");
175
176 if (!Args.hasFlag(options::OPT_fauto_import, options::OPT_fno_auto_import,
177 true))
178 CmdArgs.push_back("--disable-auto-import");
179
180 if (Arg *A = Args.getLastArg(options::OPT_mguard_EQ)) {
181 StringRef GuardArgs = A->getValue();
182 if (GuardArgs == "none")
183 CmdArgs.push_back("--no-guard-cf");
184 else if (GuardArgs == "cf" || GuardArgs == "cf-nochecks")
185 CmdArgs.push_back("--guard-cf");
186 else
187 D.Diag(diag::err_drv_unsupported_option_argument)
188 << A->getSpelling() << GuardArgs;
189 }
190
191 if (Args.hasArg(options::OPT_fms_hotpatch))
192 CmdArgs.push_back("--functionpadmin");
193
194 CmdArgs.push_back("-o");
195 const char *OutputFile = Output.getFilename();
196 // GCC implicitly adds an .exe extension if it is given an output file name
197 // that lacks an extension.
198 // GCC used to do this only when the compiler itself runs on windows, but
199 // since GCC 8 it does the same when cross compiling as well.
200 if (!llvm::sys::path::has_extension(OutputFile)) {
201 CmdArgs.push_back(Args.MakeArgString(Twine(OutputFile) + ".exe"));
202 OutputFile = CmdArgs.back();
203 } else
204 CmdArgs.push_back(OutputFile);
205
206 // FIXME: add -N, -n flags
207 Args.AddLastArg(CmdArgs, options::OPT_r);
208 Args.AddLastArg(CmdArgs, options::OPT_s);
209 Args.AddLastArg(CmdArgs, options::OPT_t);
210 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
211
212 // Add asan_dynamic as the first import lib before other libs. This allows
213 // asan to be initialized as early as possible to increase its instrumentation
214 // coverage to include other user DLLs which has not been built with asan.
215 if (Sanitize.needsAsanRt() && !Args.hasArg(options::OPT_nostdlib) &&
216 !Args.hasArg(options::OPT_nodefaultlibs)) {
217 // MinGW always links against a shared MSVCRT.
218 CmdArgs.push_back(
219 TC.getCompilerRTArgString(Args, "asan_dynamic", ToolChain::FT_Shared));
220 }
221
222 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
223 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
224 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
225 } else {
226 if (Args.hasArg(options::OPT_municode))
227 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
228 else
229 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
230 }
231 if (Args.hasArg(options::OPT_pg))
232 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
233 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
234 }
235
236 Args.AddAllArgs(CmdArgs, options::OPT_L);
237 TC.AddFilePathLibArgs(Args, CmdArgs);
238
239 // Add the compiler-rt library directories if they exist to help
240 // the linker find the various sanitizer, builtin, and profiling runtimes.
241 for (const auto &LibPath : TC.getLibraryPaths()) {
242 if (TC.getVFS().exists(LibPath))
243 CmdArgs.push_back(Args.MakeArgString("-L" + LibPath));
244 }
245 auto CRTPath = TC.getCompilerRTPath();
246 if (TC.getVFS().exists(CRTPath))
247 CmdArgs.push_back(Args.MakeArgString("-L" + CRTPath));
248
249 AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
250
251 if (D.isUsingLTO()) {
252 assert(!Inputs.empty() && "Must have at least one input.");
253 addLTOOptions(TC, Args, CmdArgs, Output, Inputs[0],
254 D.getLTOMode() == LTOK_Thin);
255 }
256
257 if (C.getDriver().IsFlangMode() &&
258 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
259 addFortranRuntimeLibraryPath(TC, Args, CmdArgs);
260 addFortranRuntimeLibs(TC, Args, CmdArgs);
261 }
262
263 // TODO: Add profile stuff here
264
265 if (TC.ShouldLinkCXXStdlib(Args)) {
266 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
267 !Args.hasArg(options::OPT_static);
268 if (OnlyLibstdcxxStatic)
269 CmdArgs.push_back("-Bstatic");
270 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
271 if (OnlyLibstdcxxStatic)
272 CmdArgs.push_back("-Bdynamic");
273 }
274
275 bool HasWindowsApp = false;
276 for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
277 if (Lib == "windowsapp") {
278 HasWindowsApp = true;
279 break;
280 }
281 }
282
283 if (!Args.hasArg(options::OPT_nostdlib)) {
284 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
285 if (Args.hasArg(options::OPT_static))
286 CmdArgs.push_back("--start-group");
287
288 if (Args.hasArg(options::OPT_fstack_protector) ||
289 Args.hasArg(options::OPT_fstack_protector_strong) ||
290 Args.hasArg(options::OPT_fstack_protector_all)) {
291 CmdArgs.push_back("-lssp_nonshared");
292 CmdArgs.push_back("-lssp");
293 }
294
295 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
296 options::OPT_fno_openmp, false)) {
297 switch (TC.getDriver().getOpenMPRuntime(Args)) {
299 CmdArgs.push_back("-lomp");
300 break;
302 CmdArgs.push_back("-liomp5md");
303 break;
305 CmdArgs.push_back("-lgomp");
306 break;
308 // Already diagnosed.
309 break;
310 }
311 }
312
313 AddLibGCC(Args, CmdArgs);
314
315 if (Args.hasArg(options::OPT_pg))
316 CmdArgs.push_back("-lgmon");
317
318 if (Args.hasArg(options::OPT_pthread))
319 CmdArgs.push_back("-lpthread");
320
321 if (Sanitize.needsAsanRt()) {
322 // MinGW always links against a shared MSVCRT.
323 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic",
325 CmdArgs.push_back(
326 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
327 CmdArgs.push_back("--require-defined");
328 CmdArgs.push_back(TC.getArch() == llvm::Triple::x86
329 ? "___asan_seh_interceptor"
330 : "__asan_seh_interceptor");
331 // Make sure the linker consider all object files from the dynamic
332 // runtime thunk.
333 CmdArgs.push_back("--whole-archive");
334 CmdArgs.push_back(
335 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
336 CmdArgs.push_back("--no-whole-archive");
337 }
338
339 TC.addProfileRTLibs(Args, CmdArgs);
340
341 if (!HasWindowsApp) {
342 // Add system libraries. If linking to libwindowsapp.a, that import
343 // library replaces all these and we shouldn't accidentally try to
344 // link to the normal desktop mode dlls.
345 if (Args.hasArg(options::OPT_mwindows)) {
346 CmdArgs.push_back("-lgdi32");
347 CmdArgs.push_back("-lcomdlg32");
348 }
349 CmdArgs.push_back("-ladvapi32");
350 CmdArgs.push_back("-lshell32");
351 CmdArgs.push_back("-luser32");
352 CmdArgs.push_back("-lkernel32");
353 }
354
355 if (Args.hasArg(options::OPT_static)) {
356 CmdArgs.push_back("--end-group");
357 } else {
358 AddLibGCC(Args, CmdArgs);
359 if (!HasWindowsApp)
360 CmdArgs.push_back("-lkernel32");
361 }
362 }
363
364 if (!Args.hasArg(options::OPT_nostartfiles)) {
365 // Add crtfastmath.o if available and fast math is enabled.
366 TC.addFastMathRuntimeIfAvailable(Args, CmdArgs);
367
368 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
369 }
370 }
371 const char *Exec = Args.MakeArgString(TC.GetLinkerPath());
372 C.addCommand(std::make_unique<Command>(JA, *this,
374 Exec, CmdArgs, Inputs, Output));
375}
376
377static bool isCrossCompiling(const llvm::Triple &T, bool RequireArchMatch) {
378 llvm::Triple HostTriple(llvm::Triple::normalize(LLVM_HOST_TRIPLE));
379 if (HostTriple.getOS() != llvm::Triple::Win32)
380 return true;
381 if (RequireArchMatch && HostTriple.getArch() != T.getArch())
382 return true;
383 return false;
384}
385
386// Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple.
387static bool findGccVersion(StringRef LibDir, std::string &GccLibDir,
388 std::string &Ver,
391 std::error_code EC;
392 for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE;
393 LI = LI.increment(EC)) {
394 StringRef VersionText = llvm::sys::path::filename(LI->path());
395 auto CandidateVersion =
397 if (CandidateVersion.Major == -1)
398 continue;
399 if (CandidateVersion <= Version)
400 continue;
401 Version = CandidateVersion;
402 Ver = std::string(VersionText);
403 GccLibDir = LI->path();
404 }
405 return Ver.size();
406}
407
408static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T) {
409 llvm::Triple LiteralTriple(D.getTargetTriple());
410 // The arch portion of the triple may be overridden by -m32/-m64.
411 LiteralTriple.setArchName(T.getArchName());
412 return LiteralTriple;
413}
414
415void toolchains::MinGW::findGccLibDir(const llvm::Triple &LiteralTriple) {
417 SubdirNames.emplace_back(LiteralTriple.str());
418 SubdirNames.emplace_back(getTriple().str());
419 SubdirNames.emplace_back(getTriple().getArchName());
420 SubdirNames.back() += "-w64-mingw32";
421 SubdirNames.emplace_back(getTriple().getArchName());
422 SubdirNames.back() += "-w64-mingw32ucrt";
423 SubdirNames.emplace_back("mingw32");
424 if (SubdirName.empty()) {
425 SubdirName = getTriple().getArchName();
426 SubdirName += "-w64-mingw32";
427 }
428 // lib: Arch Linux, Ubuntu, Windows
429 // lib64: openSUSE Linux
430 for (StringRef CandidateLib : {"lib", "lib64"}) {
431 for (StringRef CandidateSysroot : SubdirNames) {
433 llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot);
434 if (findGccVersion(LibDir, GccLibDir, Ver, GccVer)) {
435 SubdirName = std::string(CandidateSysroot);
436 return;
437 }
438 }
439 }
440}
441
442static llvm::ErrorOr<std::string> findGcc(const llvm::Triple &LiteralTriple,
443 const llvm::Triple &T) {
445 Gccs.emplace_back(LiteralTriple.str());
446 Gccs.back() += "-gcc";
447 Gccs.emplace_back(T.str());
448 Gccs.back() += "-gcc";
449 Gccs.emplace_back(T.getArchName());
450 Gccs.back() += "-w64-mingw32-gcc";
451 Gccs.emplace_back(T.getArchName());
452 Gccs.back() += "-w64-mingw32ucrt-gcc";
453 Gccs.emplace_back("mingw32-gcc");
454 // Please do not add "gcc" here
455 for (StringRef CandidateGcc : Gccs)
456 if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName(CandidateGcc))
457 return GPPName;
458 return make_error_code(std::errc::no_such_file_or_directory);
459}
460
461static llvm::ErrorOr<std::string>
462findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple,
463 const llvm::Triple &T, std::string &SubdirName) {
465 Subdirs.emplace_back(LiteralTriple.str());
466 Subdirs.emplace_back(T.str());
467 Subdirs.emplace_back(T.getArchName());
468 Subdirs.back() += "-w64-mingw32";
469 Subdirs.emplace_back(T.getArchName());
470 Subdirs.back() += "-w64-mingw32ucrt";
471 StringRef ClangRoot = llvm::sys::path::parent_path(D.Dir);
472 StringRef Sep = llvm::sys::path::get_separator();
473 for (StringRef CandidateSubdir : Subdirs) {
474 if (llvm::sys::fs::is_directory(ClangRoot + Sep + CandidateSubdir)) {
475 SubdirName = std::string(CandidateSubdir);
476 return (ClangRoot + Sep + CandidateSubdir).str();
477 }
478 }
479 return make_error_code(std::errc::no_such_file_or_directory);
480}
481
482static bool looksLikeMinGWSysroot(const std::string &Directory) {
483 StringRef Sep = llvm::sys::path::get_separator();
484 if (!llvm::sys::fs::exists(Directory + Sep + "include" + Sep + "_mingw.h"))
485 return false;
486 if (!llvm::sys::fs::exists(Directory + Sep + "lib" + Sep + "libkernel32.a"))
487 return false;
488 return true;
489}
490
491toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
492 const ArgList &Args)
493 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
494 RocmInstallation(D, Triple, Args) {
495 getProgramPaths().push_back(getDriver().Dir);
496
497 std::string InstallBase =
498 std::string(llvm::sys::path::parent_path(getDriver().Dir));
499 // The sequence for detecting a sysroot here should be kept in sync with
500 // the testTriple function below.
501 llvm::Triple LiteralTriple = getLiteralTriple(D, getTriple());
502 if (getDriver().SysRoot.size())
504 // Look for <clang-bin>/../<triplet>; if found, use <clang-bin>/.. as the
505 // base as it could still be a base for a gcc setup with libgcc.
506 else if (llvm::ErrorOr<std::string> TargetSubdir = findClangRelativeSysroot(
507 getDriver(), LiteralTriple, getTriple(), SubdirName))
508 Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
509 // If the install base of Clang seems to have mingw sysroot files directly
510 // in the toplevel include and lib directories, use this as base instead of
511 // looking for a triple prefixed GCC in the path.
512 else if (looksLikeMinGWSysroot(InstallBase))
513 Base = InstallBase;
514 else if (llvm::ErrorOr<std::string> GPPName =
515 findGcc(LiteralTriple, getTriple()))
516 Base = std::string(llvm::sys::path::parent_path(
517 llvm::sys::path::parent_path(GPPName.get())));
518 else
519 Base = InstallBase;
520
521 Base += llvm::sys::path::get_separator();
522 findGccLibDir(LiteralTriple);
523 TripleDirName = SubdirName;
524 // GccLibDir must precede Base/lib so that the
525 // correct crtbegin.o ,cetend.o would be found.
526 getFilePaths().push_back(GccLibDir);
527
528 // openSUSE/Fedora
529 std::string CandidateSubdir = SubdirName + "/sys-root/mingw";
530 if (getDriver().getVFS().exists(Base + CandidateSubdir))
531 SubdirName = CandidateSubdir;
532
533 getFilePaths().push_back(
534 (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str());
535
536 // Gentoo
537 getFilePaths().push_back(
538 (Base + SubdirName + llvm::sys::path::get_separator() + "mingw/lib").str());
539
540 // Only include <base>/lib if we're not cross compiling (not even for
541 // windows->windows to a different arch), or if the sysroot has been set
542 // (where we presume the user has pointed it at an arch specific
543 // subdirectory).
544 if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/true) ||
545 getDriver().SysRoot.size())
546 getFilePaths().push_back(Base + "lib");
547
548 NativeLLVMSupport =
549 Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER)
550 .equals_insensitive("lld");
551}
552
554 switch (AC) {
556 if (!Preprocessor)
557 Preprocessor.reset(new tools::gcc::Preprocessor(*this));
558 return Preprocessor.get();
560 if (!Compiler)
561 Compiler.reset(new tools::gcc::Compiler(*this));
562 return Compiler.get();
563 default:
564 return ToolChain::getTool(AC);
565 }
566}
567
569 return new tools::MinGW::Assembler(*this);
570}
571
573 return new tools::MinGW::Linker(*this);
574}
575
577 return NativeLLVMSupport;
578}
579
582 Arg *ExceptionArg = Args.getLastArg(options::OPT_fsjlj_exceptions,
583 options::OPT_fseh_exceptions,
584 options::OPT_fdwarf_exceptions);
585 if (ExceptionArg &&
586 ExceptionArg->getOption().matches(options::OPT_fseh_exceptions))
587 return UnwindTableLevel::Asynchronous;
588
589 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
590 getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
591 return UnwindTableLevel::Asynchronous;
592 return UnwindTableLevel::None;
593}
594
596 return getArch() == llvm::Triple::x86_64 ||
597 getArch() == llvm::Triple::aarch64;
598}
599
600bool toolchains::MinGW::isPIEDefault(const llvm::opt::ArgList &Args) const {
601 return false;
602}
603
604bool toolchains::MinGW::isPICDefaultForced() const { return true; }
605
606llvm::ExceptionHandling
607toolchains::MinGW::GetExceptionModel(const ArgList &Args) const {
608 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::aarch64 ||
609 getArch() == llvm::Triple::arm || getArch() == llvm::Triple::thumb)
610 return llvm::ExceptionHandling::WinEH;
611 return llvm::ExceptionHandling::DwarfCFI;
612}
613
616 Res |= SanitizerKind::Address;
617 Res |= SanitizerKind::PointerCompare;
618 Res |= SanitizerKind::PointerSubtract;
619 Res |= SanitizerKind::Vptr;
620 return Res;
621}
622
623void toolchains::MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs,
624 ArgStringList &CC1Args) const {
625 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
626}
627
628void toolchains::MinGW::AddHIPIncludeArgs(const ArgList &DriverArgs,
629 ArgStringList &CC1Args) const {
630 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
631}
632
633void toolchains::MinGW::printVerboseInfo(raw_ostream &OS) const {
634 CudaInstallation->print(OS);
635 RocmInstallation->print(OS);
636}
637
638// Include directories for various hosts:
639
640// Windows, mingw.org
641// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++
642// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32
643// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward
644// c:\mingw\include
645// c:\mingw\mingw32\include
646
647// Windows, mingw-w64 mingw-builds
648// c:\mingw32\i686-w64-mingw32\include
649// c:\mingw32\i686-w64-mingw32\include\c++
650// c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32
651// c:\mingw32\i686-w64-mingw32\include\c++\backward
652
653// Windows, mingw-w64 msys2
654// c:\msys64\mingw32\include
655// c:\msys64\mingw32\i686-w64-mingw32\include
656// c:\msys64\mingw32\include\c++\4.9.2
657// c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32
658// c:\msys64\mingw32\include\c++\4.9.2\backward
659
660// openSUSE
661// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++
662// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32
663// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward
664// /usr/x86_64-w64-mingw32/sys-root/mingw/include
665
666// Arch Linux
667// /usr/i686-w64-mingw32/include/c++/5.1.0
668// /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32
669// /usr/i686-w64-mingw32/include/c++/5.1.0/backward
670// /usr/i686-w64-mingw32/include
671
672// Ubuntu
673// /usr/include/c++/4.8
674// /usr/include/c++/4.8/x86_64-w64-mingw32
675// /usr/include/c++/4.8/backward
676// /usr/x86_64-w64-mingw32/include
677
678// Fedora
679// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/x86_64-w64-mingw32ucrt
680// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/backward
681// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include
682// /usr/lib/gcc/x86_64-w64-mingw32ucrt/12.2.1/include-fixed
683
684void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
685 ArgStringList &CC1Args) const {
686 if (DriverArgs.hasArg(options::OPT_nostdinc))
687 return;
688
689 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
690 SmallString<1024> P(getDriver().ResourceDir);
691 llvm::sys::path::append(P, "include");
692 addSystemInclude(DriverArgs, CC1Args, P.str());
693 }
694
695 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
696 return;
697
698 addSystemInclude(DriverArgs, CC1Args,
699 Base + SubdirName + llvm::sys::path::get_separator() +
700 "include");
701
702 // Gentoo
703 addSystemInclude(DriverArgs, CC1Args,
704 Base + SubdirName + llvm::sys::path::get_separator() + "usr/include");
705
706 // Only include <base>/include if we're not cross compiling (but do allow it
707 // if we're on Windows and building for Windows on another architecture),
708 // or if the sysroot has been set (where we presume the user has pointed it
709 // at an arch specific subdirectory).
710 if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/false) ||
711 getDriver().SysRoot.size())
712 addSystemInclude(DriverArgs, CC1Args, Base + "include");
713}
714
716 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
717 Action::OffloadKind DeviceOffloadKind) const {
718 if (Arg *A = DriverArgs.getLastArg(options::OPT_mguard_EQ)) {
719 StringRef GuardArgs = A->getValue();
720 if (GuardArgs == "none") {
721 // Do nothing.
722 } else if (GuardArgs == "cf") {
723 // Emit CFG instrumentation and the table of address-taken functions.
724 CC1Args.push_back("-cfguard");
725 } else if (GuardArgs == "cf-nochecks") {
726 // Emit only the table of address-taken functions.
727 CC1Args.push_back("-cfguard-no-checks");
728 } else {
729 getDriver().Diag(diag::err_drv_unsupported_option_argument)
730 << A->getSpelling() << GuardArgs;
731 }
732 }
733
734 // Default to not enabling sized deallocation, but let user provided options
735 // override it.
736 //
737 // If using sized deallocation, user code that invokes delete will end up
738 // calling delete(void*,size_t). If the user wanted to override the
739 // operator delete(void*), there may be a fallback operator
740 // delete(void*,size_t) which calls the regular operator delete(void*).
741 //
742 // However, if the C++ standard library is linked in the form of a DLL,
743 // and the fallback operator delete(void*,size_t) is within this DLL (which is
744 // the case for libc++ at least) it will only redirect towards the library's
745 // default operator delete(void*), not towards the user's provided operator
746 // delete(void*).
747 //
748 // This issue can be avoided, if the fallback operators are linked statically
749 // into the callers, even if the C++ standard library is linked as a DLL.
750 //
751 // This is meant as a temporary workaround until libc++ implements this
752 // technique, which is tracked in
753 // https://github.com/llvm/llvm-project/issues/96899.
754 if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation,
755 options::OPT_fno_sized_deallocation))
756 CC1Args.push_back("-fno-sized-deallocation");
757
758 CC1Args.push_back("-fno-use-init-array");
759
760 for (auto Opt : {options::OPT_mthreads, options::OPT_mwindows,
761 options::OPT_mconsole, options::OPT_mdll}) {
762 if (Arg *A = DriverArgs.getLastArgNoClaim(Opt))
763 A->ignoreTargetSpecific();
764 }
765}
766
768 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
769 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
770 options::OPT_nostdincxx))
771 return;
772
773 StringRef Slash = llvm::sys::path::get_separator();
774
775 switch (GetCXXStdlibType(DriverArgs)) {
777 std::string TargetDir = (Base + "include" + Slash + getTripleString() +
778 Slash + "c++" + Slash + "v1")
779 .str();
780 if (getDriver().getVFS().exists(TargetDir))
781 addSystemInclude(DriverArgs, CC1Args, TargetDir);
782 addSystemInclude(DriverArgs, CC1Args,
783 Base + SubdirName + Slash + "include" + Slash + "c++" +
784 Slash + "v1");
785 addSystemInclude(DriverArgs, CC1Args,
786 Base + "include" + Slash + "c++" + Slash + "v1");
787 break;
788 }
789
792 CppIncludeBases.emplace_back(Base);
793 llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++");
794 CppIncludeBases.emplace_back(Base);
795 llvm::sys::path::append(CppIncludeBases[1], SubdirName, "include", "c++",
796 Ver);
797 CppIncludeBases.emplace_back(Base);
798 llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver);
799 CppIncludeBases.emplace_back(GccLibDir);
800 llvm::sys::path::append(CppIncludeBases[3], "include", "c++");
801 CppIncludeBases.emplace_back(GccLibDir);
802 llvm::sys::path::append(CppIncludeBases[4], "include",
803 "g++-v" + GccVer.Text);
804 CppIncludeBases.emplace_back(GccLibDir);
805 llvm::sys::path::append(CppIncludeBases[5], "include",
806 "g++-v" + GccVer.MajorStr + "." + GccVer.MinorStr);
807 CppIncludeBases.emplace_back(GccLibDir);
808 llvm::sys::path::append(CppIncludeBases[6], "include",
809 "g++-v" + GccVer.MajorStr);
810 for (auto &CppIncludeBase : CppIncludeBases) {
811 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
812 CppIncludeBase += Slash;
813 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + TripleDirName);
814 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
815 }
816 break;
817 }
818}
819
820static bool testTriple(const Driver &D, const llvm::Triple &Triple,
821 const ArgList &Args) {
822 // If an explicit sysroot is set, that will be used and we shouldn't try to
823 // detect anything else.
824 std::string SubdirName;
825 if (D.SysRoot.size())
826 return true;
827 llvm::Triple LiteralTriple = getLiteralTriple(D, Triple);
828 std::string InstallBase = std::string(llvm::sys::path::parent_path(D.Dir));
829 if (llvm::ErrorOr<std::string> TargetSubdir =
830 findClangRelativeSysroot(D, LiteralTriple, Triple, SubdirName))
831 return true;
832 // If the install base itself looks like a mingw sysroot, we'll use that
833 // - don't use any potentially unrelated gcc to influence what triple to use.
834 if (looksLikeMinGWSysroot(InstallBase))
835 return false;
836 if (llvm::ErrorOr<std::string> GPPName = findGcc(LiteralTriple, Triple))
837 return true;
838 // If we neither found a colocated sysroot or a matching gcc executable,
839 // conclude that we can't know if this is the correct spelling of the triple.
840 return false;
841}
842
843static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple,
844 const ArgList &Args) {
845 // First test if the original triple can find a sysroot with the triple
846 // name.
847 if (testTriple(D, Triple, Args))
848 return Triple;
850 // If not, test a couple other possible arch names that might be what was
851 // intended.
852 if (Triple.getArch() == llvm::Triple::x86) {
853 Archs.emplace_back("i386");
854 Archs.emplace_back("i586");
855 Archs.emplace_back("i686");
856 } else if (Triple.getArch() == llvm::Triple::arm ||
857 Triple.getArch() == llvm::Triple::thumb) {
858 Archs.emplace_back("armv7");
859 }
860 for (auto A : Archs) {
861 llvm::Triple TestTriple(Triple);
862 TestTriple.setArchName(A);
863 if (testTriple(D, TestTriple, Args))
864 return TestTriple;
865 }
866 // If none was found, just proceed with the original value.
867 return Triple;
868}
869
870void toolchains::MinGW::fixTripleArch(const Driver &D, llvm::Triple &Triple,
871 const ArgList &Args) {
872 if (Triple.getArch() == llvm::Triple::x86 ||
873 Triple.getArch() == llvm::Triple::arm ||
874 Triple.getArch() == llvm::Triple::thumb)
875 Triple = adjustTriple(D, Triple, Args);
876}
StringRef P
const Decl * D
static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T)
Definition: MinGW.cpp:408
static bool looksLikeMinGWSysroot(const std::string &Directory)
Definition: MinGW.cpp:482
static bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver, toolchains::Generic_GCC::GCCVersion &Version)
Definition: MinGW.cpp:387
static bool testTriple(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
Definition: MinGW.cpp:820
static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
Definition: MinGW.cpp:843
static llvm::ErrorOr< std::string > findGcc(const llvm::Triple &LiteralTriple, const llvm::Triple &T)
Definition: MinGW.cpp:442
static llvm::ErrorOr< std::string > findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple, const llvm::Triple &T, std::string &SubdirName)
Definition: MinGW.cpp:462
static bool isCrossCompiling(const llvm::Triple &T, bool RequireArchMatch)
Definition: MinGW.cpp:377
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
std::string SysRoot
sysroot, if present
Definition: Driver.h:180
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition: Driver.cpp:758
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:140
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:130
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition: Driver.h:126
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition: Driver.h:135
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:785
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:1367
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:949
path_list & getFilePaths()
Definition: ToolChain.h:294
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:268
const Driver & getDriver() const
Definition: ToolChain.h:252
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:153
bool addFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:1440
path_list & getProgramPaths()
Definition: ToolChain.h:297
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:282
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:1373
const llvm::Triple & getTriple() const
Definition: ToolChain.h:254
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition: ToolChain.cpp:1169
virtual std::string getCompilerRTPath() const
Definition: ToolChain.cpp:698
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
Definition: ToolChain.cpp:957
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:1392
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:378
path_list & getLibraryPaths()
Definition: ToolChain.h:291
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:609
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:1456
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:1052
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
Tool * getTool(Action::ActionClass AC) const override
Definition: MinGW.cpp:553
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: MinGW.cpp:607
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: MinGW.cpp:715
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: MinGW.cpp:614
Tool * buildAssembler() const override
Definition: MinGW.cpp:568
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: MinGW.cpp:633
Tool * buildLinker() const override
Definition: MinGW.cpp:572
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition: MinGW.cpp:628
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition: MinGW.cpp:600
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition: MinGW.cpp:623
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: MinGW.cpp:576
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: MinGW.cpp:595
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: MinGW.cpp:604
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition: MinGW.cpp:684
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: MinGW.cpp:767
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition: MinGW.cpp:581
MinGW(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: MinGW.cpp:491
static void fixTripleArch(const Driver &D, llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: MinGW.cpp:870
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
MinGW Tools.
Definition: MinGW.cpp:31
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: MinGW.cpp:97
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
void addFortranRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds the path for the Fortran runtime libraries to CmdArgs.
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfo &Input, bool IsThinLTO)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
void addFortranRuntimeLibs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds Fortran runtime libraries to CmdArgs.
The JSON file list parser is used to communicate input to InstallAPI.
std::error_code make_error_code(BuildPreambleError Error)
const FunctionProtoType * T
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition: Job.h:78
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85
Struct to store and manipulate GCC versions.
Definition: Gnu.h:162
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition: Gnu.cpp:2126