clang 23.0.0git
MSVC.cpp
Go to the documentation of this file.
1//===-- MSVC.cpp - MSVC ToolChain Implementations -------------------------===//
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 "MSVC.h"
10#include "Darwin.h"
11#include "clang/Config/config.h"
14#include "clang/Driver/Driver.h"
17#include "llvm/Option/Arg.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Support/ConvertUTF.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/Process.h"
24#include "llvm/Support/VirtualFileSystem.h"
25#include "llvm/TargetParser/Host.h"
26#include <cstdio>
27
28#ifdef _WIN32
29 #define WIN32_LEAN_AND_MEAN
30 #define NOGDI
31 #ifndef NOMINMAX
32 #define NOMINMAX
33 #endif
34 #include <windows.h>
35#endif
36
37using namespace clang::driver;
38using namespace clang::driver::toolchains;
39using namespace clang::driver::tools;
40using namespace clang;
41using namespace llvm::opt;
42
43static bool canExecute(llvm::vfs::FileSystem &VFS, StringRef Path) {
44 auto Status = VFS.status(Path);
45 if (!Status)
46 return false;
47 return (Status->getPermissions() & llvm::sys::fs::perms::all_exe) != 0;
48}
49
50// Try to find Exe from a Visual Studio distribution. This first tries to find
51// an installed copy of Visual Studio and, failing that, looks in the PATH,
52// making sure that whatever executable that's found is not a same-named exe
53// from clang itself to prevent clang from falling back to itself.
54static std::string FindVisualStudioExecutable(const ToolChain &TC,
55 const char *Exe) {
56 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
57 SmallString<128> FilePath(
58 MSVC.getSubDirectoryPath(llvm::SubDirectoryType::Bin));
59 llvm::sys::path::append(FilePath, Exe);
60 return std::string(canExecute(TC.getVFS(), FilePath) ? FilePath.str() : Exe);
61}
62
64 const InputInfo &Output,
65 const InputInfoList &Inputs,
66 const ArgList &Args,
67 const char *LinkingOutput) const {
68 ArgStringList CmdArgs;
69
70 auto &TC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
71
72 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
73 if (Output.isFilename())
74 CmdArgs.push_back(
75 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
76
77 if (Args.hasArg(options::OPT_marm64x))
78 CmdArgs.push_back("-machine:arm64x");
79 else if (TC.getTriple().isWindowsArm64EC())
80 CmdArgs.push_back("-machine:arm64ec");
81
82 if (const Arg *A = Args.getLastArg(options::OPT_fveclib)) {
83 StringRef V = A->getValue();
84 if (V == "ArmPL")
85 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=amath"));
86 }
87
88 // SYCL requires dynamic CRT because STL objects cross DLL boundaries.
89 // Library dependency is added via --dependent-lib at compiler stage.
90 // Here we validate CRT compatibility and add the library search path.
91 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
92 !Args.hasArg(options::OPT_nolibsycl) &&
93 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
94
95 // Check if static CRT is being used. Use getLastArg to handle overriding
96 // options (e.g., /MT /MD -> /MD wins).
97 bool HasStaticCRT = false;
98
99 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
100 StringRef RuntimeLib = A->getValue();
101 if (RuntimeLib == "static" || RuntimeLib == "static_dbg")
102 HasStaticCRT = true;
103 }
104
105 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
106 if (A->getOption().matches(options::OPT__SLASH_MT) ||
107 A->getOption().matches(options::OPT__SLASH_MTd))
108 HasStaticCRT = true;
109 }
110
111 if (HasStaticCRT) {
112 TC.getDriver().Diag(diag::err_drv_sycl_requires_dynamic_crt);
113 } else {
114 // Add library search path so linker can find LLVMSYCL[d].lib.
115 SmallString<128> LibPath(TC.getDriver().Dir);
116 llvm::sys::path::append(LibPath, "..", "lib");
117 CmdArgs.push_back(Args.MakeArgString(Twine("-libpath:") + LibPath));
118 }
119 }
120
121 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
122 !C.getDriver().IsCLMode() && !C.getDriver().IsFlangMode()) {
123 CmdArgs.push_back("-defaultlib:libcmt");
124 CmdArgs.push_back("-defaultlib:oldnames");
125
126 // SYCL: Add runtime library for clang (non-clang-cl) with MSVC target.
127 // For clang-cl, --dependent-lib is used at compiler stage instead.
128 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
129 !Args.hasArg(options::OPT_nolibsycl)) {
130 bool IsDebugBuild = false;
131 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
132 StringRef RuntimeVal = A->getValue();
133 if (RuntimeVal == "dll_dbg")
134 IsDebugBuild = true;
135 }
136 CmdArgs.push_back(IsDebugBuild ? "-defaultlib:LLVMSYCLd"
137 : "-defaultlib:LLVMSYCL");
138 }
139 }
140
141 // If the VC environment hasn't been configured (perhaps because the user
142 // did not run vcvarsall), try to build a consistent link environment. If
143 // the environment variable is set however, assume the user knows what
144 // they're doing. If the user passes /vctoolsdir or /winsdkdir, trust that
145 // over env vars.
146 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diasdkdir,
147 options::OPT__SLASH_winsysroot)) {
148 // cl.exe doesn't find the DIA SDK automatically, so this too requires
149 // explicit flags and doesn't automatically look in "DIA SDK" relative
150 // to the path we found for VCToolChainPath.
151 llvm::SmallString<128> DIAPath(A->getValue());
152 if (A->getOption().getID() == options::OPT__SLASH_winsysroot)
153 llvm::sys::path::append(DIAPath, "DIA SDK");
154
155 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
156 llvm::sys::path::append(DIAPath, "lib",
157 llvm::archToLegacyVCArch(TC.getArch()));
158 CmdArgs.push_back(Args.MakeArgString(Twine("-libpath:") + DIAPath));
159 }
160 if (!llvm::sys::Process::GetEnv("LIB") ||
161 Args.hasArg(options::OPT__SLASH_vctoolsdir,
162 options::OPT__SLASH_vctoolsversion,
163 options::OPT__SLASH_winsysroot)) {
164 CmdArgs.push_back(Args.MakeArgString(
165 Twine("-libpath:") +
166 TC.getSubDirectoryPath(llvm::SubDirectoryType::Lib)));
167 CmdArgs.push_back(Args.MakeArgString(
168 Twine("-libpath:") +
169 TC.getSubDirectoryPath(llvm::SubDirectoryType::Lib, "atlmfc")));
170 }
171 if (!llvm::sys::Process::GetEnv("LIB") ||
172 Args.hasArg(options::OPT__SLASH_winsdkdir,
173 options::OPT__SLASH_winsdkversion,
174 options::OPT__SLASH_winsysroot)) {
175 if (TC.useUniversalCRT()) {
176 std::string UniversalCRTLibPath;
177 if (TC.getUniversalCRTLibraryPath(Args, UniversalCRTLibPath))
178 CmdArgs.push_back(
179 Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath));
180 }
181 std::string WindowsSdkLibPath;
182 if (TC.getWindowsSDKLibraryPath(Args, WindowsSdkLibPath))
183 CmdArgs.push_back(
184 Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
185 }
186
187 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
188 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
189 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
190
191 if (C.getDriver().IsFlangMode() &&
192 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
193 TC.addFortranRuntimeLibraryPath(Args, CmdArgs);
194 TC.addFortranRuntimeLibs(Args, CmdArgs);
195
196 // Inform the MSVC linker that we're generating a console application, i.e.
197 // one with `main` as the "user-defined" entry point. The `main` function is
198 // defined in flang's runtime libraries.
199 CmdArgs.push_back("/subsystem:console");
200 }
201
202 // Add the compiler-rt library directories to libpath if they exist to help
203 // the linker find the various sanitizer, builtin, and profiling runtimes.
204 for (const auto &LibPath : TC.getLibraryPaths()) {
205 if (TC.getVFS().exists(LibPath))
206 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
207 }
208 for (const auto &LibPath : TC.getFilePaths()) {
209 if (LibPath.length() > 0)
210 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
211 }
212 auto CRTPath = TC.getCompilerRTPath();
213 if (TC.getVFS().exists(CRTPath))
214 CmdArgs.push_back(Args.MakeArgString("-libpath:" + CRTPath));
215
216 // SYCL offload compilation creates .llvm.offloading sections in each object
217 // file to store device code and metadata. Suppress linker warning about
218 // multiple sections with different attributes (LNK4078).
219 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false))
220 CmdArgs.push_back("/IGNORE:4078");
221
222 CmdArgs.push_back("-nologo");
223
224 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
225 CmdArgs.push_back("-debug");
226
227 // If we specify /hotpatch, let the linker add padding in front of each
228 // function, like MSVC does.
229 if (Args.hasArg(options::OPT_fms_hotpatch, options::OPT__SLASH_hotpatch))
230 CmdArgs.push_back("-functionpadmin");
231
232 // Pass on /Brepro if it was passed to the compiler.
233 // Note that /Brepro maps to -mno-incremental-linker-compatible.
234 bool DefaultIncrementalLinkerCompatible =
235 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
236 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
237 options::OPT_mno_incremental_linker_compatible,
238 DefaultIncrementalLinkerCompatible))
239 CmdArgs.push_back("-Brepro");
240
241 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
242 options::OPT_shared);
243 if (DLL) {
244 CmdArgs.push_back(Args.MakeArgString("-dll"));
245
246 SmallString<128> ImplibName(Output.getFilename());
247 llvm::sys::path::replace_extension(ImplibName, "lib");
248 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
249 }
250
251 if (TC.getSanitizerArgs(Args).needsFuzzer()) {
252 if (!Args.hasArg(options::OPT_shared))
253 CmdArgs.push_back(
254 Args.MakeArgString(std::string("-wholearchive:") +
255 TC.getCompilerRTArgString(Args, "fuzzer")));
256 CmdArgs.push_back(Args.MakeArgString("-debug"));
257 // Prevent the linker from padding sections we use for instrumentation
258 // arrays.
259 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
260 }
261
262 if (TC.getSanitizerArgs(Args).needsAsanRt()) {
263 CmdArgs.push_back(Args.MakeArgString("-debug"));
264 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
265 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic"));
266 auto defines = Args.getAllArgValues(options::OPT_D);
267 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd) ||
268 llvm::is_contained(defines, "_DLL")) {
269 // Make sure the dynamic runtime thunk is not optimized out at link time
270 // to ensure proper SEH handling.
271 CmdArgs.push_back(Args.MakeArgString(
272 TC.getArch() == llvm::Triple::x86
273 ? "-include:___asan_seh_interceptor"
274 : "-include:__asan_seh_interceptor"));
275 // Make sure the linker consider all object files from the dynamic runtime
276 // thunk.
277 CmdArgs.push_back(Args.MakeArgString(
278 std::string("-wholearchive:") +
279 TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk")));
280 } else {
281 // Make sure the linker consider all object files from the static runtime
282 // thunk.
283 CmdArgs.push_back(Args.MakeArgString(
284 std::string("-wholearchive:") +
285 TC.getCompilerRT(Args, "asan_static_runtime_thunk")));
286 }
287 }
288
289 if (TC.isUsingLTO(Args)) {
290 if (Arg *A = tools::getLastProfileSampleUseArg(Args))
291 CmdArgs.push_back(Args.MakeArgString(std::string("-lto-sample-profile:") +
292 A->getValue()));
293 }
294 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
295
296 // Control Flow Guard checks
297 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
298 StringRef GuardArgs = A->getValue();
299 if (GuardArgs.equals_insensitive("cf") ||
300 GuardArgs.equals_insensitive("cf,nochecks")) {
301 // MSVC doesn't yet support the "nochecks" modifier.
302 CmdArgs.push_back("-guard:cf");
303 } else if (GuardArgs.equals_insensitive("cf-")) {
304 CmdArgs.push_back("-guard:cf-");
305 } else if (GuardArgs.equals_insensitive("ehcont")) {
306 CmdArgs.push_back("-guard:ehcont");
307 } else if (GuardArgs.equals_insensitive("ehcont-")) {
308 CmdArgs.push_back("-guard:ehcont-");
309 }
310 }
311
312 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
313 options::OPT_fno_openmp, false)) {
314 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
315 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
316 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
317 TC.getDriver().Dir + "/../lib"));
318 switch (TC.getDriver().getOpenMPRuntime(Args)) {
320 CmdArgs.push_back("-defaultlib:libomp.lib");
321 break;
323 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
324 break;
326 break;
328 // Already diagnosed.
329 break;
330 }
331 }
332
333 // Add compiler-rt lib in case if it was explicitly
334 // specified as an argument for --rtlib option.
335 if (!Args.hasArg(options::OPT_nostdlib)) {
336 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
337 }
338
339 const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ);
340 StringRef Linker = A ? A->getValue() : TC.getDriver().getPreferredLinker();
341
342 if (Linker.empty()) {
343 // If DWARF is requested, use LLD, because MSVC's link.exe will silently
344 // truncate the .debug_* sections to eight characters. PE/COFF doesn't allow
345 // section names longer than eight bytes in executables - LLD uses the same
346 // name length extension as in object files (where long names are allowed).
347 if (Args.hasArg(options::OPT_gdwarf, options::OPT_gdwarf_2,
348 options::OPT_gdwarf_3, options::OPT_gdwarf_4,
349 options::OPT_gdwarf_5, options::OPT_gdwarf_6))
350 Linker = "lld-link";
351 else
352 Linker = "link";
353 }
354
355 // We need to translate 'lld' into 'lld-link'.
356 if (Linker.equals_insensitive("lld"))
357 Linker = "lld-link";
358
359 if (Linker == "lld-link") {
360 for (Arg *A : Args.filtered(options::OPT_vfsoverlay))
361 CmdArgs.push_back(
362 Args.MakeArgString(std::string("/vfsoverlay:") + A->getValue()));
363
364 if (TC.isUsingLTO(Args) &&
365 Args.hasFlag(options::OPT_gsplit_dwarf, options::OPT_gno_split_dwarf,
366 false))
367 CmdArgs.push_back(Args.MakeArgString(Twine("/dwodir:") +
368 Output.getFilename() + "_dwo"));
369 }
370
371 // Add filenames, libraries, and other linker inputs.
372 for (const auto &Input : Inputs) {
373 if (Input.isFilename()) {
374 CmdArgs.push_back(Input.getFilename());
375 continue;
376 }
377
378 const Arg &A = Input.getInputArg();
379
380 // Render -l options differently for the MSVC linker.
381 if (A.getOption().matches(options::OPT_l)) {
382 StringRef Lib = A.getValue();
383 const char *LinkLibArg;
384 if (Lib.ends_with(".lib"))
385 LinkLibArg = Args.MakeArgString(Lib);
386 else
387 LinkLibArg = Args.MakeArgString(Lib + ".lib");
388 CmdArgs.push_back(LinkLibArg);
389 continue;
390 }
391
392 // Otherwise, this is some other kind of linker input option like -Wl, -z,
393 // or -L. Render it, even if MSVC doesn't understand it.
394 A.renderAsInput(Args, CmdArgs);
395 }
396
397 TC.addOffloadRTLibs(C.getActiveOffloadKinds(), Args, CmdArgs);
398
399 TC.addProfileRTLibs(Args, CmdArgs);
400
401 std::vector<const char *> Environment;
402
403 // We need to special case some linker paths. In the case of the regular msvc
404 // linker, we need to use a special search algorithm.
405 llvm::SmallString<128> linkPath;
406 if (Linker.equals_insensitive("link")) {
407 // If we're using the MSVC linker, it's not sufficient to just use link
408 // from the program PATH, because other environments like GnuWin32 install
409 // their own link.exe which may come first.
410 linkPath = FindVisualStudioExecutable(TC, "link.exe");
411
412 if (!TC.FoundMSVCInstall() && !canExecute(TC.getVFS(), linkPath)) {
414 ClPath = TC.GetProgramPath("cl.exe");
415 if (canExecute(TC.getVFS(), ClPath)) {
416 linkPath = llvm::sys::path::parent_path(ClPath);
417 llvm::sys::path::append(linkPath, "link.exe");
418 if (!canExecute(TC.getVFS(), linkPath))
419 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
420 } else {
421 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
422 }
423 }
424
425 // Clang handles passing the proper asan libs to the linker, which goes
426 // against link.exe's /INFERASANLIBS which automatically finds asan libs.
427 if (TC.getSanitizerArgs(Args).needsAsanRt())
428 CmdArgs.push_back("/INFERASANLIBS:NO");
429
430#ifdef _WIN32
431 // When cross-compiling with VS2017 or newer, link.exe expects to have
432 // its containing bin directory at the top of PATH, followed by the
433 // native target bin directory.
434 // e.g. when compiling for x86 on an x64 host, PATH should start with:
435 // /bin/Hostx64/x86;/bin/Hostx64/x64
436 // This doesn't attempt to handle llvm::ToolsetLayout::DevDivInternal.
437 if (TC.getIsVS2017OrNewer() &&
438 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
439 auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
440
441 auto EnvBlockWide =
442 std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
443 GetEnvironmentStringsW(), FreeEnvironmentStringsW);
444 if (!EnvBlockWide)
445 goto SkipSettingEnvironment;
446
447 size_t EnvCount = 0;
448 size_t EnvBlockLen = 0;
449 while (EnvBlockWide[EnvBlockLen] != L'\0') {
450 ++EnvCount;
451 EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
452 1 /*string null-terminator*/;
453 }
454 ++EnvBlockLen; // add the block null-terminator
455
456 std::string EnvBlock;
457 if (!llvm::convertUTF16ToUTF8String(
458 llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
459 EnvBlockLen * sizeof(EnvBlockWide[0])),
460 EnvBlock))
461 goto SkipSettingEnvironment;
462
463 Environment.reserve(EnvCount);
464
465 // Now loop over each string in the block and copy them into the
466 // environment vector, adjusting the PATH variable as needed when we
467 // find it.
468 for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
469 llvm::StringRef EnvVar(Cursor);
470 if (EnvVar.starts_with_insensitive("path=")) {
471 constexpr size_t PrefixLen = 5; // strlen("path=")
472 Environment.push_back(Args.MakeArgString(
473 EnvVar.substr(0, PrefixLen) +
474 TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin) +
475 llvm::Twine(llvm::sys::EnvPathSeparator) +
476 TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin, HostArch) +
477 (EnvVar.size() > PrefixLen
478 ? llvm::Twine(llvm::sys::EnvPathSeparator) +
479 EnvVar.substr(PrefixLen)
480 : "")));
481 } else {
482 Environment.push_back(Args.MakeArgString(EnvVar));
483 }
484 Cursor += EnvVar.size() + 1 /*null-terminator*/;
485 }
486 }
487 SkipSettingEnvironment:;
488#endif
489 } else {
490 linkPath = TC.GetProgramPath(Linker.str().c_str());
491 }
492
493 auto LinkCmd = std::make_unique<Command>(
495 Args.MakeArgString(linkPath), CmdArgs, Inputs, Output);
496 if (!Environment.empty())
497 LinkCmd->setEnvironment(Environment);
498 C.addCommand(std::move(LinkCmd));
499}
500
501MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
502 const ArgList &Args)
503 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
504 RocmInstallation(D, Triple, Args), SYCLInstallation(D, Triple, Args) {
505 getProgramPaths().push_back(getDriver().Dir);
506
507 std::optional<llvm::StringRef> VCToolsDir, VCToolsVersion;
508 if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsdir))
509 VCToolsDir = A->getValue();
510 if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsversion))
511 VCToolsVersion = A->getValue();
512 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkdir))
513 WinSdkDir = A->getValue();
514 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkversion))
515 WinSdkVersion = A->getValue();
516 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsysroot))
517 WinSysRoot = A->getValue();
518
519 // Check the command line first, that's the user explicitly telling us what to
520 // use. Check the environment next, in case we're being invoked from a VS
521 // command prompt. Failing that, just try to find the newest Visual Studio
522 // version we can and use its default VC toolchain.
523 llvm::findVCToolChainViaCommandLine(getVFS(), VCToolsDir, VCToolsVersion,
524 WinSysRoot, VCToolChainPath, VSLayout) ||
525 llvm::findVCToolChainViaEnvironment(getVFS(), VCToolChainPath,
526 VSLayout) ||
527 llvm::findVCToolChainViaSetupConfig(getVFS(), VCToolsVersion,
528 VCToolChainPath, VSLayout) ||
529 llvm::findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
530
531 loadMultilibsFromYAML(Args, D);
532}
533
535 return new tools::visualstudio::Linker(*this);
536}
537
539 if (getTriple().isOSBinFormatMachO())
540 return new tools::darwin::Assembler(*this);
541 getDriver().Diag(clang::diag::err_no_external_assembler);
542 return nullptr;
543}
544
547 // Don't emit unwind tables by default for MachO targets.
548 if (getTriple().isOSBinFormatMachO())
550
551 // All non-x86_32 Windows targets require unwind tables. However, LLVM
552 // doesn't know how to generate them for all targets, so only enable
553 // the ones that are actually implemented.
554 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
555 getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
557
559}
560
562 return getArch() == llvm::Triple::x86_64 ||
563 getArch() == llvm::Triple::aarch64;
564}
565
566bool MSVCToolChain::isPIEDefault(const llvm::opt::ArgList &Args) const {
567 return false;
568}
569
571 return getArch() == llvm::Triple::x86_64 ||
572 getArch() == llvm::Triple::aarch64;
573}
574
575void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
576 ArgStringList &CC1Args) const {
577 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
578}
579
580void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
581 ArgStringList &CC1Args) const {
582 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
583}
584
585void MSVCToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
586 ArgStringList &CC1Args) const {
587 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
588}
589
590void MSVCToolChain::addOffloadRTLibs(unsigned ActiveKinds, const ArgList &Args,
591 ArgStringList &CmdArgs) const {
592 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
593 true) ||
594 Args.hasArg(options::OPT_no_hip_rt) || Args.hasArg(options::OPT_r))
595 return;
596
597 if (ActiveKinds & Action::OFK_HIP) {
598 CmdArgs.append({Args.MakeArgString(StringRef("-libpath:") +
599 RocmInstallation->getLibPath()),
600 "amdhip64.lib"});
601
602 // For HIP device PGO, link clang_rt.profile_rocm when available. It is a
603 // self-contained superset of clang_rt.profile, emitted first so the base
604 // archive stays inert (avoiding a /MD-vs-/MT CRT mix in the host image).
605 if (needsProfileRT(Args) &&
606 getVFS().exists(getCompilerRT(Args, "profile_rocm", FT_Static)))
607 CmdArgs.push_back(getCompilerRTArgString(Args, "profile_rocm"));
608 }
609}
610
611void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
612 CudaInstallation->print(OS);
613 RocmInstallation->print(OS);
614}
615
616std::string
618 llvm::StringRef SubdirParent) const {
619 return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, getArch(),
620 SubdirParent);
621}
622
623std::string
625 llvm::Triple::ArchType TargetArch) const {
626 return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, TargetArch,
627 "");
628}
629
630// Find the most recent version of Universal CRT or Windows 10 SDK.
631// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
632// directory by name and uses the last one of the list.
633// So we compare entry names lexicographically to find the greatest one.
634// Gets the library path required to link against the Windows SDK.
636 std::string &path) const {
637 std::string sdkPath;
638 int sdkMajor = 0;
639 std::string windowsSDKIncludeVersion;
640 std::string windowsSDKLibVersion;
641
642 path.clear();
643 if (!llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
644 sdkPath, sdkMajor, windowsSDKIncludeVersion,
645 windowsSDKLibVersion))
646 return false;
647
648 llvm::SmallString<128> libPath(sdkPath);
649 llvm::sys::path::append(libPath, "Lib");
650 if (sdkMajor >= 10)
651 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
652 WinSdkVersion.has_value())
653 windowsSDKLibVersion = *WinSdkVersion;
654 if (sdkMajor >= 8)
655 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um");
656 return llvm::appendArchToWindowsSDKLibPath(sdkMajor, libPath, getArch(),
657 path);
658}
659
661 return llvm::useUniversalCRT(VSLayout, VCToolChainPath, getArch(), getVFS());
662}
663
665 std::string &Path) const {
666 std::string UniversalCRTSdkPath;
667 std::string UCRTVersion;
668
669 Path.clear();
670 if (!llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
671 WinSysRoot, UniversalCRTSdkPath,
672 UCRTVersion))
673 return false;
674
675 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
676 WinSdkVersion.has_value())
677 UCRTVersion = *WinSdkVersion;
678
679 StringRef ArchName = llvm::archToWindowsSDKArch(getArch());
680 if (ArchName.empty())
681 return false;
682
683 llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
684 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
685
686 Path = std::string(LibPath);
687 return true;
688}
689
690static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
691 VersionTuple Version;
692#ifdef _WIN32
693 SmallString<128> ClExe(BinDir);
694 llvm::sys::path::append(ClExe, "cl.exe");
695
696 std::wstring ClExeWide;
697 if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
698 return Version;
699
700 const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
701 nullptr);
702 if (VersionSize == 0)
703 return Version;
704
705 SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
706 if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
707 VersionBlock.data()))
708 return Version;
709
710 VS_FIXEDFILEINFO *FileInfo = nullptr;
711 UINT FileInfoSize = 0;
712 if (!::VerQueryValueW(VersionBlock.data(), L"\\",
713 reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
714 FileInfoSize < sizeof(*FileInfo))
715 return Version;
716
717 const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
718 const unsigned Minor = (FileInfo->dwFileVersionMS ) & 0xFFFF;
719 const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
720
721 Version = VersionTuple(Major, Minor, Micro);
722#endif
723 return Version;
724}
725
727 const ArgList &DriverArgs, ArgStringList &CC1Args,
728 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
729 const Twine &subfolder3) const {
730 llvm::SmallString<128> path(folder);
731 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
732 addSystemInclude(DriverArgs, CC1Args, path);
733}
734
735void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
736 ArgStringList &CC1Args) const {
737 if (DriverArgs.hasArg(options::OPT_nostdinc))
738 return;
739
740 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
741 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
742 "include");
743 }
744
745 // Add %INCLUDE%-like directories from the -imsvc flag.
746 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
747 addSystemInclude(DriverArgs, CC1Args, Path);
748
749 auto AddSystemIncludesFromEnv = [&](StringRef Var) -> bool {
750 if (auto Val = llvm::sys::Process::GetEnv(Var)) {
752 StringRef(*Val).split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
753 if (!Dirs.empty()) {
754 addSystemIncludes(DriverArgs, CC1Args, Dirs);
755 return true;
756 }
757 }
758 return false;
759 };
760
761 // Add %INCLUDE%-like dirs via /external:env: flags.
762 for (const auto &Var :
763 DriverArgs.getAllArgValues(options::OPT__SLASH_external_env)) {
764 AddSystemIncludesFromEnv(Var);
765 }
766
767 // Add DIA SDK include if requested.
768 if (const Arg *A = DriverArgs.getLastArg(options::OPT__SLASH_diasdkdir,
769 options::OPT__SLASH_winsysroot)) {
770 // cl.exe doesn't find the DIA SDK automatically, so this too requires
771 // explicit flags and doesn't automatically look in "DIA SDK" relative
772 // to the path we found for VCToolChainPath.
773 llvm::SmallString<128> DIASDKPath(A->getValue());
774 if (A->getOption().getID() == options::OPT__SLASH_winsysroot)
775 llvm::sys::path::append(DIASDKPath, "DIA SDK");
776 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, std::string(DIASDKPath),
777 "include");
778 }
779
780 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
781 return;
782
783 // Add multilib variant include paths in priority order.
784 for (const Multilib &M : getOrderedMultilibs()) {
785 if (M.isDefault())
786 continue;
787 if (std::optional<std::string> StdlibIncDir = getStdlibIncludePath()) {
788 SmallString<128> Dir(*StdlibIncDir);
789 llvm::sys::path::append(Dir, M.includeSuffix());
790 if (getDriver().getVFS().exists(Dir))
791 addSystemInclude(DriverArgs, CC1Args, Dir);
792 }
793 }
794
795 // Honor %INCLUDE% and %EXTERNAL_INCLUDE%. It should have essential search
796 // paths set by vcvarsall.bat. Skip if the user expressly set any of the
797 // Windows SDK or VC Tools options.
798 if (!DriverArgs.hasArg(
799 options::OPT__SLASH_vctoolsdir, options::OPT__SLASH_vctoolsversion,
800 options::OPT__SLASH_winsysroot, options::OPT__SLASH_winsdkdir,
801 options::OPT__SLASH_winsdkversion)) {
802 bool Found = AddSystemIncludesFromEnv("INCLUDE");
803 Found |= AddSystemIncludesFromEnv("EXTERNAL_INCLUDE");
804 if (Found)
805 return;
806 }
807
808 // When built with access to the proper Windows APIs, try to actually find
809 // the correct include paths first.
810 if (!VCToolChainPath.empty()) {
811 addSystemInclude(DriverArgs, CC1Args,
812 getSubDirectoryPath(llvm::SubDirectoryType::Include));
814 DriverArgs, CC1Args,
815 getSubDirectoryPath(llvm::SubDirectoryType::Include, "atlmfc"));
816
817 if (useUniversalCRT()) {
818 std::string UniversalCRTSdkPath;
819 std::string UCRTVersion;
820 if (llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
821 WinSysRoot, UniversalCRTSdkPath,
822 UCRTVersion)) {
823 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
824 WinSdkVersion.has_value())
825 UCRTVersion = *WinSdkVersion;
826 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
827 "Include", UCRTVersion, "ucrt");
828 }
829 }
830
831 std::string WindowsSDKDir;
832 int major = 0;
833 std::string windowsSDKIncludeVersion;
834 std::string windowsSDKLibVersion;
835 if (llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
836 WindowsSDKDir, major, windowsSDKIncludeVersion,
837 windowsSDKLibVersion)) {
838 if (major >= 10)
839 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
840 WinSdkVersion.has_value())
841 windowsSDKIncludeVersion = windowsSDKLibVersion = *WinSdkVersion;
842 if (major >= 8) {
843 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
844 // Anyway, llvm::sys::path::append is able to manage it.
845 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
846 "Include", windowsSDKIncludeVersion,
847 "shared");
848 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
849 "Include", windowsSDKIncludeVersion,
850 "um");
851 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
852 "Include", windowsSDKIncludeVersion,
853 "winrt");
854 if (major >= 10) {
855 llvm::VersionTuple Tuple;
856 if (!Tuple.tryParse(windowsSDKIncludeVersion) &&
857 Tuple.getSubminor().value_or(0) >= 17134) {
858 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
859 "Include", windowsSDKIncludeVersion,
860 "cppwinrt");
861 }
862 }
863 } else {
864 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
865 "Include");
866 }
867 }
868
869 return;
870 }
871
872#if defined(_WIN32)
873 // As a fallback, select default install paths.
874 // FIXME: Don't guess drives and paths like this on Windows.
875 const StringRef Paths[] = {
876 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
877 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
878 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
879 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
880 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
881 };
882 addSystemIncludes(DriverArgs, CC1Args, Paths);
883#endif
884}
885
886void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
887 ArgStringList &CC1Args) const {
888 // FIXME: There should probably be logic here to find libc++ on Windows.
889}
890
892 const ArgList &Args) const {
893 bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
894 VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
895 if (MSVT.empty())
896 MSVT = getTriple().getEnvironmentVersion();
897 if (MSVT.empty() && IsWindowsMSVC)
898 MSVT =
899 getMSVCVersionFromExe(getSubDirectoryPath(llvm::SubDirectoryType::Bin));
900 if (MSVT.empty() &&
901 Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
902 IsWindowsMSVC)) {
903 // -fms-compatibility-version=19.33 is default, aka 2022, 17.3
904 // NOTE: when changing this value, also update
905 // clang/docs/CommandGuide/clang.rst and clang/docs/UsersManual.rst
906 // accordingly.
907 MSVT = VersionTuple(19, 33);
908 }
909 return MSVT;
910}
911
913 const ArgList &Args, llvm::StringRef BoundArch, types::ID InputType) const {
914 // The MSVC version doesn't care about the architecture, even though it
915 // may look at the triple internally.
916 VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
917 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().value_or(0),
918 MSVT.getSubminor().value_or(0));
919
920 // For the rest of the triple, however, a computed architecture name may
921 // be needed.
922 llvm::Triple Triple(
923 ToolChain::ComputeEffectiveClangTriple(Args, BoundArch, InputType));
924 if (Triple.getEnvironment() == llvm::Triple::MSVC) {
925 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
926 if (ObjFmt.empty())
927 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
928 else
929 Triple.setEnvironmentName(
930 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
931 }
932 return Triple.getTriple();
933}
934
936 StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const {
937 SanitizerMask Res =
938 ToolChain::getSupportedSanitizers(BoundArch, DeviceOffloadKind);
939 Res |= SanitizerKind::Address;
940 Res |= SanitizerKind::PointerCompare;
941 Res |= SanitizerKind::PointerSubtract;
942 Res |= SanitizerKind::Fuzzer;
943 Res |= SanitizerKind::FuzzerNoLink;
944 Res &= ~SanitizerKind::CFIMFCall;
945 return Res;
946}
947
948static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
949 bool SupportsForcingFramePointer,
950 const char *ExpandChar, const OptTable &Opts) {
951 assert(A->getOption().matches(options::OPT__SLASH_O));
952
953 StringRef OptStr = A->getValue();
954 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
955 const char &OptChar = *(OptStr.data() + I);
956 switch (OptChar) {
957 default:
958 break;
959 case '1':
960 case '2':
961 case 'x':
962 case 'd':
963 // Ignore /O[12xd] flags that aren't the last one on the command line.
964 // Only the last one gets expanded.
965 if (&OptChar != ExpandChar) {
966 A->claim();
967 break;
968 }
969 if (OptChar == 'd') {
970 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
971 } else {
972 if (OptChar == '1') {
973 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
974 } else if (OptChar == '2' || OptChar == 'x') {
975 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
976 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
977 }
978 if (SupportsForcingFramePointer &&
979 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
980 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
981 if (OptChar == '1' || OptChar == '2')
982 DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
983 }
984 break;
985 case 'b':
986 if (I + 1 != E && isdigit(OptStr[I + 1])) {
987 switch (OptStr[I + 1]) {
988 case '0':
989 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
990 break;
991 case '1':
992 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
993 break;
994 case '2':
995 case '3':
996 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
997 break;
998 }
999 ++I;
1000 }
1001 break;
1002 case 'g':
1003 A->claim();
1004 break;
1005 case 'i':
1006 if (I + 1 != E && OptStr[I + 1] == '-') {
1007 ++I;
1008 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
1009 } else {
1010 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1011 }
1012 break;
1013 case 's':
1014 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1015 break;
1016 case 't':
1017 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
1018 break;
1019 case 'y': {
1020 bool OmitFramePointer = true;
1021 if (I + 1 != E && OptStr[I + 1] == '-') {
1022 OmitFramePointer = false;
1023 ++I;
1024 }
1025 if (SupportsForcingFramePointer) {
1026 if (OmitFramePointer)
1027 DAL.AddFlagArg(A,
1028 Opts.getOption(options::OPT_fomit_frame_pointer));
1029 else
1030 DAL.AddFlagArg(
1031 A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
1032 } else {
1033 // Don't warn about /Oy- in x86-64 builds (where
1034 // SupportsForcingFramePointer is false). The flag having no effect
1035 // there is a compiler-internal optimization, and people shouldn't have
1036 // to special-case their build files for x86-64 clang-cl.
1037 A->claim();
1038 }
1039 break;
1040 }
1041 }
1042 }
1043}
1044
1045static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1046 const OptTable &Opts) {
1047 assert(A->getOption().matches(options::OPT_D));
1048
1049 StringRef Val = A->getValue();
1050 size_t Hash = Val.find('#');
1051 if (Hash == StringRef::npos || Hash > Val.find('=')) {
1052 DAL.append(A);
1053 return;
1054 }
1055
1056 std::string NewVal = std::string(Val);
1057 NewVal[Hash] = '=';
1058 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
1059}
1060
1061static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL,
1062 const OptTable &Opts) {
1063 DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase_));
1064 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_operator_names));
1065}
1066
1067static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL,
1068 const OptTable &Opts) {
1069 DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase));
1070 DAL.AddFlagArg(A, Opts.getOption(options::OPT_foperator_names));
1071}
1072
1073llvm::opt::DerivedArgList *
1074MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
1075 StringRef BoundArch,
1076 Action::OffloadKind OFK) const {
1077 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1078 const OptTable &Opts = getDriver().getOpts();
1079
1080 // /Oy and /Oy- don't have an effect on X86-64
1081 bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64;
1082
1083 // The -O[12xd] flag actually expands to several flags. We must desugar the
1084 // flags so that options embedded can be negated. For example, the '-O2' flag
1085 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
1086 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
1087 // aspect of '-O2'.
1088 //
1089 // Note that this expansion logic only applies to the *last* of '[12xd]'.
1090
1091 // First step is to search for the character we'd like to expand.
1092 const char *ExpandChar = nullptr;
1093 for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
1094 StringRef OptStr = A->getValue();
1095 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1096 char OptChar = OptStr[I];
1097 char PrevChar = I > 0 ? OptStr[I - 1] : '0';
1098 if (PrevChar == 'b') {
1099 // OptChar does not expand; it's an argument to the previous char.
1100 continue;
1101 }
1102 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
1103 ExpandChar = OptStr.data() + I;
1104 }
1105 }
1106
1107 for (Arg *A : Args) {
1108 if (A->getOption().matches(options::OPT__SLASH_O)) {
1109 // The -O flag actually takes an amalgam of other options. For example,
1110 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
1111 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
1112 } else if (A->getOption().matches(options::OPT_D)) {
1113 // Translate -Dfoo#bar into -Dfoo=bar.
1114 TranslateDArg(A, *DAL, Opts);
1115 } else if (A->getOption().matches(options::OPT__SLASH_permissive)) {
1116 // Expand /permissive
1117 TranslatePermissive(A, *DAL, Opts);
1118 } else if (A->getOption().matches(options::OPT__SLASH_permissive_)) {
1119 // Expand /permissive-
1120 TranslatePermissiveMinus(A, *DAL, Opts);
1121 } else if (OFK != Action::OFK_HIP) {
1122 // HIP Toolchain translates input args by itself.
1123 DAL->append(A);
1124 }
1125 }
1126
1127 return DAL;
1128}
1129
1131 const ArgList &DriverArgs, ArgStringList &CC1Args,
1132 Action::OffloadKind DeviceOffloadKind) const {
1133 // MSVC STL kindly allows removing all usages of typeid by defining
1134 // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
1135 if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
1136 /*Default=*/false))
1137 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
1138
1139 if (Arg *A = DriverArgs.getLastArgNoClaim(options::OPT_marm64x))
1140 A->ignoreTargetSpecific();
1141}
#define V(N, I)
static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL, const OptTable &Opts)
Definition MSVC.cpp:1067
static VersionTuple getMSVCVersionFromExe(const std::string &BinDir)
Definition MSVC.cpp:690
static bool canExecute(llvm::vfs::FileSystem &VFS, StringRef Path)
Definition MSVC.cpp:43
static std::string FindVisualStudioExecutable(const ToolChain &TC, const char *Exe)
Definition MSVC.cpp:54
static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL, const OptTable &Opts)
Definition MSVC.cpp:1045
static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL, bool SupportsForcingFramePointer, const char *ExpandChar, const OptTable &Opts)
Definition MSVC.cpp:948
static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL, const OptTable &Opts)
Definition MSVC.cpp:1061
The base class of the type hierarchy.
Definition TypeBase.h:1875
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:94
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:406
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:154
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:144
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition Driver.h:140
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition Driver.h:149
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
bool isNothing() const
Definition InputInfo.h:74
bool isFilename() const
Definition InputInfo.h:75
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag.
Definition Multilib.h:35
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:95
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:301
const Driver & getDriver() const
Definition ToolChain.h:285
llvm::vfs::FileSystem & getVFS() const
bool loadMultilibsFromYAML(const llvm::opt::ArgList &Args, const Driver &D, StringRef Fallback={})
Discover and load a multilib.yaml configuration.
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition ToolChain.cpp:91
path_list & getProgramPaths()
Definition ToolChain.h:328
virtual SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
const llvm::Triple & getTriple() const
Definition ToolChain.h:287
OrderedMultilibs getOrderedMultilibs() const
Get selected multilibs in priority order with default fallback.
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system include directories to CC1.
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
std::optional< std::string > getStdlibIncludePath() const
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, StringRef BoundArch={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
Tool - Information on a specific compilation tool.
Definition Tool.h:32
const ToolChain & getToolChain() const
Definition Tool.h:52
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition MSVC.cpp:575
Tool * buildLinker() const override
Definition MSVC.cpp:534
bool getUniversalCRTLibraryPath(const llvm::opt::ArgList &Args, std::string &path) const
Definition MSVC.cpp:664
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition MSVC.cpp:546
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition MSVC.cpp:1074
void addOffloadRTLibs(unsigned ActiveKinds, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add the system specific libraries for the active offload kinds.
Definition MSVC.cpp:590
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition MSVC.cpp:561
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition MSVC.cpp:570
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition MSVC.cpp:891
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition MSVC.cpp:735
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 MSVC.cpp:886
MSVCToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition MSVC.cpp:501
std::string getSubDirectoryPath(llvm::SubDirectoryType Type, llvm::StringRef SubdirParent="") const
Definition MSVC.cpp:617
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition MSVC.cpp:611
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, llvm::StringRef BoundArch, types::ID InputType) const override
Definition MSVC.cpp:912
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition MSVC.cpp:566
void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific SYCL includes.
Definition MSVC.cpp:585
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 MSVC.cpp:1130
SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
Return sanitizers which are available in this toolchain.
Definition MSVC.cpp:935
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition MSVC.cpp:580
Tool * buildAssembler() const override
Definition MSVC.cpp:538
bool getWindowsSDKLibraryPath(const llvm::opt::ArgList &Args, std::string &path) const
Definition MSVC.cpp:635
void AddSystemIncludeWithSubfolder(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const std::string &folder, const Twine &subfolder1, const Twine &subfolder2="", const Twine &subfolder3="") const
Definition MSVC.cpp:726
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 MSVC.cpp:63
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
The JSON file list parser is used to communicate input to InstallAPI.
static constexpr ResponseFileSupport AtFileUTF16()
Definition Job.h:99