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 "CommonArgs.h"
11 #include "Darwin.h"
12 #include "clang/Basic/CharInfo.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/SanitizerArgs.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Option/Arg.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Support/ConvertUTF.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Process.h"
30 #include <cstdio>
31 
32 #ifdef _WIN32
33   #define WIN32_LEAN_AND_MEAN
34   #define NOGDI
35   #ifndef NOMINMAX
36     #define NOMINMAX
37   #endif
38   #include <windows.h>
39 #endif
40 
41 #ifdef _MSC_VER
42 // Don't support SetupApi on MinGW.
43 #define USE_MSVC_SETUP_API
44 
45 // Make sure this comes before MSVCSetupApi.h
46 #include <comdef.h>
47 
48 #include "MSVCSetupApi.h"
49 #include "llvm/Support/COM.h"
50 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration, __uuidof(ISetupConfiguration));
51 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration2, __uuidof(ISetupConfiguration2));
52 _COM_SMARTPTR_TYPEDEF(ISetupHelper, __uuidof(ISetupHelper));
53 _COM_SMARTPTR_TYPEDEF(IEnumSetupInstances, __uuidof(IEnumSetupInstances));
54 _COM_SMARTPTR_TYPEDEF(ISetupInstance, __uuidof(ISetupInstance));
55 _COM_SMARTPTR_TYPEDEF(ISetupInstance2, __uuidof(ISetupInstance2));
56 #endif
57 
58 using namespace clang::driver;
59 using namespace clang::driver::toolchains;
60 using namespace clang::driver::tools;
61 using namespace clang;
62 using namespace llvm::opt;
63 
64 // Defined below.
65 // Forward declare this so there aren't too many things above the constructor.
66 static bool getSystemRegistryString(const char *keyPath, const char *valueName,
67                                     std::string &value, std::string *phValue);
68 
69 // Check various environment variables to try and find a toolchain.
70 static bool findVCToolChainViaEnvironment(std::string &Path,
71                                           MSVCToolChain::ToolsetLayout &VSLayout) {
72   // These variables are typically set by vcvarsall.bat
73   // when launching a developer command prompt.
74   if (llvm::Optional<std::string> VCToolsInstallDir =
75           llvm::sys::Process::GetEnv("VCToolsInstallDir")) {
76     // This is only set by newer Visual Studios, and it leads straight to
77     // the toolchain directory.
78     Path = std::move(*VCToolsInstallDir);
79     VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
80     return true;
81   }
82   if (llvm::Optional<std::string> VCInstallDir =
83           llvm::sys::Process::GetEnv("VCINSTALLDIR")) {
84     // If the previous variable isn't set but this one is, then we've found
85     // an older Visual Studio. This variable is set by newer Visual Studios too,
86     // so this check has to appear second.
87     // In older Visual Studios, the VC directory is the toolchain.
88     Path = std::move(*VCInstallDir);
89     VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
90     return true;
91   }
92 
93   // We couldn't find any VC environment variables. Let's walk through PATH and
94   // see if it leads us to a VC toolchain bin directory. If it does, pick the
95   // first one that we find.
96   if (llvm::Optional<std::string> PathEnv =
97           llvm::sys::Process::GetEnv("PATH")) {
98     llvm::SmallVector<llvm::StringRef, 8> PathEntries;
99     llvm::StringRef(*PathEnv).split(PathEntries, llvm::sys::EnvPathSeparator);
100     for (llvm::StringRef PathEntry : PathEntries) {
101       if (PathEntry.empty())
102         continue;
103 
104       llvm::SmallString<256> ExeTestPath;
105 
106       // If cl.exe doesn't exist, then this definitely isn't a VC toolchain.
107       ExeTestPath = PathEntry;
108       llvm::sys::path::append(ExeTestPath, "cl.exe");
109       if (!llvm::sys::fs::exists(ExeTestPath))
110         continue;
111 
112       // cl.exe existing isn't a conclusive test for a VC toolchain; clang also
113       // has a cl.exe. So let's check for link.exe too.
114       ExeTestPath = PathEntry;
115       llvm::sys::path::append(ExeTestPath, "link.exe");
116       if (!llvm::sys::fs::exists(ExeTestPath))
117         continue;
118 
119       // whatever/VC/bin --> old toolchain, VC dir is toolchain dir.
120       llvm::StringRef TestPath = PathEntry;
121       bool IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin");
122       if (!IsBin) {
123         // Strip any architecture subdir like "amd64".
124         TestPath = llvm::sys::path::parent_path(TestPath);
125         IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin");
126       }
127       if (IsBin) {
128         llvm::StringRef ParentPath = llvm::sys::path::parent_path(TestPath);
129         llvm::StringRef ParentFilename = llvm::sys::path::filename(ParentPath);
130         if (ParentFilename == "VC") {
131           Path = std::string(ParentPath);
132           VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
133           return true;
134         }
135         if (ParentFilename == "x86ret" || ParentFilename == "x86chk"
136           || ParentFilename == "amd64ret" || ParentFilename == "amd64chk") {
137           Path = std::string(ParentPath);
138           VSLayout = MSVCToolChain::ToolsetLayout::DevDivInternal;
139           return true;
140         }
141 
142       } else {
143         // This could be a new (>=VS2017) toolchain. If it is, we should find
144         // path components with these prefixes when walking backwards through
145         // the path.
146         // Note: empty strings match anything.
147         llvm::StringRef ExpectedPrefixes[] = {"",     "Host",  "bin", "",
148                                               "MSVC", "Tools", "VC"};
149 
150         auto It = llvm::sys::path::rbegin(PathEntry);
151         auto End = llvm::sys::path::rend(PathEntry);
152         for (llvm::StringRef Prefix : ExpectedPrefixes) {
153           if (It == End)
154             goto NotAToolChain;
155           if (!It->startswith(Prefix))
156             goto NotAToolChain;
157           ++It;
158         }
159 
160         // We've found a new toolchain!
161         // Back up 3 times (/bin/Host/arch) to get the root path.
162         llvm::StringRef ToolChainPath(PathEntry);
163         for (int i = 0; i < 3; ++i)
164           ToolChainPath = llvm::sys::path::parent_path(ToolChainPath);
165 
166         Path = std::string(ToolChainPath);
167         VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
168         return true;
169       }
170 
171     NotAToolChain:
172       continue;
173     }
174   }
175   return false;
176 }
177 
178 // Query the Setup Config server for installs, then pick the newest version
179 // and find its default VC toolchain.
180 // This is the preferred way to discover new Visual Studios, as they're no
181 // longer listed in the registry.
182 static bool findVCToolChainViaSetupConfig(std::string &Path,
183                                           MSVCToolChain::ToolsetLayout &VSLayout) {
184 #if !defined(USE_MSVC_SETUP_API)
185   return false;
186 #else
187   // FIXME: This really should be done once in the top-level program's main
188   // function, as it may have already been initialized with a different
189   // threading model otherwise.
190   llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::SingleThreaded);
191   HRESULT HR;
192 
193   // _com_ptr_t will throw a _com_error if a COM calls fail.
194   // The LLVM coding standards forbid exception handling, so we'll have to
195   // stop them from being thrown in the first place.
196   // The destructor will put the regular error handler back when we leave
197   // this scope.
198   struct SuppressCOMErrorsRAII {
199     static void __stdcall handler(HRESULT hr, IErrorInfo *perrinfo) {}
200 
201     SuppressCOMErrorsRAII() { _set_com_error_handler(handler); }
202 
203     ~SuppressCOMErrorsRAII() { _set_com_error_handler(_com_raise_error); }
204 
205   } COMErrorSuppressor;
206 
207   ISetupConfigurationPtr Query;
208   HR = Query.CreateInstance(__uuidof(SetupConfiguration));
209   if (FAILED(HR))
210     return false;
211 
212   IEnumSetupInstancesPtr EnumInstances;
213   HR = ISetupConfiguration2Ptr(Query)->EnumAllInstances(&EnumInstances);
214   if (FAILED(HR))
215     return false;
216 
217   ISetupInstancePtr Instance;
218   HR = EnumInstances->Next(1, &Instance, nullptr);
219   if (HR != S_OK)
220     return false;
221 
222   ISetupInstancePtr NewestInstance;
223   Optional<uint64_t> NewestVersionNum;
224   do {
225     bstr_t VersionString;
226     uint64_t VersionNum;
227     HR = Instance->GetInstallationVersion(VersionString.GetAddress());
228     if (FAILED(HR))
229       continue;
230     HR = ISetupHelperPtr(Query)->ParseVersion(VersionString, &VersionNum);
231     if (FAILED(HR))
232       continue;
233     if (!NewestVersionNum || (VersionNum > NewestVersionNum)) {
234       NewestInstance = Instance;
235       NewestVersionNum = VersionNum;
236     }
237   } while ((HR = EnumInstances->Next(1, &Instance, nullptr)) == S_OK);
238 
239   if (!NewestInstance)
240     return false;
241 
242   bstr_t VCPathWide;
243   HR = NewestInstance->ResolvePath(L"VC", VCPathWide.GetAddress());
244   if (FAILED(HR))
245     return false;
246 
247   std::string VCRootPath;
248   llvm::convertWideToUTF8(std::wstring(VCPathWide), VCRootPath);
249 
250   llvm::SmallString<256> ToolsVersionFilePath(VCRootPath);
251   llvm::sys::path::append(ToolsVersionFilePath, "Auxiliary", "Build",
252                           "Microsoft.VCToolsVersion.default.txt");
253 
254   auto ToolsVersionFile = llvm::MemoryBuffer::getFile(ToolsVersionFilePath);
255   if (!ToolsVersionFile)
256     return false;
257 
258   llvm::SmallString<256> ToolchainPath(VCRootPath);
259   llvm::sys::path::append(ToolchainPath, "Tools", "MSVC",
260                           ToolsVersionFile->get()->getBuffer().rtrim());
261   if (!llvm::sys::fs::is_directory(ToolchainPath))
262     return false;
263 
264   Path = std::string(ToolchainPath.str());
265   VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
266   return true;
267 #endif
268 }
269 
270 // Look in the registry for Visual Studio installs, and use that to get
271 // a toolchain path. VS2017 and newer don't get added to the registry.
272 // So if we find something here, we know that it's an older version.
273 static bool findVCToolChainViaRegistry(std::string &Path,
274                                        MSVCToolChain::ToolsetLayout &VSLayout) {
275   std::string VSInstallPath;
276   if (getSystemRegistryString(R"(SOFTWARE\Microsoft\VisualStudio\$VERSION)",
277                               "InstallDir", VSInstallPath, nullptr) ||
278       getSystemRegistryString(R"(SOFTWARE\Microsoft\VCExpress\$VERSION)",
279                               "InstallDir", VSInstallPath, nullptr)) {
280     if (!VSInstallPath.empty()) {
281       llvm::SmallString<256> VCPath(llvm::StringRef(
282           VSInstallPath.c_str(), VSInstallPath.find(R"(\Common7\IDE)")));
283       llvm::sys::path::append(VCPath, "VC");
284 
285       Path = std::string(VCPath.str());
286       VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
287       return true;
288     }
289   }
290   return false;
291 }
292 
293 // Try to find Exe from a Visual Studio distribution.  This first tries to find
294 // an installed copy of Visual Studio and, failing that, looks in the PATH,
295 // making sure that whatever executable that's found is not a same-named exe
296 // from clang itself to prevent clang from falling back to itself.
297 static std::string FindVisualStudioExecutable(const ToolChain &TC,
298                                               const char *Exe) {
299   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
300   SmallString<128> FilePath(MSVC.getSubDirectoryPath(
301       toolchains::MSVCToolChain::SubDirectoryType::Bin));
302   llvm::sys::path::append(FilePath, Exe);
303   return std::string(llvm::sys::fs::can_execute(FilePath) ? FilePath.str()
304                                                           : Exe);
305 }
306 
307 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
308                                         const InputInfo &Output,
309                                         const InputInfoList &Inputs,
310                                         const ArgList &Args,
311                                         const char *LinkingOutput) const {
312   ArgStringList CmdArgs;
313 
314   auto &TC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
315 
316   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
317   if (Output.isFilename())
318     CmdArgs.push_back(
319         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
320 
321   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
322       !C.getDriver().IsCLMode())
323     CmdArgs.push_back("-defaultlib:libcmt");
324 
325   if (!llvm::sys::Process::GetEnv("LIB")) {
326     // If the VC environment hasn't been configured (perhaps because the user
327     // did not run vcvarsall), try to build a consistent link environment.  If
328     // the environment variable is set however, assume the user knows what
329     // they're doing.
330     CmdArgs.push_back(Args.MakeArgString(
331         Twine("-libpath:") +
332         TC.getSubDirectoryPath(
333             toolchains::MSVCToolChain::SubDirectoryType::Lib)));
334 
335     CmdArgs.push_back(Args.MakeArgString(
336         Twine("-libpath:") +
337         TC.getSubDirectoryPath(toolchains::MSVCToolChain::SubDirectoryType::Lib,
338                                "atlmfc")));
339 
340     if (TC.useUniversalCRT()) {
341       std::string UniversalCRTLibPath;
342       if (TC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
343         CmdArgs.push_back(
344             Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath));
345     }
346 
347     std::string WindowsSdkLibPath;
348     if (TC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
349       CmdArgs.push_back(
350           Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
351   }
352 
353   // Add the compiler-rt library directories to libpath if they exist to help
354   // the linker find the various sanitizer, builtin, and profiling runtimes.
355   for (const auto &LibPath : TC.getLibraryPaths()) {
356     if (TC.getVFS().exists(LibPath))
357       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
358   }
359   auto CRTPath = TC.getCompilerRTPath();
360   if (TC.getVFS().exists(CRTPath))
361     CmdArgs.push_back(Args.MakeArgString("-libpath:" + CRTPath));
362 
363   if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
364     for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
365       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
366 
367   CmdArgs.push_back("-nologo");
368 
369   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
370                   options::OPT__SLASH_Zd))
371     CmdArgs.push_back("-debug");
372 
373   // Pass on /Brepro if it was passed to the compiler.
374   // Note that /Brepro maps to -mno-incremental-linker-compatible.
375   bool DefaultIncrementalLinkerCompatible =
376       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
377   if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
378                     options::OPT_mno_incremental_linker_compatible,
379                     DefaultIncrementalLinkerCompatible))
380     CmdArgs.push_back("-Brepro");
381 
382   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
383                          options::OPT_shared);
384   if (DLL) {
385     CmdArgs.push_back(Args.MakeArgString("-dll"));
386 
387     SmallString<128> ImplibName(Output.getFilename());
388     llvm::sys::path::replace_extension(ImplibName, "lib");
389     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
390   }
391 
392   if (TC.getSanitizerArgs().needsFuzzer()) {
393     if (!Args.hasArg(options::OPT_shared))
394       CmdArgs.push_back(
395           Args.MakeArgString(std::string("-wholearchive:") +
396                              TC.getCompilerRTArgString(Args, "fuzzer")));
397     CmdArgs.push_back(Args.MakeArgString("-debug"));
398     // Prevent the linker from padding sections we use for instrumentation
399     // arrays.
400     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
401   }
402 
403   if (TC.getSanitizerArgs().needsAsanRt()) {
404     CmdArgs.push_back(Args.MakeArgString("-debug"));
405     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
406     if (TC.getSanitizerArgs().needsSharedRt() ||
407         Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
408       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
409         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
410       // Make sure the dynamic runtime thunk is not optimized out at link time
411       // to ensure proper SEH handling.
412       CmdArgs.push_back(Args.MakeArgString(
413           TC.getArch() == llvm::Triple::x86
414               ? "-include:___asan_seh_interceptor"
415               : "-include:__asan_seh_interceptor"));
416       // Make sure the linker consider all object files from the dynamic runtime
417       // thunk.
418       CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
419           TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk")));
420     } else if (DLL) {
421       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
422     } else {
423       for (const auto &Lib : {"asan", "asan_cxx"}) {
424         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
425         // Make sure the linker consider all object files from the static lib.
426         // This is necessary because instrumented dlls need access to all the
427         // interface exported by the static lib in the main executable.
428         CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
429             TC.getCompilerRT(Args, Lib)));
430       }
431     }
432   }
433 
434   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
435 
436   // Control Flow Guard checks
437   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
438     StringRef GuardArgs = A->getValue();
439     if (GuardArgs.equals_lower("cf") || GuardArgs.equals_lower("cf,nochecks")) {
440       // MSVC doesn't yet support the "nochecks" modifier.
441       CmdArgs.push_back("-guard:cf");
442     } else if (GuardArgs.equals_lower("cf-")) {
443       CmdArgs.push_back("-guard:cf-");
444     }
445   }
446 
447   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
448                    options::OPT_fno_openmp, false)) {
449     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
450     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
451     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
452                                          TC.getDriver().Dir + "/../lib"));
453     switch (TC.getDriver().getOpenMPRuntime(Args)) {
454     case Driver::OMPRT_OMP:
455       CmdArgs.push_back("-defaultlib:libomp.lib");
456       break;
457     case Driver::OMPRT_IOMP5:
458       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
459       break;
460     case Driver::OMPRT_GOMP:
461       break;
462     case Driver::OMPRT_Unknown:
463       // Already diagnosed.
464       break;
465     }
466   }
467 
468   // Add compiler-rt lib in case if it was explicitly
469   // specified as an argument for --rtlib option.
470   if (!Args.hasArg(options::OPT_nostdlib)) {
471     AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
472   }
473 
474   // Add filenames, libraries, and other linker inputs.
475   for (const auto &Input : Inputs) {
476     if (Input.isFilename()) {
477       CmdArgs.push_back(Input.getFilename());
478       continue;
479     }
480 
481     const Arg &A = Input.getInputArg();
482 
483     // Render -l options differently for the MSVC linker.
484     if (A.getOption().matches(options::OPT_l)) {
485       StringRef Lib = A.getValue();
486       const char *LinkLibArg;
487       if (Lib.endswith(".lib"))
488         LinkLibArg = Args.MakeArgString(Lib);
489       else
490         LinkLibArg = Args.MakeArgString(Lib + ".lib");
491       CmdArgs.push_back(LinkLibArg);
492       continue;
493     }
494 
495     // Otherwise, this is some other kind of linker input option like -Wl, -z,
496     // or -L. Render it, even if MSVC doesn't understand it.
497     A.renderAsInput(Args, CmdArgs);
498   }
499 
500   TC.addProfileRTLibs(Args, CmdArgs);
501 
502   std::vector<const char *> Environment;
503 
504   // We need to special case some linker paths.  In the case of lld, we need to
505   // translate 'lld' into 'lld-link', and in the case of the regular msvc
506   // linker, we need to use a special search algorithm.
507   llvm::SmallString<128> linkPath;
508   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
509   if (Linker.equals_lower("lld"))
510     Linker = "lld-link";
511 
512   if (Linker.equals_lower("link")) {
513     // If we're using the MSVC linker, it's not sufficient to just use link
514     // from the program PATH, because other environments like GnuWin32 install
515     // their own link.exe which may come first.
516     linkPath = FindVisualStudioExecutable(TC, "link.exe");
517 
518     if (!TC.FoundMSVCInstall() && !llvm::sys::fs::can_execute(linkPath)) {
519       llvm::SmallString<128> ClPath;
520       ClPath = TC.GetProgramPath("cl.exe");
521       if (llvm::sys::fs::can_execute(ClPath)) {
522         linkPath = llvm::sys::path::parent_path(ClPath);
523         llvm::sys::path::append(linkPath, "link.exe");
524         if (!llvm::sys::fs::can_execute(linkPath))
525           C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
526       } else {
527         C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
528       }
529     }
530 
531 #ifdef _WIN32
532     // When cross-compiling with VS2017 or newer, link.exe expects to have
533     // its containing bin directory at the top of PATH, followed by the
534     // native target bin directory.
535     // e.g. when compiling for x86 on an x64 host, PATH should start with:
536     // /bin/Hostx64/x86;/bin/Hostx64/x64
537     // This doesn't attempt to handle ToolsetLayout::DevDivInternal.
538     if (TC.getIsVS2017OrNewer() &&
539         llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
540       auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
541 
542       auto EnvBlockWide =
543           std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
544               GetEnvironmentStringsW(), FreeEnvironmentStringsW);
545       if (!EnvBlockWide)
546         goto SkipSettingEnvironment;
547 
548       size_t EnvCount = 0;
549       size_t EnvBlockLen = 0;
550       while (EnvBlockWide[EnvBlockLen] != L'\0') {
551         ++EnvCount;
552         EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
553                        1 /*string null-terminator*/;
554       }
555       ++EnvBlockLen; // add the block null-terminator
556 
557       std::string EnvBlock;
558       if (!llvm::convertUTF16ToUTF8String(
559               llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
560                                    EnvBlockLen * sizeof(EnvBlockWide[0])),
561               EnvBlock))
562         goto SkipSettingEnvironment;
563 
564       Environment.reserve(EnvCount);
565 
566       // Now loop over each string in the block and copy them into the
567       // environment vector, adjusting the PATH variable as needed when we
568       // find it.
569       for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
570         llvm::StringRef EnvVar(Cursor);
571         if (EnvVar.startswith_lower("path=")) {
572           using SubDirectoryType = toolchains::MSVCToolChain::SubDirectoryType;
573           constexpr size_t PrefixLen = 5; // strlen("path=")
574           Environment.push_back(Args.MakeArgString(
575               EnvVar.substr(0, PrefixLen) +
576               TC.getSubDirectoryPath(SubDirectoryType::Bin) +
577               llvm::Twine(llvm::sys::EnvPathSeparator) +
578               TC.getSubDirectoryPath(SubDirectoryType::Bin, "", HostArch) +
579               (EnvVar.size() > PrefixLen
580                    ? llvm::Twine(llvm::sys::EnvPathSeparator) +
581                          EnvVar.substr(PrefixLen)
582                    : "")));
583         } else {
584           Environment.push_back(Args.MakeArgString(EnvVar));
585         }
586         Cursor += EnvVar.size() + 1 /*null-terminator*/;
587       }
588     }
589   SkipSettingEnvironment:;
590 #endif
591   } else {
592     linkPath = TC.GetProgramPath(Linker.str().c_str());
593   }
594 
595   auto LinkCmd = std::make_unique<Command>(
596       JA, *this, Args.MakeArgString(linkPath), CmdArgs, Inputs);
597   if (!Environment.empty())
598     LinkCmd->setEnvironment(Environment);
599   C.addCommand(std::move(LinkCmd));
600 }
601 
602 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
603                                           const InputInfo &Output,
604                                           const InputInfoList &Inputs,
605                                           const ArgList &Args,
606                                           const char *LinkingOutput) const {
607   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
608 }
609 
610 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
611     Compilation &C, const JobAction &JA, const InputInfo &Output,
612     const InputInfoList &Inputs, const ArgList &Args,
613     const char *LinkingOutput) const {
614   ArgStringList CmdArgs;
615   CmdArgs.push_back("/nologo");
616   CmdArgs.push_back("/c");  // Compile only.
617   CmdArgs.push_back("/W0"); // No warnings.
618 
619   // The goal is to be able to invoke this tool correctly based on
620   // any flag accepted by clang-cl.
621 
622   // These are spelled the same way in clang and cl.exe,.
623   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
624 
625   // Optimization level.
626   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
627     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
628                                                                       : "/Oi-");
629   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
630     if (A->getOption().getID() == options::OPT_O0) {
631       CmdArgs.push_back("/Od");
632     } else {
633       CmdArgs.push_back("/Og");
634 
635       StringRef OptLevel = A->getValue();
636       if (OptLevel == "s" || OptLevel == "z")
637         CmdArgs.push_back("/Os");
638       else
639         CmdArgs.push_back("/Ot");
640 
641       CmdArgs.push_back("/Ob2");
642     }
643   }
644   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
645                                options::OPT_fno_omit_frame_pointer))
646     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
647                           ? "/Oy"
648                           : "/Oy-");
649   if (!Args.hasArg(options::OPT_fwritable_strings))
650     CmdArgs.push_back("/GF");
651 
652   // Flags for which clang-cl has an alias.
653   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
654 
655   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
656                    /*Default=*/false))
657     CmdArgs.push_back("/GR-");
658 
659   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
660                    /*Default=*/false))
661     CmdArgs.push_back("/GS-");
662 
663   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
664                                options::OPT_fno_function_sections))
665     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
666                           ? "/Gy"
667                           : "/Gy-");
668   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
669                                options::OPT_fno_data_sections))
670     CmdArgs.push_back(
671         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
672   if (Args.hasArg(options::OPT_fsyntax_only))
673     CmdArgs.push_back("/Zs");
674   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
675                   options::OPT__SLASH_Z7))
676     CmdArgs.push_back("/Z7");
677 
678   std::vector<std::string> Includes =
679       Args.getAllArgValues(options::OPT_include);
680   for (const auto &Include : Includes)
681     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
682 
683   // Flags that can simply be passed through.
684   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
685   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
686   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
687   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
688   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
689   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
690 
691   // The order of these flags is relevant, so pick the last one.
692   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
693                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
694     A->render(Args, CmdArgs);
695 
696   // Use MSVC's default threadsafe statics behaviour unless there was a flag.
697   if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
698                                options::OPT_fno_threadsafe_statics)) {
699     CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
700                           ? "/Zc:threadSafeInit"
701                           : "/Zc:threadSafeInit-");
702   }
703 
704   // Control Flow Guard checks
705   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
706     StringRef GuardArgs = A->getValue();
707     if (GuardArgs.equals_lower("cf") || GuardArgs.equals_lower("cf,nochecks")) {
708       // MSVC doesn't yet support the "nochecks" modifier.
709       CmdArgs.push_back("/guard:cf");
710     } else if (GuardArgs.equals_lower("cf-")) {
711       CmdArgs.push_back("/guard:cf-");
712     }
713   }
714 
715   // Pass through all unknown arguments so that the fallback command can see
716   // them too.
717   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
718 
719   // Input filename.
720   assert(Inputs.size() == 1);
721   const InputInfo &II = Inputs[0];
722   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
723   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
724   if (II.isFilename())
725     CmdArgs.push_back(II.getFilename());
726   else
727     II.getInputArg().renderAsInput(Args, CmdArgs);
728 
729   // Output filename.
730   assert(Output.getType() == types::TY_Object);
731   const char *Fo =
732       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
733   CmdArgs.push_back(Fo);
734 
735   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe");
736   return std::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
737                                     CmdArgs, Inputs);
738 }
739 
740 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
741                              const ArgList &Args)
742     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
743       RocmInstallation(D, Triple, Args) {
744   getProgramPaths().push_back(getDriver().getInstalledDir());
745   if (getDriver().getInstalledDir() != getDriver().Dir)
746     getProgramPaths().push_back(getDriver().Dir);
747 
748   // Check the environment first, since that's probably the user telling us
749   // what they want to use.
750   // Failing that, just try to find the newest Visual Studio version we can
751   // and use its default VC toolchain.
752   findVCToolChainViaEnvironment(VCToolChainPath, VSLayout) ||
753       findVCToolChainViaSetupConfig(VCToolChainPath, VSLayout) ||
754       findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
755 }
756 
757 Tool *MSVCToolChain::buildLinker() const {
758   return new tools::visualstudio::Linker(*this);
759 }
760 
761 Tool *MSVCToolChain::buildAssembler() const {
762   if (getTriple().isOSBinFormatMachO())
763     return new tools::darwin::Assembler(*this);
764   getDriver().Diag(clang::diag::err_no_external_assembler);
765   return nullptr;
766 }
767 
768 bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
769   return true;
770 }
771 
772 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
773   // Don't emit unwind tables by default for MachO targets.
774   if (getTriple().isOSBinFormatMachO())
775     return false;
776 
777   // All non-x86_32 Windows targets require unwind tables. However, LLVM
778   // doesn't know how to generate them for all targets, so only enable
779   // the ones that are actually implemented.
780   return getArch() == llvm::Triple::x86_64 ||
781          getArch() == llvm::Triple::aarch64;
782 }
783 
784 bool MSVCToolChain::isPICDefault() const {
785   return getArch() == llvm::Triple::x86_64;
786 }
787 
788 bool MSVCToolChain::isPIEDefault() const {
789   return false;
790 }
791 
792 bool MSVCToolChain::isPICDefaultForced() const {
793   return getArch() == llvm::Triple::x86_64;
794 }
795 
796 void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
797                                        ArgStringList &CC1Args) const {
798   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
799 }
800 
801 void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
802                                       ArgStringList &CC1Args) const {
803   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
804 }
805 
806 void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
807   CudaInstallation.print(OS);
808 }
809 
810 // Windows SDKs and VC Toolchains group their contents into subdirectories based
811 // on the target architecture. This function converts an llvm::Triple::ArchType
812 // to the corresponding subdirectory name.
813 static const char *llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch) {
814   using ArchType = llvm::Triple::ArchType;
815   switch (Arch) {
816   case ArchType::x86:
817     return "x86";
818   case ArchType::x86_64:
819     return "x64";
820   case ArchType::arm:
821     return "arm";
822   case ArchType::aarch64:
823     return "arm64";
824   default:
825     return "";
826   }
827 }
828 
829 // Similar to the above function, but for Visual Studios before VS2017.
830 static const char *llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch) {
831   using ArchType = llvm::Triple::ArchType;
832   switch (Arch) {
833   case ArchType::x86:
834     // x86 is default in legacy VC toolchains.
835     // e.g. x86 libs are directly in /lib as opposed to /lib/x86.
836     return "";
837   case ArchType::x86_64:
838     return "amd64";
839   case ArchType::arm:
840     return "arm";
841   case ArchType::aarch64:
842     return "arm64";
843   default:
844     return "";
845   }
846 }
847 
848 // Similar to the above function, but for DevDiv internal builds.
849 static const char *llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch) {
850   using ArchType = llvm::Triple::ArchType;
851   switch (Arch) {
852   case ArchType::x86:
853     return "i386";
854   case ArchType::x86_64:
855     return "amd64";
856   case ArchType::arm:
857     return "arm";
858   case ArchType::aarch64:
859     return "arm64";
860   default:
861     return "";
862   }
863 }
864 
865 // Get the path to a specific subdirectory in the current toolchain for
866 // a given target architecture.
867 // VS2017 changed the VC toolchain layout, so this should be used instead
868 // of hardcoding paths.
869 std::string
870 MSVCToolChain::getSubDirectoryPath(SubDirectoryType Type,
871                                    llvm::StringRef SubdirParent,
872                                    llvm::Triple::ArchType TargetArch) const {
873   const char *SubdirName;
874   const char *IncludeName;
875   switch (VSLayout) {
876   case ToolsetLayout::OlderVS:
877     SubdirName = llvmArchToLegacyVCArch(TargetArch);
878     IncludeName = "include";
879     break;
880   case ToolsetLayout::VS2017OrNewer:
881     SubdirName = llvmArchToWindowsSDKArch(TargetArch);
882     IncludeName = "include";
883     break;
884   case ToolsetLayout::DevDivInternal:
885     SubdirName = llvmArchToDevDivInternalArch(TargetArch);
886     IncludeName = "inc";
887     break;
888   }
889 
890   llvm::SmallString<256> Path(VCToolChainPath);
891   if (!SubdirParent.empty())
892     llvm::sys::path::append(Path, SubdirParent);
893 
894   switch (Type) {
895   case SubDirectoryType::Bin:
896     if (VSLayout == ToolsetLayout::VS2017OrNewer) {
897       const bool HostIsX64 =
898           llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
899       const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
900       llvm::sys::path::append(Path, "bin", HostName, SubdirName);
901     } else { // OlderVS or DevDivInternal
902       llvm::sys::path::append(Path, "bin", SubdirName);
903     }
904     break;
905   case SubDirectoryType::Include:
906     llvm::sys::path::append(Path, IncludeName);
907     break;
908   case SubDirectoryType::Lib:
909     llvm::sys::path::append(Path, "lib", SubdirName);
910     break;
911   }
912   return std::string(Path.str());
913 }
914 
915 #ifdef _WIN32
916 static bool readFullStringValue(HKEY hkey, const char *valueName,
917                                 std::string &value) {
918   std::wstring WideValueName;
919   if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
920     return false;
921 
922   DWORD result = 0;
923   DWORD valueSize = 0;
924   DWORD type = 0;
925   // First just query for the required size.
926   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
927                             &valueSize);
928   if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
929     return false;
930   std::vector<BYTE> buffer(valueSize);
931   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
932                             &valueSize);
933   if (result == ERROR_SUCCESS) {
934     std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
935                            valueSize / sizeof(wchar_t));
936     if (valueSize && WideValue.back() == L'\0') {
937       WideValue.pop_back();
938     }
939     // The destination buffer must be empty as an invariant of the conversion
940     // function; but this function is sometimes called in a loop that passes in
941     // the same buffer, however. Simply clear it out so we can overwrite it.
942     value.clear();
943     return llvm::convertWideToUTF8(WideValue, value);
944   }
945   return false;
946 }
947 #endif
948 
949 /// Read registry string.
950 /// This also supports a means to look for high-versioned keys by use
951 /// of a $VERSION placeholder in the key path.
952 /// $VERSION in the key path is a placeholder for the version number,
953 /// causing the highest value path to be searched for and used.
954 /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
955 /// There can be additional characters in the component.  Only the numeric
956 /// characters are compared.  This function only searches HKLM.
957 static bool getSystemRegistryString(const char *keyPath, const char *valueName,
958                                     std::string &value, std::string *phValue) {
959 #ifndef _WIN32
960   return false;
961 #else
962   HKEY hRootKey = HKEY_LOCAL_MACHINE;
963   HKEY hKey = NULL;
964   long lResult;
965   bool returnValue = false;
966 
967   const char *placeHolder = strstr(keyPath, "$VERSION");
968   std::string bestName;
969   // If we have a $VERSION placeholder, do the highest-version search.
970   if (placeHolder) {
971     const char *keyEnd = placeHolder - 1;
972     const char *nextKey = placeHolder;
973     // Find end of previous key.
974     while ((keyEnd > keyPath) && (*keyEnd != '\\'))
975       keyEnd--;
976     // Find end of key containing $VERSION.
977     while (*nextKey && (*nextKey != '\\'))
978       nextKey++;
979     size_t partialKeyLength = keyEnd - keyPath;
980     char partialKey[256];
981     if (partialKeyLength >= sizeof(partialKey))
982       partialKeyLength = sizeof(partialKey) - 1;
983     strncpy(partialKey, keyPath, partialKeyLength);
984     partialKey[partialKeyLength] = '\0';
985     HKEY hTopKey = NULL;
986     lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
987                             &hTopKey);
988     if (lResult == ERROR_SUCCESS) {
989       char keyName[256];
990       double bestValue = 0.0;
991       DWORD index, size = sizeof(keyName) - 1;
992       for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
993                                     NULL, NULL) == ERROR_SUCCESS;
994            index++) {
995         const char *sp = keyName;
996         while (*sp && !isDigit(*sp))
997           sp++;
998         if (!*sp)
999           continue;
1000         const char *ep = sp + 1;
1001         while (*ep && (isDigit(*ep) || (*ep == '.')))
1002           ep++;
1003         char numBuf[32];
1004         strncpy(numBuf, sp, sizeof(numBuf) - 1);
1005         numBuf[sizeof(numBuf) - 1] = '\0';
1006         double dvalue = strtod(numBuf, NULL);
1007         if (dvalue > bestValue) {
1008           // Test that InstallDir is indeed there before keeping this index.
1009           // Open the chosen key path remainder.
1010           bestName = keyName;
1011           // Append rest of key.
1012           bestName.append(nextKey);
1013           lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
1014                                   KEY_READ | KEY_WOW64_32KEY, &hKey);
1015           if (lResult == ERROR_SUCCESS) {
1016             if (readFullStringValue(hKey, valueName, value)) {
1017               bestValue = dvalue;
1018               if (phValue)
1019                 *phValue = bestName;
1020               returnValue = true;
1021             }
1022             RegCloseKey(hKey);
1023           }
1024         }
1025         size = sizeof(keyName) - 1;
1026       }
1027       RegCloseKey(hTopKey);
1028     }
1029   } else {
1030     lResult =
1031         RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
1032     if (lResult == ERROR_SUCCESS) {
1033       if (readFullStringValue(hKey, valueName, value))
1034         returnValue = true;
1035       if (phValue)
1036         phValue->clear();
1037       RegCloseKey(hKey);
1038     }
1039   }
1040   return returnValue;
1041 #endif // _WIN32
1042 }
1043 
1044 // Find the most recent version of Universal CRT or Windows 10 SDK.
1045 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
1046 // directory by name and uses the last one of the list.
1047 // So we compare entry names lexicographically to find the greatest one.
1048 static bool getWindows10SDKVersionFromPath(const std::string &SDKPath,
1049                                            std::string &SDKVersion) {
1050   SDKVersion.clear();
1051 
1052   std::error_code EC;
1053   llvm::SmallString<128> IncludePath(SDKPath);
1054   llvm::sys::path::append(IncludePath, "Include");
1055   for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
1056        DirIt != DirEnd && !EC; DirIt.increment(EC)) {
1057     if (!llvm::sys::fs::is_directory(DirIt->path()))
1058       continue;
1059     StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
1060     // If WDK is installed, there could be subfolders like "wdf" in the
1061     // "Include" directory.
1062     // Allow only directories which names start with "10.".
1063     if (!CandidateName.startswith("10."))
1064       continue;
1065     if (CandidateName > SDKVersion)
1066       SDKVersion = std::string(CandidateName);
1067   }
1068 
1069   return !SDKVersion.empty();
1070 }
1071 
1072 /// Get Windows SDK installation directory.
1073 static bool getWindowsSDKDir(std::string &Path, int &Major,
1074                              std::string &WindowsSDKIncludeVersion,
1075                              std::string &WindowsSDKLibVersion) {
1076   std::string RegistrySDKVersion;
1077   // Try the Windows registry.
1078   if (!getSystemRegistryString(
1079           "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
1080           "InstallationFolder", Path, &RegistrySDKVersion))
1081     return false;
1082   if (Path.empty() || RegistrySDKVersion.empty())
1083     return false;
1084 
1085   WindowsSDKIncludeVersion.clear();
1086   WindowsSDKLibVersion.clear();
1087   Major = 0;
1088   std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
1089   if (Major <= 7)
1090     return true;
1091   if (Major == 8) {
1092     // Windows SDK 8.x installs libraries in a folder whose names depend on the
1093     // version of the OS you're targeting.  By default choose the newest, which
1094     // usually corresponds to the version of the OS you've installed the SDK on.
1095     const char *Tests[] = {"winv6.3", "win8", "win7"};
1096     for (const char *Test : Tests) {
1097       llvm::SmallString<128> TestPath(Path);
1098       llvm::sys::path::append(TestPath, "Lib", Test);
1099       if (llvm::sys::fs::exists(TestPath.c_str())) {
1100         WindowsSDKLibVersion = Test;
1101         break;
1102       }
1103     }
1104     return !WindowsSDKLibVersion.empty();
1105   }
1106   if (Major == 10) {
1107     if (!getWindows10SDKVersionFromPath(Path, WindowsSDKIncludeVersion))
1108       return false;
1109     WindowsSDKLibVersion = WindowsSDKIncludeVersion;
1110     return true;
1111   }
1112   // Unsupported SDK version
1113   return false;
1114 }
1115 
1116 // Gets the library path required to link against the Windows SDK.
1117 bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
1118   std::string sdkPath;
1119   int sdkMajor = 0;
1120   std::string windowsSDKIncludeVersion;
1121   std::string windowsSDKLibVersion;
1122 
1123   path.clear();
1124   if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
1125                         windowsSDKLibVersion))
1126     return false;
1127 
1128   llvm::SmallString<128> libPath(sdkPath);
1129   llvm::sys::path::append(libPath, "Lib");
1130   if (sdkMajor >= 8) {
1131     llvm::sys::path::append(libPath, windowsSDKLibVersion, "um",
1132                             llvmArchToWindowsSDKArch(getArch()));
1133   } else {
1134     switch (getArch()) {
1135     // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
1136     case llvm::Triple::x86:
1137       break;
1138     case llvm::Triple::x86_64:
1139       llvm::sys::path::append(libPath, "x64");
1140       break;
1141     case llvm::Triple::arm:
1142       // It is not necessary to link against Windows SDK 7.x when targeting ARM.
1143       return false;
1144     default:
1145       return false;
1146     }
1147   }
1148 
1149   path = std::string(libPath.str());
1150   return true;
1151 }
1152 
1153 // Check if the Include path of a specified version of Visual Studio contains
1154 // specific header files. If not, they are probably shipped with Universal CRT.
1155 bool MSVCToolChain::useUniversalCRT() const {
1156   llvm::SmallString<128> TestPath(
1157       getSubDirectoryPath(SubDirectoryType::Include));
1158   llvm::sys::path::append(TestPath, "stdlib.h");
1159   return !llvm::sys::fs::exists(TestPath);
1160 }
1161 
1162 static bool getUniversalCRTSdkDir(std::string &Path, std::string &UCRTVersion) {
1163   // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
1164   // for the specific key "KitsRoot10". So do we.
1165   if (!getSystemRegistryString(
1166           "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
1167           Path, nullptr))
1168     return false;
1169 
1170   return getWindows10SDKVersionFromPath(Path, UCRTVersion);
1171 }
1172 
1173 bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
1174   std::string UniversalCRTSdkPath;
1175   std::string UCRTVersion;
1176 
1177   Path.clear();
1178   if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
1179     return false;
1180 
1181   StringRef ArchName = llvmArchToWindowsSDKArch(getArch());
1182   if (ArchName.empty())
1183     return false;
1184 
1185   llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
1186   llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
1187 
1188   Path = std::string(LibPath.str());
1189   return true;
1190 }
1191 
1192 static VersionTuple getMSVCVersionFromTriple(const llvm::Triple &Triple) {
1193   unsigned Major, Minor, Micro;
1194   Triple.getEnvironmentVersion(Major, Minor, Micro);
1195   if (Major || Minor || Micro)
1196     return VersionTuple(Major, Minor, Micro);
1197   return VersionTuple();
1198 }
1199 
1200 static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
1201   VersionTuple Version;
1202 #ifdef _WIN32
1203   SmallString<128> ClExe(BinDir);
1204   llvm::sys::path::append(ClExe, "cl.exe");
1205 
1206   std::wstring ClExeWide;
1207   if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
1208     return Version;
1209 
1210   const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
1211                                                       nullptr);
1212   if (VersionSize == 0)
1213     return Version;
1214 
1215   SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
1216   if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
1217                              VersionBlock.data()))
1218     return Version;
1219 
1220   VS_FIXEDFILEINFO *FileInfo = nullptr;
1221   UINT FileInfoSize = 0;
1222   if (!::VerQueryValueW(VersionBlock.data(), L"\\",
1223                         reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
1224       FileInfoSize < sizeof(*FileInfo))
1225     return Version;
1226 
1227   const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
1228   const unsigned Minor = (FileInfo->dwFileVersionMS      ) & 0xFFFF;
1229   const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
1230 
1231   Version = VersionTuple(Major, Minor, Micro);
1232 #endif
1233   return Version;
1234 }
1235 
1236 void MSVCToolChain::AddSystemIncludeWithSubfolder(
1237     const ArgList &DriverArgs, ArgStringList &CC1Args,
1238     const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
1239     const Twine &subfolder3) const {
1240   llvm::SmallString<128> path(folder);
1241   llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
1242   addSystemInclude(DriverArgs, CC1Args, path);
1243 }
1244 
1245 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1246                                               ArgStringList &CC1Args) const {
1247   if (DriverArgs.hasArg(options::OPT_nostdinc))
1248     return;
1249 
1250   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1251     AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
1252                                   "include");
1253   }
1254 
1255   // Add %INCLUDE%-like directories from the -imsvc flag.
1256   for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
1257     addSystemInclude(DriverArgs, CC1Args, Path);
1258 
1259   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
1260     return;
1261 
1262   // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
1263   if (llvm::Optional<std::string> cl_include_dir =
1264           llvm::sys::Process::GetEnv("INCLUDE")) {
1265     SmallVector<StringRef, 8> Dirs;
1266     StringRef(*cl_include_dir)
1267         .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1268     for (StringRef Dir : Dirs)
1269       addSystemInclude(DriverArgs, CC1Args, Dir);
1270     if (!Dirs.empty())
1271       return;
1272   }
1273 
1274   // When built with access to the proper Windows APIs, try to actually find
1275   // the correct include paths first.
1276   if (!VCToolChainPath.empty()) {
1277     addSystemInclude(DriverArgs, CC1Args,
1278                      getSubDirectoryPath(SubDirectoryType::Include));
1279     addSystemInclude(DriverArgs, CC1Args,
1280                      getSubDirectoryPath(SubDirectoryType::Include, "atlmfc"));
1281 
1282     if (useUniversalCRT()) {
1283       std::string UniversalCRTSdkPath;
1284       std::string UCRTVersion;
1285       if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
1286         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
1287                                       "Include", UCRTVersion, "ucrt");
1288       }
1289     }
1290 
1291     std::string WindowsSDKDir;
1292     int major;
1293     std::string windowsSDKIncludeVersion;
1294     std::string windowsSDKLibVersion;
1295     if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
1296                          windowsSDKLibVersion)) {
1297       if (major >= 8) {
1298         // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
1299         // Anyway, llvm::sys::path::append is able to manage it.
1300         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1301                                       "include", windowsSDKIncludeVersion,
1302                                       "shared");
1303         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1304                                       "include", windowsSDKIncludeVersion,
1305                                       "um");
1306         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1307                                       "include", windowsSDKIncludeVersion,
1308                                       "winrt");
1309       } else {
1310         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1311                                       "include");
1312       }
1313     }
1314 
1315     return;
1316   }
1317 
1318 #if defined(_WIN32)
1319   // As a fallback, select default install paths.
1320   // FIXME: Don't guess drives and paths like this on Windows.
1321   const StringRef Paths[] = {
1322     "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
1323     "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
1324     "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
1325     "C:/Program Files/Microsoft Visual Studio 8/VC/include",
1326     "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
1327   };
1328   addSystemIncludes(DriverArgs, CC1Args, Paths);
1329 #endif
1330 }
1331 
1332 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1333                                                  ArgStringList &CC1Args) const {
1334   // FIXME: There should probably be logic here to find libc++ on Windows.
1335 }
1336 
1337 VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
1338                                                const ArgList &Args) const {
1339   bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
1340   VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
1341   if (MSVT.empty())
1342     MSVT = getMSVCVersionFromTriple(getTriple());
1343   if (MSVT.empty() && IsWindowsMSVC)
1344     MSVT = getMSVCVersionFromExe(getSubDirectoryPath(SubDirectoryType::Bin));
1345   if (MSVT.empty() &&
1346       Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1347                    IsWindowsMSVC)) {
1348     // -fms-compatibility-version=19.11 is default, aka 2017, 15.3
1349     MSVT = VersionTuple(19, 11);
1350   }
1351   return MSVT;
1352 }
1353 
1354 std::string
1355 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1356                                            types::ID InputType) const {
1357   // The MSVC version doesn't care about the architecture, even though it
1358   // may look at the triple internally.
1359   VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
1360   MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
1361                       MSVT.getSubminor().getValueOr(0));
1362 
1363   // For the rest of the triple, however, a computed architecture name may
1364   // be needed.
1365   llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
1366   if (Triple.getEnvironment() == llvm::Triple::MSVC) {
1367     StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
1368     if (ObjFmt.empty())
1369       Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
1370     else
1371       Triple.setEnvironmentName(
1372           (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
1373   }
1374   return Triple.getTriple();
1375 }
1376 
1377 SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
1378   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1379   Res |= SanitizerKind::Address;
1380   Res |= SanitizerKind::PointerCompare;
1381   Res |= SanitizerKind::PointerSubtract;
1382   Res |= SanitizerKind::Fuzzer;
1383   Res |= SanitizerKind::FuzzerNoLink;
1384   Res &= ~SanitizerKind::CFIMFCall;
1385   return Res;
1386 }
1387 
1388 static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1389                             bool SupportsForcingFramePointer,
1390                             const char *ExpandChar, const OptTable &Opts) {
1391   assert(A->getOption().matches(options::OPT__SLASH_O));
1392 
1393   StringRef OptStr = A->getValue();
1394   for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1395     const char &OptChar = *(OptStr.data() + I);
1396     switch (OptChar) {
1397     default:
1398       break;
1399     case '1':
1400     case '2':
1401     case 'x':
1402     case 'd':
1403       // Ignore /O[12xd] flags that aren't the last one on the command line.
1404       // Only the last one gets expanded.
1405       if (&OptChar != ExpandChar) {
1406         A->claim();
1407         break;
1408       }
1409       if (OptChar == 'd') {
1410         DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
1411       } else {
1412         if (OptChar == '1') {
1413           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1414         } else if (OptChar == '2' || OptChar == 'x') {
1415           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1416           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1417         }
1418         if (SupportsForcingFramePointer &&
1419             !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
1420           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
1421         if (OptChar == '1' || OptChar == '2')
1422           DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
1423       }
1424       break;
1425     case 'b':
1426       if (I + 1 != E && isdigit(OptStr[I + 1])) {
1427         switch (OptStr[I + 1]) {
1428         case '0':
1429           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
1430           break;
1431         case '1':
1432           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
1433           break;
1434         case '2':
1435           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
1436           break;
1437         }
1438         ++I;
1439       }
1440       break;
1441     case 'g':
1442       A->claim();
1443       break;
1444     case 'i':
1445       if (I + 1 != E && OptStr[I + 1] == '-') {
1446         ++I;
1447         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
1448       } else {
1449         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1450       }
1451       break;
1452     case 's':
1453       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1454       break;
1455     case 't':
1456       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1457       break;
1458     case 'y': {
1459       bool OmitFramePointer = true;
1460       if (I + 1 != E && OptStr[I + 1] == '-') {
1461         OmitFramePointer = false;
1462         ++I;
1463       }
1464       if (SupportsForcingFramePointer) {
1465         if (OmitFramePointer)
1466           DAL.AddFlagArg(A,
1467                          Opts.getOption(options::OPT_fomit_frame_pointer));
1468         else
1469           DAL.AddFlagArg(
1470               A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
1471       } else {
1472         // Don't warn about /Oy- in x86-64 builds (where
1473         // SupportsForcingFramePointer is false).  The flag having no effect
1474         // there is a compiler-internal optimization, and people shouldn't have
1475         // to special-case their build files for x86-64 clang-cl.
1476         A->claim();
1477       }
1478       break;
1479     }
1480     }
1481   }
1482 }
1483 
1484 static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1485                           const OptTable &Opts) {
1486   assert(A->getOption().matches(options::OPT_D));
1487 
1488   StringRef Val = A->getValue();
1489   size_t Hash = Val.find('#');
1490   if (Hash == StringRef::npos || Hash > Val.find('=')) {
1491     DAL.append(A);
1492     return;
1493   }
1494 
1495   std::string NewVal = std::string(Val);
1496   NewVal[Hash] = '=';
1497   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
1498 }
1499 
1500 llvm::opt::DerivedArgList *
1501 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
1502                              StringRef BoundArch,
1503                              Action::OffloadKind OFK) const {
1504   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1505   const OptTable &Opts = getDriver().getOpts();
1506 
1507   // /Oy and /Oy- don't have an effect on X86-64
1508   bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64;
1509 
1510   // The -O[12xd] flag actually expands to several flags.  We must desugar the
1511   // flags so that options embedded can be negated.  For example, the '-O2' flag
1512   // enables '-Oy'.  Expanding '-O2' into its constituent flags allows us to
1513   // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
1514   // aspect of '-O2'.
1515   //
1516   // Note that this expansion logic only applies to the *last* of '[12xd]'.
1517 
1518   // First step is to search for the character we'd like to expand.
1519   const char *ExpandChar = nullptr;
1520   for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
1521     StringRef OptStr = A->getValue();
1522     for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1523       char OptChar = OptStr[I];
1524       char PrevChar = I > 0 ? OptStr[I - 1] : '0';
1525       if (PrevChar == 'b') {
1526         // OptChar does not expand; it's an argument to the previous char.
1527         continue;
1528       }
1529       if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
1530         ExpandChar = OptStr.data() + I;
1531     }
1532   }
1533 
1534   for (Arg *A : Args) {
1535     if (A->getOption().matches(options::OPT__SLASH_O)) {
1536       // The -O flag actually takes an amalgam of other options.  For example,
1537       // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
1538       TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
1539     } else if (A->getOption().matches(options::OPT_D)) {
1540       // Translate -Dfoo#bar into -Dfoo=bar.
1541       TranslateDArg(A, *DAL, Opts);
1542     } else if (OFK != Action::OFK_HIP) {
1543       // HIP Toolchain translates input args by itself.
1544       DAL->append(A);
1545     }
1546   }
1547 
1548   return DAL;
1549 }
1550