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