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