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