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