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 =
596       std::make_unique<Command>(JA, *this, ResponseFileSupport::AtFileUTF16(),
597                                 Args.MakeArgString(linkPath), CmdArgs, Inputs);
598   if (!Environment.empty())
599     LinkCmd->setEnvironment(Environment);
600   C.addCommand(std::move(LinkCmd));
601 }
602 
603 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
604                                           const InputInfo &Output,
605                                           const InputInfoList &Inputs,
606                                           const ArgList &Args,
607                                           const char *LinkingOutput) const {
608   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
609 }
610 
611 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
612     Compilation &C, const JobAction &JA, const InputInfo &Output,
613     const InputInfoList &Inputs, const ArgList &Args,
614     const char *LinkingOutput) const {
615   ArgStringList CmdArgs;
616   CmdArgs.push_back("/nologo");
617   CmdArgs.push_back("/c");  // Compile only.
618   CmdArgs.push_back("/W0"); // No warnings.
619 
620   // The goal is to be able to invoke this tool correctly based on
621   // any flag accepted by clang-cl.
622 
623   // These are spelled the same way in clang and cl.exe,.
624   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
625 
626   // Optimization level.
627   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
628     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
629                                                                       : "/Oi-");
630   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
631     if (A->getOption().getID() == options::OPT_O0) {
632       CmdArgs.push_back("/Od");
633     } else {
634       CmdArgs.push_back("/Og");
635 
636       StringRef OptLevel = A->getValue();
637       if (OptLevel == "s" || OptLevel == "z")
638         CmdArgs.push_back("/Os");
639       else
640         CmdArgs.push_back("/Ot");
641 
642       CmdArgs.push_back("/Ob2");
643     }
644   }
645   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
646                                options::OPT_fno_omit_frame_pointer))
647     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
648                           ? "/Oy"
649                           : "/Oy-");
650   if (!Args.hasArg(options::OPT_fwritable_strings))
651     CmdArgs.push_back("/GF");
652 
653   // Flags for which clang-cl has an alias.
654   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
655 
656   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
657                    /*Default=*/false))
658     CmdArgs.push_back("/GR-");
659 
660   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
661                    /*Default=*/false))
662     CmdArgs.push_back("/GS-");
663 
664   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
665                                options::OPT_fno_function_sections))
666     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
667                           ? "/Gy"
668                           : "/Gy-");
669   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
670                                options::OPT_fno_data_sections))
671     CmdArgs.push_back(
672         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
673   if (Args.hasArg(options::OPT_fsyntax_only))
674     CmdArgs.push_back("/Zs");
675   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
676                   options::OPT__SLASH_Z7))
677     CmdArgs.push_back("/Z7");
678 
679   std::vector<std::string> Includes =
680       Args.getAllArgValues(options::OPT_include);
681   for (const auto &Include : Includes)
682     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
683 
684   // Flags that can simply be passed through.
685   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
686   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
687   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
688   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
689   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
690   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
691 
692   // The order of these flags is relevant, so pick the last one.
693   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
694                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
695     A->render(Args, CmdArgs);
696 
697   // Use MSVC's default threadsafe statics behaviour unless there was a flag.
698   if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
699                                options::OPT_fno_threadsafe_statics)) {
700     CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
701                           ? "/Zc:threadSafeInit"
702                           : "/Zc:threadSafeInit-");
703   }
704 
705   // Control Flow Guard checks
706   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
707     StringRef GuardArgs = A->getValue();
708     if (GuardArgs.equals_lower("cf") || GuardArgs.equals_lower("cf,nochecks")) {
709       // MSVC doesn't yet support the "nochecks" modifier.
710       CmdArgs.push_back("/guard:cf");
711     } else if (GuardArgs.equals_lower("cf-")) {
712       CmdArgs.push_back("/guard:cf-");
713     }
714   }
715 
716   // Pass through all unknown arguments so that the fallback command can see
717   // them too.
718   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
719 
720   // Input filename.
721   assert(Inputs.size() == 1);
722   const InputInfo &II = Inputs[0];
723   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
724   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
725   if (II.isFilename())
726     CmdArgs.push_back(II.getFilename());
727   else
728     II.getInputArg().renderAsInput(Args, CmdArgs);
729 
730   // Output filename.
731   assert(Output.getType() == types::TY_Object);
732   const char *Fo =
733       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
734   CmdArgs.push_back(Fo);
735 
736   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe");
737   return std::make_unique<Command>(JA, *this,
738                                    ResponseFileSupport::AtFileUTF16(),
739                                    Args.MakeArgString(Exec), CmdArgs, Inputs);
740 }
741 
742 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
743                              const ArgList &Args)
744     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
745       RocmInstallation(D, Triple, Args) {
746   getProgramPaths().push_back(getDriver().getInstalledDir());
747   if (getDriver().getInstalledDir() != getDriver().Dir)
748     getProgramPaths().push_back(getDriver().Dir);
749 
750   // Check the environment first, since that's probably the user telling us
751   // what they want to use.
752   // Failing that, just try to find the newest Visual Studio version we can
753   // and use its default VC toolchain.
754   findVCToolChainViaEnvironment(VCToolChainPath, VSLayout) ||
755       findVCToolChainViaSetupConfig(VCToolChainPath, VSLayout) ||
756       findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
757 }
758 
759 Tool *MSVCToolChain::buildLinker() const {
760   return new tools::visualstudio::Linker(*this);
761 }
762 
763 Tool *MSVCToolChain::buildAssembler() const {
764   if (getTriple().isOSBinFormatMachO())
765     return new tools::darwin::Assembler(*this);
766   getDriver().Diag(clang::diag::err_no_external_assembler);
767   return nullptr;
768 }
769 
770 bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
771   return true;
772 }
773 
774 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
775   // Don't emit unwind tables by default for MachO targets.
776   if (getTriple().isOSBinFormatMachO())
777     return false;
778 
779   // All non-x86_32 Windows targets require unwind tables. However, LLVM
780   // doesn't know how to generate them for all targets, so only enable
781   // the ones that are actually implemented.
782   return getArch() == llvm::Triple::x86_64 ||
783          getArch() == llvm::Triple::aarch64;
784 }
785 
786 bool MSVCToolChain::isPICDefault() const {
787   return getArch() == llvm::Triple::x86_64;
788 }
789 
790 bool MSVCToolChain::isPIEDefault() const {
791   return false;
792 }
793 
794 bool MSVCToolChain::isPICDefaultForced() const {
795   return getArch() == llvm::Triple::x86_64;
796 }
797 
798 void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
799                                        ArgStringList &CC1Args) const {
800   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
801 }
802 
803 void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
804                                       ArgStringList &CC1Args) const {
805   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
806 }
807 
808 void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
809   CudaInstallation.print(OS);
810 }
811 
812 // Windows SDKs and VC Toolchains group their contents into subdirectories based
813 // on the target architecture. This function converts an llvm::Triple::ArchType
814 // to the corresponding subdirectory name.
815 static const char *llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch) {
816   using ArchType = llvm::Triple::ArchType;
817   switch (Arch) {
818   case ArchType::x86:
819     return "x86";
820   case ArchType::x86_64:
821     return "x64";
822   case ArchType::arm:
823     return "arm";
824   case ArchType::aarch64:
825     return "arm64";
826   default:
827     return "";
828   }
829 }
830 
831 // Similar to the above function, but for Visual Studios before VS2017.
832 static const char *llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch) {
833   using ArchType = llvm::Triple::ArchType;
834   switch (Arch) {
835   case ArchType::x86:
836     // x86 is default in legacy VC toolchains.
837     // e.g. x86 libs are directly in /lib as opposed to /lib/x86.
838     return "";
839   case ArchType::x86_64:
840     return "amd64";
841   case ArchType::arm:
842     return "arm";
843   case ArchType::aarch64:
844     return "arm64";
845   default:
846     return "";
847   }
848 }
849 
850 // Similar to the above function, but for DevDiv internal builds.
851 static const char *llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch) {
852   using ArchType = llvm::Triple::ArchType;
853   switch (Arch) {
854   case ArchType::x86:
855     return "i386";
856   case ArchType::x86_64:
857     return "amd64";
858   case ArchType::arm:
859     return "arm";
860   case ArchType::aarch64:
861     return "arm64";
862   default:
863     return "";
864   }
865 }
866 
867 // Get the path to a specific subdirectory in the current toolchain for
868 // a given target architecture.
869 // VS2017 changed the VC toolchain layout, so this should be used instead
870 // of hardcoding paths.
871 std::string
872 MSVCToolChain::getSubDirectoryPath(SubDirectoryType Type,
873                                    llvm::StringRef SubdirParent,
874                                    llvm::Triple::ArchType TargetArch) const {
875   const char *SubdirName;
876   const char *IncludeName;
877   switch (VSLayout) {
878   case ToolsetLayout::OlderVS:
879     SubdirName = llvmArchToLegacyVCArch(TargetArch);
880     IncludeName = "include";
881     break;
882   case ToolsetLayout::VS2017OrNewer:
883     SubdirName = llvmArchToWindowsSDKArch(TargetArch);
884     IncludeName = "include";
885     break;
886   case ToolsetLayout::DevDivInternal:
887     SubdirName = llvmArchToDevDivInternalArch(TargetArch);
888     IncludeName = "inc";
889     break;
890   }
891 
892   llvm::SmallString<256> Path(VCToolChainPath);
893   if (!SubdirParent.empty())
894     llvm::sys::path::append(Path, SubdirParent);
895 
896   switch (Type) {
897   case SubDirectoryType::Bin:
898     if (VSLayout == ToolsetLayout::VS2017OrNewer) {
899       const bool HostIsX64 =
900           llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
901       const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
902       llvm::sys::path::append(Path, "bin", HostName, SubdirName);
903     } else { // OlderVS or DevDivInternal
904       llvm::sys::path::append(Path, "bin", SubdirName);
905     }
906     break;
907   case SubDirectoryType::Include:
908     llvm::sys::path::append(Path, IncludeName);
909     break;
910   case SubDirectoryType::Lib:
911     llvm::sys::path::append(Path, "lib", SubdirName);
912     break;
913   }
914   return std::string(Path.str());
915 }
916 
917 #ifdef _WIN32
918 static bool readFullStringValue(HKEY hkey, const char *valueName,
919                                 std::string &value) {
920   std::wstring WideValueName;
921   if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
922     return false;
923 
924   DWORD result = 0;
925   DWORD valueSize = 0;
926   DWORD type = 0;
927   // First just query for the required size.
928   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
929                             &valueSize);
930   if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
931     return false;
932   std::vector<BYTE> buffer(valueSize);
933   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
934                             &valueSize);
935   if (result == ERROR_SUCCESS) {
936     std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
937                            valueSize / sizeof(wchar_t));
938     if (valueSize && WideValue.back() == L'\0') {
939       WideValue.pop_back();
940     }
941     // The destination buffer must be empty as an invariant of the conversion
942     // function; but this function is sometimes called in a loop that passes in
943     // the same buffer, however. Simply clear it out so we can overwrite it.
944     value.clear();
945     return llvm::convertWideToUTF8(WideValue, value);
946   }
947   return false;
948 }
949 #endif
950 
951 /// Read registry string.
952 /// This also supports a means to look for high-versioned keys by use
953 /// of a $VERSION placeholder in the key path.
954 /// $VERSION in the key path is a placeholder for the version number,
955 /// causing the highest value path to be searched for and used.
956 /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
957 /// There can be additional characters in the component.  Only the numeric
958 /// characters are compared.  This function only searches HKLM.
959 static bool getSystemRegistryString(const char *keyPath, const char *valueName,
960                                     std::string &value, std::string *phValue) {
961 #ifndef _WIN32
962   return false;
963 #else
964   HKEY hRootKey = HKEY_LOCAL_MACHINE;
965   HKEY hKey = NULL;
966   long lResult;
967   bool returnValue = false;
968 
969   const char *placeHolder = strstr(keyPath, "$VERSION");
970   std::string bestName;
971   // If we have a $VERSION placeholder, do the highest-version search.
972   if (placeHolder) {
973     const char *keyEnd = placeHolder - 1;
974     const char *nextKey = placeHolder;
975     // Find end of previous key.
976     while ((keyEnd > keyPath) && (*keyEnd != '\\'))
977       keyEnd--;
978     // Find end of key containing $VERSION.
979     while (*nextKey && (*nextKey != '\\'))
980       nextKey++;
981     size_t partialKeyLength = keyEnd - keyPath;
982     char partialKey[256];
983     if (partialKeyLength >= sizeof(partialKey))
984       partialKeyLength = sizeof(partialKey) - 1;
985     strncpy(partialKey, keyPath, partialKeyLength);
986     partialKey[partialKeyLength] = '\0';
987     HKEY hTopKey = NULL;
988     lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
989                             &hTopKey);
990     if (lResult == ERROR_SUCCESS) {
991       char keyName[256];
992       double bestValue = 0.0;
993       DWORD index, size = sizeof(keyName) - 1;
994       for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
995                                     NULL, NULL) == ERROR_SUCCESS;
996            index++) {
997         const char *sp = keyName;
998         while (*sp && !isDigit(*sp))
999           sp++;
1000         if (!*sp)
1001           continue;
1002         const char *ep = sp + 1;
1003         while (*ep && (isDigit(*ep) || (*ep == '.')))
1004           ep++;
1005         char numBuf[32];
1006         strncpy(numBuf, sp, sizeof(numBuf) - 1);
1007         numBuf[sizeof(numBuf) - 1] = '\0';
1008         double dvalue = strtod(numBuf, NULL);
1009         if (dvalue > bestValue) {
1010           // Test that InstallDir is indeed there before keeping this index.
1011           // Open the chosen key path remainder.
1012           bestName = keyName;
1013           // Append rest of key.
1014           bestName.append(nextKey);
1015           lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
1016                                   KEY_READ | KEY_WOW64_32KEY, &hKey);
1017           if (lResult == ERROR_SUCCESS) {
1018             if (readFullStringValue(hKey, valueName, value)) {
1019               bestValue = dvalue;
1020               if (phValue)
1021                 *phValue = bestName;
1022               returnValue = true;
1023             }
1024             RegCloseKey(hKey);
1025           }
1026         }
1027         size = sizeof(keyName) - 1;
1028       }
1029       RegCloseKey(hTopKey);
1030     }
1031   } else {
1032     lResult =
1033         RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
1034     if (lResult == ERROR_SUCCESS) {
1035       if (readFullStringValue(hKey, valueName, value))
1036         returnValue = true;
1037       if (phValue)
1038         phValue->clear();
1039       RegCloseKey(hKey);
1040     }
1041   }
1042   return returnValue;
1043 #endif // _WIN32
1044 }
1045 
1046 // Find the most recent version of Universal CRT or Windows 10 SDK.
1047 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
1048 // directory by name and uses the last one of the list.
1049 // So we compare entry names lexicographically to find the greatest one.
1050 static bool getWindows10SDKVersionFromPath(const std::string &SDKPath,
1051                                            std::string &SDKVersion) {
1052   SDKVersion.clear();
1053 
1054   std::error_code EC;
1055   llvm::SmallString<128> IncludePath(SDKPath);
1056   llvm::sys::path::append(IncludePath, "Include");
1057   for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
1058        DirIt != DirEnd && !EC; DirIt.increment(EC)) {
1059     if (!llvm::sys::fs::is_directory(DirIt->path()))
1060       continue;
1061     StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
1062     // If WDK is installed, there could be subfolders like "wdf" in the
1063     // "Include" directory.
1064     // Allow only directories which names start with "10.".
1065     if (!CandidateName.startswith("10."))
1066       continue;
1067     if (CandidateName > SDKVersion)
1068       SDKVersion = std::string(CandidateName);
1069   }
1070 
1071   return !SDKVersion.empty();
1072 }
1073 
1074 /// Get Windows SDK installation directory.
1075 static bool getWindowsSDKDir(std::string &Path, int &Major,
1076                              std::string &WindowsSDKIncludeVersion,
1077                              std::string &WindowsSDKLibVersion) {
1078   std::string RegistrySDKVersion;
1079   // Try the Windows registry.
1080   if (!getSystemRegistryString(
1081           "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
1082           "InstallationFolder", Path, &RegistrySDKVersion))
1083     return false;
1084   if (Path.empty() || RegistrySDKVersion.empty())
1085     return false;
1086 
1087   WindowsSDKIncludeVersion.clear();
1088   WindowsSDKLibVersion.clear();
1089   Major = 0;
1090   std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
1091   if (Major <= 7)
1092     return true;
1093   if (Major == 8) {
1094     // Windows SDK 8.x installs libraries in a folder whose names depend on the
1095     // version of the OS you're targeting.  By default choose the newest, which
1096     // usually corresponds to the version of the OS you've installed the SDK on.
1097     const char *Tests[] = {"winv6.3", "win8", "win7"};
1098     for (const char *Test : Tests) {
1099       llvm::SmallString<128> TestPath(Path);
1100       llvm::sys::path::append(TestPath, "Lib", Test);
1101       if (llvm::sys::fs::exists(TestPath.c_str())) {
1102         WindowsSDKLibVersion = Test;
1103         break;
1104       }
1105     }
1106     return !WindowsSDKLibVersion.empty();
1107   }
1108   if (Major == 10) {
1109     if (!getWindows10SDKVersionFromPath(Path, WindowsSDKIncludeVersion))
1110       return false;
1111     WindowsSDKLibVersion = WindowsSDKIncludeVersion;
1112     return true;
1113   }
1114   // Unsupported SDK version
1115   return false;
1116 }
1117 
1118 // Gets the library path required to link against the Windows SDK.
1119 bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
1120   std::string sdkPath;
1121   int sdkMajor = 0;
1122   std::string windowsSDKIncludeVersion;
1123   std::string windowsSDKLibVersion;
1124 
1125   path.clear();
1126   if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
1127                         windowsSDKLibVersion))
1128     return false;
1129 
1130   llvm::SmallString<128> libPath(sdkPath);
1131   llvm::sys::path::append(libPath, "Lib");
1132   if (sdkMajor >= 8) {
1133     llvm::sys::path::append(libPath, windowsSDKLibVersion, "um",
1134                             llvmArchToWindowsSDKArch(getArch()));
1135   } else {
1136     switch (getArch()) {
1137     // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
1138     case llvm::Triple::x86:
1139       break;
1140     case llvm::Triple::x86_64:
1141       llvm::sys::path::append(libPath, "x64");
1142       break;
1143     case llvm::Triple::arm:
1144       // It is not necessary to link against Windows SDK 7.x when targeting ARM.
1145       return false;
1146     default:
1147       return false;
1148     }
1149   }
1150 
1151   path = std::string(libPath.str());
1152   return true;
1153 }
1154 
1155 // Check if the Include path of a specified version of Visual Studio contains
1156 // specific header files. If not, they are probably shipped with Universal CRT.
1157 bool MSVCToolChain::useUniversalCRT() const {
1158   llvm::SmallString<128> TestPath(
1159       getSubDirectoryPath(SubDirectoryType::Include));
1160   llvm::sys::path::append(TestPath, "stdlib.h");
1161   return !llvm::sys::fs::exists(TestPath);
1162 }
1163 
1164 static bool getUniversalCRTSdkDir(std::string &Path, std::string &UCRTVersion) {
1165   // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
1166   // for the specific key "KitsRoot10". So do we.
1167   if (!getSystemRegistryString(
1168           "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
1169           Path, nullptr))
1170     return false;
1171 
1172   return getWindows10SDKVersionFromPath(Path, UCRTVersion);
1173 }
1174 
1175 bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
1176   std::string UniversalCRTSdkPath;
1177   std::string UCRTVersion;
1178 
1179   Path.clear();
1180   if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
1181     return false;
1182 
1183   StringRef ArchName = llvmArchToWindowsSDKArch(getArch());
1184   if (ArchName.empty())
1185     return false;
1186 
1187   llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
1188   llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
1189 
1190   Path = std::string(LibPath.str());
1191   return true;
1192 }
1193 
1194 static VersionTuple getMSVCVersionFromTriple(const llvm::Triple &Triple) {
1195   unsigned Major, Minor, Micro;
1196   Triple.getEnvironmentVersion(Major, Minor, Micro);
1197   if (Major || Minor || Micro)
1198     return VersionTuple(Major, Minor, Micro);
1199   return VersionTuple();
1200 }
1201 
1202 static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
1203   VersionTuple Version;
1204 #ifdef _WIN32
1205   SmallString<128> ClExe(BinDir);
1206   llvm::sys::path::append(ClExe, "cl.exe");
1207 
1208   std::wstring ClExeWide;
1209   if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
1210     return Version;
1211 
1212   const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
1213                                                       nullptr);
1214   if (VersionSize == 0)
1215     return Version;
1216 
1217   SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
1218   if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
1219                              VersionBlock.data()))
1220     return Version;
1221 
1222   VS_FIXEDFILEINFO *FileInfo = nullptr;
1223   UINT FileInfoSize = 0;
1224   if (!::VerQueryValueW(VersionBlock.data(), L"\\",
1225                         reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
1226       FileInfoSize < sizeof(*FileInfo))
1227     return Version;
1228 
1229   const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
1230   const unsigned Minor = (FileInfo->dwFileVersionMS      ) & 0xFFFF;
1231   const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
1232 
1233   Version = VersionTuple(Major, Minor, Micro);
1234 #endif
1235   return Version;
1236 }
1237 
1238 void MSVCToolChain::AddSystemIncludeWithSubfolder(
1239     const ArgList &DriverArgs, ArgStringList &CC1Args,
1240     const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
1241     const Twine &subfolder3) const {
1242   llvm::SmallString<128> path(folder);
1243   llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
1244   addSystemInclude(DriverArgs, CC1Args, path);
1245 }
1246 
1247 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1248                                               ArgStringList &CC1Args) const {
1249   if (DriverArgs.hasArg(options::OPT_nostdinc))
1250     return;
1251 
1252   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1253     AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
1254                                   "include");
1255   }
1256 
1257   // Add %INCLUDE%-like directories from the -imsvc flag.
1258   for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
1259     addSystemInclude(DriverArgs, CC1Args, Path);
1260 
1261   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
1262     return;
1263 
1264   // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
1265   if (llvm::Optional<std::string> cl_include_dir =
1266           llvm::sys::Process::GetEnv("INCLUDE")) {
1267     SmallVector<StringRef, 8> Dirs;
1268     StringRef(*cl_include_dir)
1269         .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1270     for (StringRef Dir : Dirs)
1271       addSystemInclude(DriverArgs, CC1Args, Dir);
1272     if (!Dirs.empty())
1273       return;
1274   }
1275 
1276   // When built with access to the proper Windows APIs, try to actually find
1277   // the correct include paths first.
1278   if (!VCToolChainPath.empty()) {
1279     addSystemInclude(DriverArgs, CC1Args,
1280                      getSubDirectoryPath(SubDirectoryType::Include));
1281     addSystemInclude(DriverArgs, CC1Args,
1282                      getSubDirectoryPath(SubDirectoryType::Include, "atlmfc"));
1283 
1284     if (useUniversalCRT()) {
1285       std::string UniversalCRTSdkPath;
1286       std::string UCRTVersion;
1287       if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
1288         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
1289                                       "Include", UCRTVersion, "ucrt");
1290       }
1291     }
1292 
1293     std::string WindowsSDKDir;
1294     int major;
1295     std::string windowsSDKIncludeVersion;
1296     std::string windowsSDKLibVersion;
1297     if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
1298                          windowsSDKLibVersion)) {
1299       if (major >= 8) {
1300         // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
1301         // Anyway, llvm::sys::path::append is able to manage it.
1302         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1303                                       "include", windowsSDKIncludeVersion,
1304                                       "shared");
1305         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1306                                       "include", windowsSDKIncludeVersion,
1307                                       "um");
1308         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1309                                       "include", windowsSDKIncludeVersion,
1310                                       "winrt");
1311       } else {
1312         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1313                                       "include");
1314       }
1315     }
1316 
1317     return;
1318   }
1319 
1320 #if defined(_WIN32)
1321   // As a fallback, select default install paths.
1322   // FIXME: Don't guess drives and paths like this on Windows.
1323   const StringRef Paths[] = {
1324     "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
1325     "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
1326     "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
1327     "C:/Program Files/Microsoft Visual Studio 8/VC/include",
1328     "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
1329   };
1330   addSystemIncludes(DriverArgs, CC1Args, Paths);
1331 #endif
1332 }
1333 
1334 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1335                                                  ArgStringList &CC1Args) const {
1336   // FIXME: There should probably be logic here to find libc++ on Windows.
1337 }
1338 
1339 VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
1340                                                const ArgList &Args) const {
1341   bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
1342   VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
1343   if (MSVT.empty())
1344     MSVT = getMSVCVersionFromTriple(getTriple());
1345   if (MSVT.empty() && IsWindowsMSVC)
1346     MSVT = getMSVCVersionFromExe(getSubDirectoryPath(SubDirectoryType::Bin));
1347   if (MSVT.empty() &&
1348       Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1349                    IsWindowsMSVC)) {
1350     // -fms-compatibility-version=19.11 is default, aka 2017, 15.3
1351     MSVT = VersionTuple(19, 11);
1352   }
1353   return MSVT;
1354 }
1355 
1356 std::string
1357 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1358                                            types::ID InputType) const {
1359   // The MSVC version doesn't care about the architecture, even though it
1360   // may look at the triple internally.
1361   VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
1362   MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
1363                       MSVT.getSubminor().getValueOr(0));
1364 
1365   // For the rest of the triple, however, a computed architecture name may
1366   // be needed.
1367   llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
1368   if (Triple.getEnvironment() == llvm::Triple::MSVC) {
1369     StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
1370     if (ObjFmt.empty())
1371       Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
1372     else
1373       Triple.setEnvironmentName(
1374           (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
1375   }
1376   return Triple.getTriple();
1377 }
1378 
1379 SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
1380   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1381   Res |= SanitizerKind::Address;
1382   Res |= SanitizerKind::PointerCompare;
1383   Res |= SanitizerKind::PointerSubtract;
1384   Res |= SanitizerKind::Fuzzer;
1385   Res |= SanitizerKind::FuzzerNoLink;
1386   Res &= ~SanitizerKind::CFIMFCall;
1387   return Res;
1388 }
1389 
1390 static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1391                             bool SupportsForcingFramePointer,
1392                             const char *ExpandChar, const OptTable &Opts) {
1393   assert(A->getOption().matches(options::OPT__SLASH_O));
1394 
1395   StringRef OptStr = A->getValue();
1396   for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1397     const char &OptChar = *(OptStr.data() + I);
1398     switch (OptChar) {
1399     default:
1400       break;
1401     case '1':
1402     case '2':
1403     case 'x':
1404     case 'd':
1405       // Ignore /O[12xd] flags that aren't the last one on the command line.
1406       // Only the last one gets expanded.
1407       if (&OptChar != ExpandChar) {
1408         A->claim();
1409         break;
1410       }
1411       if (OptChar == 'd') {
1412         DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
1413       } else {
1414         if (OptChar == '1') {
1415           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1416         } else if (OptChar == '2' || OptChar == 'x') {
1417           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1418           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1419         }
1420         if (SupportsForcingFramePointer &&
1421             !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
1422           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
1423         if (OptChar == '1' || OptChar == '2')
1424           DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
1425       }
1426       break;
1427     case 'b':
1428       if (I + 1 != E && isdigit(OptStr[I + 1])) {
1429         switch (OptStr[I + 1]) {
1430         case '0':
1431           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
1432           break;
1433         case '1':
1434           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
1435           break;
1436         case '2':
1437           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
1438           break;
1439         }
1440         ++I;
1441       }
1442       break;
1443     case 'g':
1444       A->claim();
1445       break;
1446     case 'i':
1447       if (I + 1 != E && OptStr[I + 1] == '-') {
1448         ++I;
1449         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
1450       } else {
1451         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1452       }
1453       break;
1454     case 's':
1455       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1456       break;
1457     case 't':
1458       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1459       break;
1460     case 'y': {
1461       bool OmitFramePointer = true;
1462       if (I + 1 != E && OptStr[I + 1] == '-') {
1463         OmitFramePointer = false;
1464         ++I;
1465       }
1466       if (SupportsForcingFramePointer) {
1467         if (OmitFramePointer)
1468           DAL.AddFlagArg(A,
1469                          Opts.getOption(options::OPT_fomit_frame_pointer));
1470         else
1471           DAL.AddFlagArg(
1472               A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
1473       } else {
1474         // Don't warn about /Oy- in x86-64 builds (where
1475         // SupportsForcingFramePointer is false).  The flag having no effect
1476         // there is a compiler-internal optimization, and people shouldn't have
1477         // to special-case their build files for x86-64 clang-cl.
1478         A->claim();
1479       }
1480       break;
1481     }
1482     }
1483   }
1484 }
1485 
1486 static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1487                           const OptTable &Opts) {
1488   assert(A->getOption().matches(options::OPT_D));
1489 
1490   StringRef Val = A->getValue();
1491   size_t Hash = Val.find('#');
1492   if (Hash == StringRef::npos || Hash > Val.find('=')) {
1493     DAL.append(A);
1494     return;
1495   }
1496 
1497   std::string NewVal = std::string(Val);
1498   NewVal[Hash] = '=';
1499   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
1500 }
1501 
1502 llvm::opt::DerivedArgList *
1503 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
1504                              StringRef BoundArch,
1505                              Action::OffloadKind OFK) const {
1506   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1507   const OptTable &Opts = getDriver().getOpts();
1508 
1509   // /Oy and /Oy- don't have an effect on X86-64
1510   bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64;
1511 
1512   // The -O[12xd] flag actually expands to several flags.  We must desugar the
1513   // flags so that options embedded can be negated.  For example, the '-O2' flag
1514   // enables '-Oy'.  Expanding '-O2' into its constituent flags allows us to
1515   // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
1516   // aspect of '-O2'.
1517   //
1518   // Note that this expansion logic only applies to the *last* of '[12xd]'.
1519 
1520   // First step is to search for the character we'd like to expand.
1521   const char *ExpandChar = nullptr;
1522   for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
1523     StringRef OptStr = A->getValue();
1524     for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1525       char OptChar = OptStr[I];
1526       char PrevChar = I > 0 ? OptStr[I - 1] : '0';
1527       if (PrevChar == 'b') {
1528         // OptChar does not expand; it's an argument to the previous char.
1529         continue;
1530       }
1531       if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
1532         ExpandChar = OptStr.data() + I;
1533     }
1534   }
1535 
1536   for (Arg *A : Args) {
1537     if (A->getOption().matches(options::OPT__SLASH_O)) {
1538       // The -O flag actually takes an amalgam of other options.  For example,
1539       // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
1540       TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
1541     } else if (A->getOption().matches(options::OPT_D)) {
1542       // Translate -Dfoo#bar into -Dfoo=bar.
1543       TranslateDArg(A, *DAL, Opts);
1544     } else if (OFK != Action::OFK_HIP) {
1545       // HIP Toolchain translates input args by itself.
1546       DAL->append(A);
1547     }
1548   }
1549 
1550   return DAL;
1551 }
1552