blob: acfb507fea50421091627fa2c6321f16bff7b8d8 [file] [log] [blame]
Chandler Carruth1fc603e2011-12-17 23:10:01 +00001//===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ToolChains.h"
David Majnemere11d3732015-06-08 00:22:46 +000011#include "Tools.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000012#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/Version.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000014#include "clang/Driver/Compilation.h"
15#include "clang/Driver/Driver.h"
Rafael Espindola79764462013-03-24 15:06:53 +000016#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000017#include "clang/Driver/Options.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000018#include "llvm/ADT/StringExtras.h"
Alp Tokerf1ffc842014-06-22 04:31:15 +000019#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000022#include "llvm/Support/ErrorHandling.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000023#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Process.h"
Reid Kleckner6b7156b2015-01-23 19:16:25 +000025#include <cstdio>
26
Chandler Carruth1fc603e2011-12-17 23:10:01 +000027// Include the necessary headers to interface with the Windows registry and
28// environment.
Alp Tokerf1ffc842014-06-22 04:31:15 +000029#if defined(LLVM_ON_WIN32)
Alp Tokerfcce1832014-06-22 03:27:45 +000030#define USE_WIN32
31#endif
32
33#ifdef USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +000034 #define WIN32_LEAN_AND_MEAN
35 #define NOGDI
Yaron Keren7fc6f1e2014-12-04 21:46:50 +000036 #ifndef NOMINMAX
37 #define NOMINMAX
38 #endif
Logan Chien733e3c62014-06-24 16:18:10 +000039 #include <windows.h>
Chandler Carruth1fc603e2011-12-17 23:10:01 +000040#endif
41
42using namespace clang::driver;
43using namespace clang::driver::toolchains;
44using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000045using namespace llvm::opt;
Chandler Carruth1fc603e2011-12-17 23:10:01 +000046
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000047MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple& Triple,
48 const ArgList &Args)
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000049 : ToolChain(D, Triple, Args) {
Zachary Turner719f58c2014-12-01 23:06:47 +000050 getProgramPaths().push_back(getDriver().getInstalledDir());
51 if (getDriver().getInstalledDir() != getDriver().Dir)
52 getProgramPaths().push_back(getDriver().Dir);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000053}
54
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000055Tool *MSVCToolChain::buildLinker() const {
Douglas Katzman95354292015-06-23 20:42:09 +000056 return new tools::visualstudio::Linker(*this);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000057}
58
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000059Tool *MSVCToolChain::buildAssembler() const {
Saleem Abdulrasool377066a2014-03-27 22:50:18 +000060 if (getTriple().isOSBinFormatMachO())
Douglas Katzman95354292015-06-23 20:42:09 +000061 return new tools::darwin::Assembler(*this);
Alp Tokerc8d4f0f2013-11-22 08:27:46 +000062 getDriver().Diag(clang::diag::err_no_external_assembler);
Craig Topper92fc2df2014-05-17 16:56:41 +000063 return nullptr;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000064}
65
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000066bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000067 return true;
68}
69
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000070bool MSVCToolChain::IsUnwindTablesDefault() const {
Reid Kleckner6b3a9402014-09-04 18:13:12 +000071 // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
72 // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
73 // how to generate them yet.
Akira Hatanakae4218132016-05-05 01:41:07 +000074
75 // Don't emit unwind tables by default for MachO targets.
76 if (getTriple().isOSBinFormatMachO())
77 return false;
78
Reid Kleckner6b3a9402014-09-04 18:13:12 +000079 return getArch() == llvm::Triple::x86_64;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000080}
81
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000082bool MSVCToolChain::isPICDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000083 return getArch() == llvm::Triple::x86_64;
84}
85
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000086bool MSVCToolChain::isPIEDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000087 return false;
88}
89
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000090bool MSVCToolChain::isPICDefaultForced() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000091 return getArch() == llvm::Triple::x86_64;
92}
93
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000094#ifdef USE_WIN32
95static bool readFullStringValue(HKEY hkey, const char *valueName,
96 std::string &value) {
97 // FIXME: We should be using the W versions of the registry functions, but
98 // doing so requires UTF8 / UTF16 conversions similar to how we handle command
99 // line arguments. The UTF8 conversion functions are not exposed publicly
100 // from LLVM though, so in order to do this we will probably need to create
101 // a registry abstraction in LLVMSupport that is Windows only.
102 DWORD result = 0;
103 DWORD valueSize = 0;
104 DWORD type = 0;
105 // First just query for the required size.
106 result = RegQueryValueEx(hkey, valueName, NULL, &type, NULL, &valueSize);
107 if (result != ERROR_SUCCESS || type != REG_SZ)
108 return false;
109 std::vector<BYTE> buffer(valueSize);
110 result = RegQueryValueEx(hkey, valueName, NULL, NULL, &buffer[0], &valueSize);
111 if (result == ERROR_SUCCESS)
112 value.assign(reinterpret_cast<const char *>(buffer.data()));
113 return result;
114}
115#endif
116
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000117/// \brief Read registry string.
118/// This also supports a means to look for high-versioned keys by use
119/// of a $VERSION placeholder in the key path.
120/// $VERSION in the key path is a placeholder for the version number,
121/// causing the highest value path to be searched for and used.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000122/// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
123/// There can be additional characters in the component. Only the numeric
124/// characters are compared. This function only searches HKLM.
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000125static bool getSystemRegistryString(const char *keyPath, const char *valueName,
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000126 std::string &value, std::string *phValue) {
Alp Tokerfcce1832014-06-22 03:27:45 +0000127#ifndef USE_WIN32
128 return false;
129#else
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000130 HKEY hRootKey = HKEY_LOCAL_MACHINE;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000131 HKEY hKey = NULL;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000132 long lResult;
133 bool returnValue = false;
134
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000135 const char *placeHolder = strstr(keyPath, "$VERSION");
136 std::string bestName;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000137 // If we have a $VERSION placeholder, do the highest-version search.
138 if (placeHolder) {
139 const char *keyEnd = placeHolder - 1;
140 const char *nextKey = placeHolder;
141 // Find end of previous key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000142 while ((keyEnd > keyPath) && (*keyEnd != '\\'))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000143 keyEnd--;
144 // Find end of key containing $VERSION.
145 while (*nextKey && (*nextKey != '\\'))
146 nextKey++;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000147 size_t partialKeyLength = keyEnd - keyPath;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000148 char partialKey[256];
Daniel Marjamakie1146692016-01-27 07:33:50 +0000149 if (partialKeyLength >= sizeof(partialKey))
150 partialKeyLength = sizeof(partialKey) - 1;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000151 strncpy(partialKey, keyPath, partialKeyLength);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000152 partialKey[partialKeyLength] = '\0';
153 HKEY hTopKey = NULL;
Hans Wennborg935d01d2013-10-09 23:41:48 +0000154 lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
155 &hTopKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000156 if (lResult == ERROR_SUCCESS) {
157 char keyName[256];
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000158 double bestValue = 0.0;
159 DWORD index, size = sizeof(keyName) - 1;
160 for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
161 NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
162 const char *sp = keyName;
Jordan Rosea7d03842013-02-08 22:30:41 +0000163 while (*sp && !isDigit(*sp))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000164 sp++;
165 if (!*sp)
166 continue;
167 const char *ep = sp + 1;
Jordan Rosea7d03842013-02-08 22:30:41 +0000168 while (*ep && (isDigit(*ep) || (*ep == '.')))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000169 ep++;
170 char numBuf[32];
171 strncpy(numBuf, sp, sizeof(numBuf) - 1);
172 numBuf[sizeof(numBuf) - 1] = '\0';
Hans Wennborgd2192312013-10-10 18:03:08 +0000173 double dvalue = strtod(numBuf, NULL);
174 if (dvalue > bestValue) {
175 // Test that InstallDir is indeed there before keeping this index.
176 // Open the chosen key path remainder.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000177 bestName = keyName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000178 // Append rest of key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000179 bestName.append(nextKey);
180 lResult = RegOpenKeyEx(hTopKey, bestName.c_str(), 0,
Hans Wennborgd2192312013-10-10 18:03:08 +0000181 KEY_READ | KEY_WOW64_32KEY, &hKey);
182 if (lResult == ERROR_SUCCESS) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000183 lResult = readFullStringValue(hKey, valueName, value);
Hans Wennborgd2192312013-10-10 18:03:08 +0000184 if (lResult == ERROR_SUCCESS) {
Hans Wennborgd2192312013-10-10 18:03:08 +0000185 bestValue = dvalue;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000186 if (phValue)
187 *phValue = bestName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000188 returnValue = true;
189 }
190 RegCloseKey(hKey);
191 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000192 }
193 size = sizeof(keyName) - 1;
194 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000195 RegCloseKey(hTopKey);
196 }
197 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000198 lResult =
199 RegOpenKeyEx(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000200 if (lResult == ERROR_SUCCESS) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000201 lResult = readFullStringValue(hKey, valueName, value);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000202 if (lResult == ERROR_SUCCESS)
203 returnValue = true;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000204 if (phValue)
205 phValue->clear();
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000206 RegCloseKey(hKey);
207 }
208 }
209 return returnValue;
Alp Tokerfcce1832014-06-22 03:27:45 +0000210#endif // USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000211}
212
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000213// Convert LLVM's ArchType
214// to the corresponding name of Windows SDK libraries subfolder
215static StringRef getWindowsSDKArch(llvm::Triple::ArchType Arch) {
216 switch (Arch) {
217 case llvm::Triple::x86:
218 return "x86";
219 case llvm::Triple::x86_64:
220 return "x64";
221 case llvm::Triple::arm:
222 return "arm";
223 default:
224 return "";
225 }
226}
227
Igor Kudrinf2e75242015-09-24 05:16:36 +0000228// Find the most recent version of Universal CRT or Windows 10 SDK.
229// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
230// directory by name and uses the last one of the list.
231// So we compare entry names lexicographically to find the greatest one.
232static bool getWindows10SDKVersion(const std::string &SDKPath,
233 std::string &SDKVersion) {
234 SDKVersion.clear();
235
236 std::error_code EC;
237 llvm::SmallString<128> IncludePath(SDKPath);
238 llvm::sys::path::append(IncludePath, "Include");
239 for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
240 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
241 if (!llvm::sys::fs::is_directory(DirIt->path()))
242 continue;
243 StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
244 // If WDK is installed, there could be subfolders like "wdf" in the
245 // "Include" directory.
246 // Allow only directories which names start with "10.".
247 if (!CandidateName.startswith("10."))
248 continue;
249 if (CandidateName > SDKVersion)
250 SDKVersion = CandidateName;
251 }
252
253 return !SDKVersion.empty();
254}
255
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000256/// \brief Get Windows SDK installation directory.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000257bool MSVCToolChain::getWindowsSDKDir(std::string &Path, int &Major,
258 std::string &WindowsSDKIncludeVersion,
259 std::string &WindowsSDKLibVersion) const {
260 std::string RegistrySDKVersion;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000261 // Try the Windows registry.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000262 if (!getSystemRegistryString(
263 "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
264 "InstallationFolder", Path, &RegistrySDKVersion))
265 return false;
266 if (Path.empty() || RegistrySDKVersion.empty())
267 return false;
268
269 WindowsSDKIncludeVersion.clear();
270 WindowsSDKLibVersion.clear();
271 Major = 0;
272 std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
273 if (Major <= 7)
274 return true;
275 if (Major == 8) {
276 // Windows SDK 8.x installs libraries in a folder whose names depend on the
277 // version of the OS you're targeting. By default choose the newest, which
278 // usually corresponds to the version of the OS you've installed the SDK on.
279 const char *Tests[] = {"winv6.3", "win8", "win7"};
280 for (const char *Test : Tests) {
281 llvm::SmallString<128> TestPath(Path);
282 llvm::sys::path::append(TestPath, "Lib", Test);
283 if (llvm::sys::fs::exists(TestPath.c_str())) {
284 WindowsSDKLibVersion = Test;
285 break;
286 }
287 }
288 return !WindowsSDKLibVersion.empty();
289 }
290 if (Major == 10) {
291 if (!getWindows10SDKVersion(Path, WindowsSDKIncludeVersion))
292 return false;
293 WindowsSDKLibVersion = WindowsSDKIncludeVersion;
294 return true;
295 }
296 // Unsupported SDK version
297 return false;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000298}
299
Zachary Turner10d75b22014-10-22 20:40:43 +0000300// Gets the library path required to link against the Windows SDK.
301bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
302 std::string sdkPath;
303 int sdkMajor = 0;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000304 std::string windowsSDKIncludeVersion;
305 std::string windowsSDKLibVersion;
Zachary Turner10d75b22014-10-22 20:40:43 +0000306
307 path.clear();
Igor Kudrinf2e75242015-09-24 05:16:36 +0000308 if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
309 windowsSDKLibVersion))
Zachary Turner10d75b22014-10-22 20:40:43 +0000310 return false;
311
312 llvm::SmallString<128> libPath(sdkPath);
313 llvm::sys::path::append(libPath, "Lib");
314 if (sdkMajor <= 7) {
315 switch (getArch()) {
316 // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
317 case llvm::Triple::x86:
318 break;
319 case llvm::Triple::x86_64:
320 llvm::sys::path::append(libPath, "x64");
321 break;
322 case llvm::Triple::arm:
323 // It is not necessary to link against Windows SDK 7.x when targeting ARM.
324 return false;
325 default:
326 return false;
327 }
328 } else {
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000329 const StringRef archName = getWindowsSDKArch(getArch());
330 if (archName.empty())
Zachary Turner10d75b22014-10-22 20:40:43 +0000331 return false;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000332 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um", archName);
Zachary Turner10d75b22014-10-22 20:40:43 +0000333 }
334
335 path = libPath.str();
336 return true;
337}
338
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000339// Check if the Include path of a specified version of Visual Studio contains
340// specific header files. If not, they are probably shipped with Universal CRT.
341bool clang::driver::toolchains::MSVCToolChain::useUniversalCRT(
342 std::string &VisualStudioDir) const {
343 llvm::SmallString<128> TestPath(VisualStudioDir);
344 llvm::sys::path::append(TestPath, "VC\\include\\stdlib.h");
345
346 return !llvm::sys::fs::exists(TestPath);
347}
348
349bool MSVCToolChain::getUniversalCRTSdkDir(std::string &Path,
350 std::string &UCRTVersion) const {
351 // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
352 // for the specific key "KitsRoot10". So do we.
353 if (!getSystemRegistryString(
354 "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
355 Path, nullptr))
356 return false;
357
Igor Kudrinf2e75242015-09-24 05:16:36 +0000358 return getWindows10SDKVersion(Path, UCRTVersion);
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000359}
360
361bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
362 std::string UniversalCRTSdkPath;
363 std::string UCRTVersion;
364
365 Path.clear();
366 if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
367 return false;
368
369 StringRef ArchName = getWindowsSDKArch(getArch());
370 if (ArchName.empty())
371 return false;
372
373 llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
374 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
375
376 Path = LibPath.str();
377 return true;
378}
379
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000380// Get the location to use for Visual Studio binaries. The location priority
381// is: %VCINSTALLDIR% > %PATH% > newest copy of Visual Studio installed on
382// system (as reported by the registry).
383bool MSVCToolChain::getVisualStudioBinariesFolder(const char *clangProgramPath,
384 std::string &path) const {
385 path.clear();
386
387 SmallString<128> BinDir;
388
389 // First check the environment variables that vsvars32.bat sets.
390 llvm::Optional<std::string> VcInstallDir =
391 llvm::sys::Process::GetEnv("VCINSTALLDIR");
392 if (VcInstallDir.hasValue()) {
393 BinDir = VcInstallDir.getValue();
394 llvm::sys::path::append(BinDir, "bin");
395 } else {
396 // Next walk the PATH, trying to find a cl.exe in the path. If we find one,
397 // use that. However, make sure it's not clang's cl.exe.
398 llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
399 if (OptPath.hasValue()) {
400 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
401 SmallVector<StringRef, 8> PathSegments;
402 llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
403
404 for (StringRef PathSegment : PathSegments) {
405 if (PathSegment.empty())
406 continue;
407
408 SmallString<128> FilePath(PathSegment);
409 llvm::sys::path::append(FilePath, "cl.exe");
410 if (llvm::sys::fs::can_execute(FilePath.c_str()) &&
411 !llvm::sys::fs::equivalent(FilePath.c_str(), clangProgramPath)) {
412 // If we found it on the PATH, use it exactly as is with no
413 // modifications.
414 path = PathSegment;
415 return true;
416 }
417 }
418 }
419
420 std::string installDir;
421 // With no VCINSTALLDIR and nothing on the PATH, if we can't find it in the
422 // registry then we have no choice but to fail.
423 if (!getVisualStudioInstallDir(installDir))
424 return false;
425
426 // Regardless of what binary we're ultimately trying to find, we make sure
427 // that this is a Visual Studio directory by checking for cl.exe. We use
428 // cl.exe instead of other binaries like link.exe because programs such as
429 // GnuWin32 also have a utility called link.exe, so cl.exe is the least
430 // ambiguous.
431 BinDir = installDir;
432 llvm::sys::path::append(BinDir, "VC", "bin");
433 SmallString<128> ClPath(BinDir);
434 llvm::sys::path::append(ClPath, "cl.exe");
435
436 if (!llvm::sys::fs::can_execute(ClPath.c_str()))
437 return false;
Hans Wennborge6b994e2014-10-20 23:26:03 +0000438 }
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000439
440 if (BinDir.empty())
441 return false;
442
443 switch (getArch()) {
444 case llvm::Triple::x86:
445 break;
446 case llvm::Triple::x86_64:
447 llvm::sys::path::append(BinDir, "amd64");
448 break;
449 case llvm::Triple::arm:
450 llvm::sys::path::append(BinDir, "arm");
451 break;
452 default:
453 // Whatever this is, Visual Studio doesn't have a toolchain for it.
454 return false;
455 }
456 path = BinDir.str();
457 return true;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000458}
459
Alp Tokerfcce1832014-06-22 03:27:45 +0000460// Get Visual Studio installation directory.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000461bool MSVCToolChain::getVisualStudioInstallDir(std::string &path) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000462 // First check the environment variables that vsvars32.bat sets.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000463 const char *vcinstalldir = getenv("VCINSTALLDIR");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000464 if (vcinstalldir) {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000465 path = vcinstalldir;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000466 path = path.substr(0, path.find("\\VC"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000467 return true;
468 }
469
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000470 std::string vsIDEInstallDir;
471 std::string vsExpressIDEInstallDir;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000472 // Then try the windows registry.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000473 bool hasVCDir =
474 getSystemRegistryString("SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
475 "InstallDir", vsIDEInstallDir, nullptr);
476 if (hasVCDir && !vsIDEInstallDir.empty()) {
477 path = vsIDEInstallDir.substr(0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000478 return true;
479 }
480
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000481 bool hasVCExpressDir =
482 getSystemRegistryString("SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
483 "InstallDir", vsExpressIDEInstallDir, nullptr);
484 if (hasVCExpressDir && !vsExpressIDEInstallDir.empty()) {
485 path = vsExpressIDEInstallDir.substr(
486 0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000487 return true;
488 }
489
490 // Try the environment.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000491 const char *vs120comntools = getenv("VS120COMNTOOLS");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000492 const char *vs100comntools = getenv("VS100COMNTOOLS");
493 const char *vs90comntools = getenv("VS90COMNTOOLS");
494 const char *vs80comntools = getenv("VS80COMNTOOLS");
Alp Tokerfcce1832014-06-22 03:27:45 +0000495
496 const char *vscomntools = nullptr;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000497
Alp Tokera2074402014-06-22 03:27:52 +0000498 // Find any version we can
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000499 if (vs120comntools)
500 vscomntools = vs120comntools;
501 else if (vs100comntools)
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000502 vscomntools = vs100comntools;
503 else if (vs90comntools)
504 vscomntools = vs90comntools;
505 else if (vs80comntools)
506 vscomntools = vs80comntools;
507
508 if (vscomntools && *vscomntools) {
509 const char *p = strstr(vscomntools, "\\Common7\\Tools");
510 path = p ? std::string(vscomntools, p) : vscomntools;
511 return true;
512 }
513 return false;
514}
515
Igor Kudrinf2e75242015-09-24 05:16:36 +0000516void MSVCToolChain::AddSystemIncludeWithSubfolder(
517 const ArgList &DriverArgs, ArgStringList &CC1Args,
518 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
519 const Twine &subfolder3) const {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000520 llvm::SmallString<128> path(folder);
Igor Kudrinf2e75242015-09-24 05:16:36 +0000521 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
Yaron Keren92e1b622015-03-18 10:17:07 +0000522 addSystemInclude(DriverArgs, CC1Args, path);
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000523}
524
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000525void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
526 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000527 if (DriverArgs.hasArg(options::OPT_nostdinc))
528 return;
529
530 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000531 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
532 "include");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000533 }
534
Nico Weberfd3e1ad2016-04-12 19:04:37 +0000535 // Add %INCLUDE%-like directories from the -imsvc flag.
536 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
537 addSystemInclude(DriverArgs, CC1Args, Path);
538
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000539 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
540 return;
541
Joao Matos792d7af2012-09-04 17:29:52 +0000542 // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
543 if (const char *cl_include_dir = getenv("INCLUDE")) {
544 SmallVector<StringRef, 8> Dirs;
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000545 StringRef(cl_include_dir)
546 .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
547 for (StringRef Dir : Dirs)
548 addSystemInclude(DriverArgs, CC1Args, Dir);
549 if (!Dirs.empty())
550 return;
Joao Matos792d7af2012-09-04 17:29:52 +0000551 }
552
553 std::string VSDir;
Joao Matos792d7af2012-09-04 17:29:52 +0000554
555 // When built with access to the proper Windows APIs, try to actually find
556 // the correct include paths first.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000557 if (getVisualStudioInstallDir(VSDir)) {
558 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, VSDir, "VC\\include");
559
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000560 if (useUniversalCRT(VSDir)) {
561 std::string UniversalCRTSdkPath;
562 std::string UCRTVersion;
563 if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000564 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
565 "Include", UCRTVersion, "ucrt");
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000566 }
567 }
568
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000569 std::string WindowsSDKDir;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000570 int major;
571 std::string windowsSDKIncludeVersion;
572 std::string windowsSDKLibVersion;
573 if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
574 windowsSDKLibVersion)) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000575 if (major >= 8) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000576 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
577 // Anyway, llvm::sys::path::append is able to manage it.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000578 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000579 "include", windowsSDKIncludeVersion,
580 "shared");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000581 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000582 "include", windowsSDKIncludeVersion,
583 "um");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000584 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000585 "include", windowsSDKIncludeVersion,
586 "winrt");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000587 } else {
588 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
589 "include");
590 }
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000591 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000592 addSystemInclude(DriverArgs, CC1Args, VSDir);
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000593 }
Joao Matos792d7af2012-09-04 17:29:52 +0000594 return;
595 }
Joao Matos792d7af2012-09-04 17:29:52 +0000596
597 // As a fallback, select default install paths.
Alp Tokerfcce1832014-06-22 03:27:45 +0000598 // FIXME: Don't guess drives and paths like this on Windows.
Joao Matos792d7af2012-09-04 17:29:52 +0000599 const StringRef Paths[] = {
600 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
601 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
602 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
603 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
604 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
605 };
606 addSystemIncludes(DriverArgs, CC1Args, Paths);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000607}
608
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000609void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
610 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000611 // FIXME: There should probably be logic here to find libc++ on Windows.
612}
David Majnemere11d3732015-06-08 00:22:46 +0000613
614std::string
615MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
616 types::ID InputType) const {
617 std::string TripleStr =
618 ToolChain::ComputeEffectiveClangTriple(Args, InputType);
619 llvm::Triple Triple(TripleStr);
620 VersionTuple MSVT =
621 tools::visualstudio::getMSVCVersion(/*D=*/nullptr, Triple, Args,
622 /*IsWindowsMSVC=*/true);
623 if (MSVT.empty())
624 return TripleStr;
625
626 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
627 MSVT.getSubminor().getValueOr(0));
628
David Majnemer75fdd6b2015-06-09 06:30:01 +0000629 if (Triple.getEnvironment() == llvm::Triple::MSVC) {
630 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
631 if (ObjFmt.empty())
632 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
633 else
634 Triple.setEnvironmentName(
635 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
636 }
David Majnemere11d3732015-06-08 00:22:46 +0000637 return Triple.getTriple();
638}
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000639
640SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
641 SanitizerMask Res = ToolChain::getSupportedSanitizers();
642 Res |= SanitizerKind::Address;
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000643 return Res;
644}
David Majnemer015ce0f2015-07-27 07:32:11 +0000645
Hans Wennborg21d73d22016-01-12 23:17:03 +0000646static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
647 bool SupportsForcingFramePointer,
648 const char *ExpandChar, const OptTable &Opts) {
649 assert(A->getOption().matches(options::OPT__SLASH_O));
650
651 StringRef OptStr = A->getValue();
652 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
653 const char &OptChar = *(OptStr.data() + I);
654 switch (OptChar) {
655 default:
656 break;
657 case '1':
658 case '2':
659 case 'x':
660 case 'd':
661 if (&OptChar == ExpandChar) {
662 if (OptChar == 'd') {
663 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
664 } else {
665 if (OptChar == '1') {
666 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
667 } else if (OptChar == '2' || OptChar == 'x') {
668 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
669 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
670 }
David Majnemer259d71a2016-01-21 23:01:11 +0000671 if (SupportsForcingFramePointer &&
672 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
Hans Wennborg21d73d22016-01-12 23:17:03 +0000673 DAL.AddFlagArg(A,
674 Opts.getOption(options::OPT_fomit_frame_pointer));
675 if (OptChar == '1' || OptChar == '2')
676 DAL.AddFlagArg(A,
677 Opts.getOption(options::OPT_ffunction_sections));
678 }
679 }
680 break;
681 case 'b':
682 if (I + 1 != E && isdigit(OptStr[I + 1]))
683 ++I;
684 break;
685 case 'g':
686 break;
687 case 'i':
688 if (I + 1 != E && OptStr[I + 1] == '-') {
689 ++I;
690 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
691 } else {
692 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
693 }
694 break;
695 case 's':
696 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
697 break;
698 case 't':
699 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
700 break;
701 case 'y': {
702 bool OmitFramePointer = true;
703 if (I + 1 != E && OptStr[I + 1] == '-') {
704 OmitFramePointer = false;
705 ++I;
706 }
707 if (SupportsForcingFramePointer) {
708 if (OmitFramePointer)
709 DAL.AddFlagArg(A,
710 Opts.getOption(options::OPT_fomit_frame_pointer));
711 else
712 DAL.AddFlagArg(
713 A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
Nico Weber9c3fca32016-03-23 15:37:41 +0000714 } else {
715 // Don't warn about /Oy- in 64-bit builds (where
716 // SupportsForcingFramePointer is false). The flag having no effect
717 // there is a compiler-internal optimization, and people shouldn't have
718 // to special-case their build files for 64-bit clang-cl.
719 A->claim();
Hans Wennborg21d73d22016-01-12 23:17:03 +0000720 }
721 break;
722 }
723 }
724 }
725}
726
727static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
728 const OptTable &Opts) {
729 assert(A->getOption().matches(options::OPT_D));
730
731 StringRef Val = A->getValue();
732 size_t Hash = Val.find('#');
733 if (Hash == StringRef::npos || Hash > Val.find('=')) {
734 DAL.append(A);
735 return;
736 }
737
738 std::string NewVal = Val;
739 NewVal[Hash] = '=';
740 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
741}
742
David Majnemer015ce0f2015-07-27 07:32:11 +0000743llvm::opt::DerivedArgList *
744MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
745 const char *BoundArch) const {
746 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
747 const OptTable &Opts = getDriver().getOpts();
748
David Majnemer7ab76f22015-08-25 00:46:45 +0000749 // /Oy and /Oy- only has an effect under X86-32.
750 bool SupportsForcingFramePointer = getArch() == llvm::Triple::x86;
751
David Majnemer015ce0f2015-07-27 07:32:11 +0000752 // The -O[12xd] flag actually expands to several flags. We must desugar the
753 // flags so that options embedded can be negated. For example, the '-O2' flag
754 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
755 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
756 // aspect of '-O2'.
757 //
758 // Note that this expansion logic only applies to the *last* of '[12xd]'.
759
760 // First step is to search for the character we'd like to expand.
761 const char *ExpandChar = nullptr;
762 for (Arg *A : Args) {
763 if (!A->getOption().matches(options::OPT__SLASH_O))
764 continue;
765 StringRef OptStr = A->getValue();
766 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
767 const char &OptChar = *(OptStr.data() + I);
768 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
769 ExpandChar = OptStr.data() + I;
770 }
771 }
772
David Majnemer015ce0f2015-07-27 07:32:11 +0000773 for (Arg *A : Args) {
Hans Wennborg21d73d22016-01-12 23:17:03 +0000774 if (A->getOption().matches(options::OPT__SLASH_O)) {
775 // The -O flag actually takes an amalgam of other options. For example,
776 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
777 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
778 } else if (A->getOption().matches(options::OPT_D)) {
779 // Translate -Dfoo#bar into -Dfoo=bar.
780 TranslateDArg(A, *DAL, Opts);
781 } else {
David Majnemer015ce0f2015-07-27 07:32:11 +0000782 DAL->append(A);
David Majnemer015ce0f2015-07-27 07:32:11 +0000783 }
784 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000785
David Majnemer015ce0f2015-07-27 07:32:11 +0000786 return DAL;
787}