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