MSVC.cpp 55 KB

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