blob: 95cf056f7a741d7a0c849d95aec13d85c0a586f1 [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"
David L. Jones24fb20c2016-12-07 23:41:58 +000019#include "llvm/ADT/StringSwitch.h"
Alp Tokerf1ffc842014-06-22 04:31:15 +000020#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000021#include "llvm/Option/Arg.h"
22#include "llvm/Option/ArgList.h"
Adrian McCarthye4b26fc2016-05-13 23:20:11 +000023#include "llvm/Support/ConvertUTF.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000024#include "llvm/Support/ErrorHandling.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000025#include "llvm/Support/FileSystem.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000026#include "llvm/Support/Path.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000027#include "llvm/Support/Process.h"
Reid Kleckner6b7156b2015-01-23 19:16:25 +000028#include <cstdio>
29
Chandler Carruth1fc603e2011-12-17 23:10:01 +000030// Include the necessary headers to interface with the Windows registry and
31// environment.
Alp Tokerf1ffc842014-06-22 04:31:15 +000032#if defined(LLVM_ON_WIN32)
Alp Tokerfcce1832014-06-22 03:27:45 +000033#define USE_WIN32
34#endif
35
36#ifdef USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +000037 #define WIN32_LEAN_AND_MEAN
38 #define NOGDI
Yaron Keren7fc6f1e2014-12-04 21:46:50 +000039 #ifndef NOMINMAX
40 #define NOMINMAX
41 #endif
Logan Chien733e3c62014-06-24 16:18:10 +000042 #include <windows.h>
Chandler Carruth1fc603e2011-12-17 23:10:01 +000043#endif
44
45using namespace clang::driver;
46using namespace clang::driver::toolchains;
47using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000048using namespace llvm::opt;
Chandler Carruth1fc603e2011-12-17 23:10:01 +000049
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000050MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple& Triple,
51 const ArgList &Args)
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000052 : ToolChain(D, Triple, Args) {
Zachary Turner719f58c2014-12-01 23:06:47 +000053 getProgramPaths().push_back(getDriver().getInstalledDir());
54 if (getDriver().getInstalledDir() != getDriver().Dir)
55 getProgramPaths().push_back(getDriver().Dir);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000056}
57
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000058Tool *MSVCToolChain::buildLinker() const {
Douglas Katzman95354292015-06-23 20:42:09 +000059 return new tools::visualstudio::Linker(*this);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000060}
61
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000062Tool *MSVCToolChain::buildAssembler() const {
Saleem Abdulrasool377066a2014-03-27 22:50:18 +000063 if (getTriple().isOSBinFormatMachO())
Douglas Katzman95354292015-06-23 20:42:09 +000064 return new tools::darwin::Assembler(*this);
Alp Tokerc8d4f0f2013-11-22 08:27:46 +000065 getDriver().Diag(clang::diag::err_no_external_assembler);
Craig Topper92fc2df2014-05-17 16:56:41 +000066 return nullptr;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000067}
68
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000069bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000070 return true;
71}
72
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000073bool MSVCToolChain::IsUnwindTablesDefault() const {
Reid Kleckner6b3a9402014-09-04 18:13:12 +000074 // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
75 // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
76 // how to generate them yet.
Akira Hatanakae4218132016-05-05 01:41:07 +000077
78 // Don't emit unwind tables by default for MachO targets.
79 if (getTriple().isOSBinFormatMachO())
80 return false;
81
Reid Kleckner6b3a9402014-09-04 18:13:12 +000082 return getArch() == llvm::Triple::x86_64;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000083}
84
Reid Kleckner8c190832016-12-28 17:41:36 +000085bool MSVCToolChain::isPICDefault() const {
86 return getArch() == llvm::Triple::x86_64;
87}
88
89bool MSVCToolChain::isPIEDefault() const {
90 return false;
91}
92
93bool MSVCToolChain::isPICDefaultForced() const {
94 return getArch() == llvm::Triple::x86_64;
95}
96
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000097#ifdef USE_WIN32
98static bool readFullStringValue(HKEY hkey, const char *valueName,
99 std::string &value) {
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000100 std::wstring WideValueName;
101 if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
102 return false;
103
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000104 DWORD result = 0;
105 DWORD valueSize = 0;
106 DWORD type = 0;
107 // First just query for the required size.
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000108 result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
109 &valueSize);
110 if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000111 return false;
112 std::vector<BYTE> buffer(valueSize);
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000113 result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
114 &valueSize);
115 if (result == ERROR_SUCCESS) {
116 std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
117 valueSize / sizeof(wchar_t));
Zachary Turnere78a3472016-07-28 17:13:32 +0000118 if (valueSize && WideValue.back() == L'\0') {
Etienne Bergeron982a3bc2016-08-30 18:38:25 +0000119 WideValue.pop_back();
Zachary Turnere78a3472016-07-28 17:13:32 +0000120 }
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000121 // The destination buffer must be empty as an invariant of the conversion
122 // function; but this function is sometimes called in a loop that passes in
123 // the same buffer, however. Simply clear it out so we can overwrite it.
124 value.clear();
125 return llvm::convertWideToUTF8(WideValue, value);
126 }
127 return false;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000128}
129#endif
130
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000131/// \brief Read registry string.
132/// This also supports a means to look for high-versioned keys by use
133/// of a $VERSION placeholder in the key path.
134/// $VERSION in the key path is a placeholder for the version number,
135/// causing the highest value path to be searched for and used.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000136/// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
137/// There can be additional characters in the component. Only the numeric
138/// characters are compared. This function only searches HKLM.
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000139static bool getSystemRegistryString(const char *keyPath, const char *valueName,
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000140 std::string &value, std::string *phValue) {
Alp Tokerfcce1832014-06-22 03:27:45 +0000141#ifndef USE_WIN32
142 return false;
143#else
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000144 HKEY hRootKey = HKEY_LOCAL_MACHINE;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000145 HKEY hKey = NULL;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000146 long lResult;
147 bool returnValue = false;
148
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000149 const char *placeHolder = strstr(keyPath, "$VERSION");
150 std::string bestName;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000151 // If we have a $VERSION placeholder, do the highest-version search.
152 if (placeHolder) {
153 const char *keyEnd = placeHolder - 1;
154 const char *nextKey = placeHolder;
155 // Find end of previous key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000156 while ((keyEnd > keyPath) && (*keyEnd != '\\'))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000157 keyEnd--;
158 // Find end of key containing $VERSION.
159 while (*nextKey && (*nextKey != '\\'))
160 nextKey++;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000161 size_t partialKeyLength = keyEnd - keyPath;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000162 char partialKey[256];
Daniel Marjamakie1146692016-01-27 07:33:50 +0000163 if (partialKeyLength >= sizeof(partialKey))
164 partialKeyLength = sizeof(partialKey) - 1;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000165 strncpy(partialKey, keyPath, partialKeyLength);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000166 partialKey[partialKeyLength] = '\0';
167 HKEY hTopKey = NULL;
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000168 lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
169 &hTopKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000170 if (lResult == ERROR_SUCCESS) {
171 char keyName[256];
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000172 double bestValue = 0.0;
173 DWORD index, size = sizeof(keyName) - 1;
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000174 for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
175 NULL, NULL) == ERROR_SUCCESS;
176 index++) {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000177 const char *sp = keyName;
Jordan Rosea7d03842013-02-08 22:30:41 +0000178 while (*sp && !isDigit(*sp))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000179 sp++;
180 if (!*sp)
181 continue;
182 const char *ep = sp + 1;
Jordan Rosea7d03842013-02-08 22:30:41 +0000183 while (*ep && (isDigit(*ep) || (*ep == '.')))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000184 ep++;
185 char numBuf[32];
186 strncpy(numBuf, sp, sizeof(numBuf) - 1);
187 numBuf[sizeof(numBuf) - 1] = '\0';
Hans Wennborgd2192312013-10-10 18:03:08 +0000188 double dvalue = strtod(numBuf, NULL);
189 if (dvalue > bestValue) {
190 // Test that InstallDir is indeed there before keeping this index.
191 // Open the chosen key path remainder.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000192 bestName = keyName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000193 // Append rest of key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000194 bestName.append(nextKey);
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000195 lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
196 KEY_READ | KEY_WOW64_32KEY, &hKey);
Hans Wennborgd2192312013-10-10 18:03:08 +0000197 if (lResult == ERROR_SUCCESS) {
Zachary Turnere78a3472016-07-28 17:13:32 +0000198 if (readFullStringValue(hKey, valueName, value)) {
Hans Wennborgd2192312013-10-10 18:03:08 +0000199 bestValue = dvalue;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000200 if (phValue)
201 *phValue = bestName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000202 returnValue = true;
203 }
204 RegCloseKey(hKey);
205 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000206 }
207 size = sizeof(keyName) - 1;
208 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000209 RegCloseKey(hTopKey);
210 }
211 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000212 lResult =
Aaron Ballmanb06a3592016-06-23 14:33:53 +0000213 RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000214 if (lResult == ERROR_SUCCESS) {
Zachary Turnere78a3472016-07-28 17:13:32 +0000215 if (readFullStringValue(hKey, valueName, value))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000216 returnValue = true;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000217 if (phValue)
218 phValue->clear();
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000219 RegCloseKey(hKey);
220 }
221 }
222 return returnValue;
Alp Tokerfcce1832014-06-22 03:27:45 +0000223#endif // USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000224}
225
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000226// Convert LLVM's ArchType
227// to the corresponding name of Windows SDK libraries subfolder
228static StringRef getWindowsSDKArch(llvm::Triple::ArchType Arch) {
229 switch (Arch) {
230 case llvm::Triple::x86:
231 return "x86";
232 case llvm::Triple::x86_64:
233 return "x64";
234 case llvm::Triple::arm:
235 return "arm";
236 default:
237 return "";
238 }
239}
240
Igor Kudrinf2e75242015-09-24 05:16:36 +0000241// Find the most recent version of Universal CRT or Windows 10 SDK.
242// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
243// directory by name and uses the last one of the list.
244// So we compare entry names lexicographically to find the greatest one.
245static bool getWindows10SDKVersion(const std::string &SDKPath,
246 std::string &SDKVersion) {
247 SDKVersion.clear();
248
249 std::error_code EC;
250 llvm::SmallString<128> IncludePath(SDKPath);
251 llvm::sys::path::append(IncludePath, "Include");
252 for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
253 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
254 if (!llvm::sys::fs::is_directory(DirIt->path()))
255 continue;
256 StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
257 // If WDK is installed, there could be subfolders like "wdf" in the
258 // "Include" directory.
259 // Allow only directories which names start with "10.".
260 if (!CandidateName.startswith("10."))
261 continue;
262 if (CandidateName > SDKVersion)
263 SDKVersion = CandidateName;
264 }
265
266 return !SDKVersion.empty();
267}
268
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000269/// \brief Get Windows SDK installation directory.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000270bool MSVCToolChain::getWindowsSDKDir(std::string &Path, int &Major,
271 std::string &WindowsSDKIncludeVersion,
272 std::string &WindowsSDKLibVersion) const {
273 std::string RegistrySDKVersion;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000274 // Try the Windows registry.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000275 if (!getSystemRegistryString(
276 "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
277 "InstallationFolder", Path, &RegistrySDKVersion))
278 return false;
279 if (Path.empty() || RegistrySDKVersion.empty())
280 return false;
281
282 WindowsSDKIncludeVersion.clear();
283 WindowsSDKLibVersion.clear();
284 Major = 0;
285 std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
286 if (Major <= 7)
287 return true;
288 if (Major == 8) {
289 // Windows SDK 8.x installs libraries in a folder whose names depend on the
290 // version of the OS you're targeting. By default choose the newest, which
291 // usually corresponds to the version of the OS you've installed the SDK on.
292 const char *Tests[] = {"winv6.3", "win8", "win7"};
293 for (const char *Test : Tests) {
294 llvm::SmallString<128> TestPath(Path);
295 llvm::sys::path::append(TestPath, "Lib", Test);
296 if (llvm::sys::fs::exists(TestPath.c_str())) {
297 WindowsSDKLibVersion = Test;
298 break;
299 }
300 }
301 return !WindowsSDKLibVersion.empty();
302 }
303 if (Major == 10) {
304 if (!getWindows10SDKVersion(Path, WindowsSDKIncludeVersion))
305 return false;
306 WindowsSDKLibVersion = WindowsSDKIncludeVersion;
307 return true;
308 }
309 // Unsupported SDK version
310 return false;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000311}
312
Zachary Turner10d75b22014-10-22 20:40:43 +0000313// Gets the library path required to link against the Windows SDK.
314bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
315 std::string sdkPath;
316 int sdkMajor = 0;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000317 std::string windowsSDKIncludeVersion;
318 std::string windowsSDKLibVersion;
Zachary Turner10d75b22014-10-22 20:40:43 +0000319
320 path.clear();
Igor Kudrinf2e75242015-09-24 05:16:36 +0000321 if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
322 windowsSDKLibVersion))
Zachary Turner10d75b22014-10-22 20:40:43 +0000323 return false;
324
325 llvm::SmallString<128> libPath(sdkPath);
326 llvm::sys::path::append(libPath, "Lib");
327 if (sdkMajor <= 7) {
328 switch (getArch()) {
329 // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
330 case llvm::Triple::x86:
331 break;
332 case llvm::Triple::x86_64:
333 llvm::sys::path::append(libPath, "x64");
334 break;
335 case llvm::Triple::arm:
336 // It is not necessary to link against Windows SDK 7.x when targeting ARM.
337 return false;
338 default:
339 return false;
340 }
341 } else {
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000342 const StringRef archName = getWindowsSDKArch(getArch());
343 if (archName.empty())
Zachary Turner10d75b22014-10-22 20:40:43 +0000344 return false;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000345 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um", archName);
Zachary Turner10d75b22014-10-22 20:40:43 +0000346 }
347
348 path = libPath.str();
349 return true;
350}
351
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000352// Check if the Include path of a specified version of Visual Studio contains
353// specific header files. If not, they are probably shipped with Universal CRT.
354bool clang::driver::toolchains::MSVCToolChain::useUniversalCRT(
355 std::string &VisualStudioDir) const {
356 llvm::SmallString<128> TestPath(VisualStudioDir);
357 llvm::sys::path::append(TestPath, "VC\\include\\stdlib.h");
358
359 return !llvm::sys::fs::exists(TestPath);
360}
361
362bool MSVCToolChain::getUniversalCRTSdkDir(std::string &Path,
363 std::string &UCRTVersion) const {
364 // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
365 // for the specific key "KitsRoot10". So do we.
366 if (!getSystemRegistryString(
367 "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
368 Path, nullptr))
369 return false;
370
Igor Kudrinf2e75242015-09-24 05:16:36 +0000371 return getWindows10SDKVersion(Path, UCRTVersion);
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000372}
373
374bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
375 std::string UniversalCRTSdkPath;
376 std::string UCRTVersion;
377
378 Path.clear();
379 if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
380 return false;
381
382 StringRef ArchName = getWindowsSDKArch(getArch());
383 if (ArchName.empty())
384 return false;
385
386 llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
387 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
388
389 Path = LibPath.str();
390 return true;
391}
392
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000393// Get the location to use for Visual Studio binaries. The location priority
394// is: %VCINSTALLDIR% > %PATH% > newest copy of Visual Studio installed on
395// system (as reported by the registry).
396bool MSVCToolChain::getVisualStudioBinariesFolder(const char *clangProgramPath,
397 std::string &path) const {
398 path.clear();
399
400 SmallString<128> BinDir;
401
402 // First check the environment variables that vsvars32.bat sets.
403 llvm::Optional<std::string> VcInstallDir =
404 llvm::sys::Process::GetEnv("VCINSTALLDIR");
405 if (VcInstallDir.hasValue()) {
406 BinDir = VcInstallDir.getValue();
407 llvm::sys::path::append(BinDir, "bin");
408 } else {
409 // Next walk the PATH, trying to find a cl.exe in the path. If we find one,
410 // use that. However, make sure it's not clang's cl.exe.
411 llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
412 if (OptPath.hasValue()) {
413 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
414 SmallVector<StringRef, 8> PathSegments;
415 llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
416
417 for (StringRef PathSegment : PathSegments) {
418 if (PathSegment.empty())
419 continue;
420
421 SmallString<128> FilePath(PathSegment);
422 llvm::sys::path::append(FilePath, "cl.exe");
Adrian McCarthy8e0879a92016-05-20 15:46:23 +0000423 // Checking if cl.exe exists is a small optimization over calling
424 // can_execute, which really only checks for existence but will also do
425 // extra checks for cl.exe.exe. These add up when walking a long path.
426 if (llvm::sys::fs::exists(FilePath.c_str()) &&
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000427 !llvm::sys::fs::equivalent(FilePath.c_str(), clangProgramPath)) {
428 // If we found it on the PATH, use it exactly as is with no
429 // modifications.
430 path = PathSegment;
431 return true;
432 }
433 }
434 }
435
436 std::string installDir;
437 // With no VCINSTALLDIR and nothing on the PATH, if we can't find it in the
438 // registry then we have no choice but to fail.
439 if (!getVisualStudioInstallDir(installDir))
440 return false;
441
442 // Regardless of what binary we're ultimately trying to find, we make sure
443 // that this is a Visual Studio directory by checking for cl.exe. We use
444 // cl.exe instead of other binaries like link.exe because programs such as
445 // GnuWin32 also have a utility called link.exe, so cl.exe is the least
446 // ambiguous.
447 BinDir = installDir;
448 llvm::sys::path::append(BinDir, "VC", "bin");
449 SmallString<128> ClPath(BinDir);
450 llvm::sys::path::append(ClPath, "cl.exe");
451
452 if (!llvm::sys::fs::can_execute(ClPath.c_str()))
453 return false;
Hans Wennborge6b994e2014-10-20 23:26:03 +0000454 }
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000455
456 if (BinDir.empty())
457 return false;
458
459 switch (getArch()) {
460 case llvm::Triple::x86:
461 break;
462 case llvm::Triple::x86_64:
463 llvm::sys::path::append(BinDir, "amd64");
464 break;
465 case llvm::Triple::arm:
466 llvm::sys::path::append(BinDir, "arm");
467 break;
468 default:
469 // Whatever this is, Visual Studio doesn't have a toolchain for it.
470 return false;
471 }
472 path = BinDir.str();
473 return true;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000474}
475
David L. Jones24fb20c2016-12-07 23:41:58 +0000476VersionTuple MSVCToolChain::getMSVCVersionFromTriple() const {
477 unsigned Major, Minor, Micro;
478 getTriple().getEnvironmentVersion(Major, Minor, Micro);
479 if (Major || Minor || Micro)
480 return VersionTuple(Major, Minor, Micro);
481 return VersionTuple();
482}
483
Adrian McCarthye4b26fc2016-05-13 23:20:11 +0000484VersionTuple MSVCToolChain::getMSVCVersionFromExe() const {
485 VersionTuple Version;
486#ifdef USE_WIN32
487 std::string BinPath;
488 if (!getVisualStudioBinariesFolder("", BinPath))
489 return Version;
NAKAMURA Takumi4b8e3e52016-05-14 08:09:12 +0000490 SmallString<128> ClExe(BinPath);
Adrian McCarthye4b26fc2016-05-13 23:20:11 +0000491 llvm::sys::path::append(ClExe, "cl.exe");
492
493 std::wstring ClExeWide;
494 if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
495 return Version;
496
497 const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
498 nullptr);
499 if (VersionSize == 0)
500 return Version;
501
502 SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
503 if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
504 VersionBlock.data()))
505 return Version;
506
507 VS_FIXEDFILEINFO *FileInfo = nullptr;
508 UINT FileInfoSize = 0;
509 if (!::VerQueryValueW(VersionBlock.data(), L"\\",
510 reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
511 FileInfoSize < sizeof(*FileInfo))
512 return Version;
513
514 const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
515 const unsigned Minor = (FileInfo->dwFileVersionMS ) & 0xFFFF;
516 const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
517
518 Version = VersionTuple(Major, Minor, Micro);
519#endif
520 return Version;
521}
522
Alp Tokerfcce1832014-06-22 03:27:45 +0000523// Get Visual Studio installation directory.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000524bool MSVCToolChain::getVisualStudioInstallDir(std::string &path) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000525 // First check the environment variables that vsvars32.bat sets.
David Majnemer85c25b42016-07-24 17:44:03 +0000526 if (llvm::Optional<std::string> VcInstallDir =
527 llvm::sys::Process::GetEnv("VCINSTALLDIR")) {
528 path = std::move(*VcInstallDir);
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000529 path = path.substr(0, path.find("\\VC"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000530 return true;
531 }
532
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000533 std::string vsIDEInstallDir;
534 std::string vsExpressIDEInstallDir;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000535 // Then try the windows registry.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000536 bool hasVCDir =
537 getSystemRegistryString("SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
538 "InstallDir", vsIDEInstallDir, nullptr);
539 if (hasVCDir && !vsIDEInstallDir.empty()) {
540 path = vsIDEInstallDir.substr(0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000541 return true;
542 }
543
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000544 bool hasVCExpressDir =
545 getSystemRegistryString("SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
546 "InstallDir", vsExpressIDEInstallDir, nullptr);
547 if (hasVCExpressDir && !vsExpressIDEInstallDir.empty()) {
548 path = vsExpressIDEInstallDir.substr(
549 0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000550 return true;
551 }
552
553 // Try the environment.
David Majnemer85c25b42016-07-24 17:44:03 +0000554 std::string vcomntools;
555 if (llvm::Optional<std::string> vs120comntools =
556 llvm::sys::Process::GetEnv("VS120COMNTOOLS"))
557 vcomntools = std::move(*vs120comntools);
558 else if (llvm::Optional<std::string> vs100comntools =
559 llvm::sys::Process::GetEnv("VS100COMNTOOLS"))
560 vcomntools = std::move(*vs100comntools);
561 else if (llvm::Optional<std::string> vs90comntools =
562 llvm::sys::Process::GetEnv("VS90COMNTOOLS"))
563 vcomntools = std::move(*vs90comntools);
564 else if (llvm::Optional<std::string> vs80comntools =
565 llvm::sys::Process::GetEnv("VS80COMNTOOLS"))
566 vcomntools = std::move(*vs80comntools);
Alp Tokerfcce1832014-06-22 03:27:45 +0000567
David Majnemer85c25b42016-07-24 17:44:03 +0000568 // Find any version we can.
569 if (!vcomntools.empty()) {
570 size_t p = vcomntools.find("\\Common7\\Tools");
571 if (p != std::string::npos)
572 vcomntools.resize(p);
573 path = std::move(vcomntools);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000574 return true;
575 }
576 return false;
577}
578
Igor Kudrinf2e75242015-09-24 05:16:36 +0000579void MSVCToolChain::AddSystemIncludeWithSubfolder(
580 const ArgList &DriverArgs, ArgStringList &CC1Args,
581 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
582 const Twine &subfolder3) const {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000583 llvm::SmallString<128> path(folder);
Igor Kudrinf2e75242015-09-24 05:16:36 +0000584 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
Yaron Keren92e1b622015-03-18 10:17:07 +0000585 addSystemInclude(DriverArgs, CC1Args, path);
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000586}
587
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000588void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
589 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000590 if (DriverArgs.hasArg(options::OPT_nostdinc))
591 return;
592
593 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000594 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
595 "include");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000596 }
597
Nico Weberfd3e1ad2016-04-12 19:04:37 +0000598 // Add %INCLUDE%-like directories from the -imsvc flag.
599 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
600 addSystemInclude(DriverArgs, CC1Args, Path);
601
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000602 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
603 return;
604
Joao Matos792d7af2012-09-04 17:29:52 +0000605 // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
David Majnemer85c25b42016-07-24 17:44:03 +0000606 if (llvm::Optional<std::string> cl_include_dir =
607 llvm::sys::Process::GetEnv("INCLUDE")) {
Joao Matos792d7af2012-09-04 17:29:52 +0000608 SmallVector<StringRef, 8> Dirs;
David Majnemer85c25b42016-07-24 17:44:03 +0000609 StringRef(*cl_include_dir)
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000610 .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
611 for (StringRef Dir : Dirs)
612 addSystemInclude(DriverArgs, CC1Args, Dir);
613 if (!Dirs.empty())
614 return;
Joao Matos792d7af2012-09-04 17:29:52 +0000615 }
616
617 std::string VSDir;
Joao Matos792d7af2012-09-04 17:29:52 +0000618
619 // When built with access to the proper Windows APIs, try to actually find
620 // the correct include paths first.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000621 if (getVisualStudioInstallDir(VSDir)) {
622 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, VSDir, "VC\\include");
623
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000624 if (useUniversalCRT(VSDir)) {
625 std::string UniversalCRTSdkPath;
626 std::string UCRTVersion;
627 if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000628 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
629 "Include", UCRTVersion, "ucrt");
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000630 }
631 }
632
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000633 std::string WindowsSDKDir;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000634 int major;
635 std::string windowsSDKIncludeVersion;
636 std::string windowsSDKLibVersion;
637 if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
638 windowsSDKLibVersion)) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000639 if (major >= 8) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000640 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
641 // Anyway, llvm::sys::path::append is able to manage it.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000642 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000643 "include", windowsSDKIncludeVersion,
644 "shared");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000645 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000646 "include", windowsSDKIncludeVersion,
647 "um");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000648 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000649 "include", windowsSDKIncludeVersion,
650 "winrt");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000651 } else {
652 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
653 "include");
654 }
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000655 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000656 addSystemInclude(DriverArgs, CC1Args, VSDir);
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000657 }
Joao Matos792d7af2012-09-04 17:29:52 +0000658 return;
659 }
Joao Matos792d7af2012-09-04 17:29:52 +0000660
David Majnemerd5f7d192016-07-25 04:47:44 +0000661#if defined(LLVM_ON_WIN32)
Joao Matos792d7af2012-09-04 17:29:52 +0000662 // As a fallback, select default install paths.
Alp Tokerfcce1832014-06-22 03:27:45 +0000663 // FIXME: Don't guess drives and paths like this on Windows.
Joao Matos792d7af2012-09-04 17:29:52 +0000664 const StringRef Paths[] = {
665 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
666 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
667 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
668 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
669 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
670 };
671 addSystemIncludes(DriverArgs, CC1Args, Paths);
David Majnemerd5f7d192016-07-25 04:47:44 +0000672#endif
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000673}
674
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000675void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
676 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000677 // FIXME: There should probably be logic here to find libc++ on Windows.
678}
David Majnemere11d3732015-06-08 00:22:46 +0000679
David L. Jones24fb20c2016-12-07 23:41:58 +0000680VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
681 const ArgList &Args) const {
682 bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
683 VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
684 if (MSVT.empty()) MSVT = getMSVCVersionFromTriple();
685 if (MSVT.empty() && IsWindowsMSVC) MSVT = getMSVCVersionFromExe();
686 if (MSVT.empty() &&
687 Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
688 IsWindowsMSVC)) {
689 // -fms-compatibility-version=18.00 is default.
690 // FIXME: Consider bumping this to 19 (MSVC2015) soon.
691 MSVT = VersionTuple(18);
692 }
693 return MSVT;
694}
695
David Majnemere11d3732015-06-08 00:22:46 +0000696std::string
697MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
698 types::ID InputType) const {
David L. Jones24fb20c2016-12-07 23:41:58 +0000699 // The MSVC version doesn't care about the architecture, even though it
700 // may look at the triple internally.
701 VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
David Majnemere11d3732015-06-08 00:22:46 +0000702 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
703 MSVT.getSubminor().getValueOr(0));
704
David L. Jones24fb20c2016-12-07 23:41:58 +0000705 // For the rest of the triple, however, a computed architecture name may
706 // be needed.
707 llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
David Majnemer75fdd6b2015-06-09 06:30:01 +0000708 if (Triple.getEnvironment() == llvm::Triple::MSVC) {
709 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
710 if (ObjFmt.empty())
711 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
712 else
713 Triple.setEnvironmentName(
714 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
715 }
David Majnemere11d3732015-06-08 00:22:46 +0000716 return Triple.getTriple();
717}
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000718
719SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
720 SanitizerMask Res = ToolChain::getSupportedSanitizers();
721 Res |= SanitizerKind::Address;
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000722 return Res;
723}
David Majnemer015ce0f2015-07-27 07:32:11 +0000724
Hans Wennborg21d73d22016-01-12 23:17:03 +0000725static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
726 bool SupportsForcingFramePointer,
727 const char *ExpandChar, const OptTable &Opts) {
728 assert(A->getOption().matches(options::OPT__SLASH_O));
729
730 StringRef OptStr = A->getValue();
731 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
732 const char &OptChar = *(OptStr.data() + I);
733 switch (OptChar) {
734 default:
735 break;
736 case '1':
737 case '2':
738 case 'x':
739 case 'd':
740 if (&OptChar == ExpandChar) {
741 if (OptChar == 'd') {
742 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
743 } else {
744 if (OptChar == '1') {
745 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
746 } else if (OptChar == '2' || OptChar == 'x') {
747 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
748 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
749 }
David Majnemer259d71a2016-01-21 23:01:11 +0000750 if (SupportsForcingFramePointer &&
751 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
Hans Wennborg21d73d22016-01-12 23:17:03 +0000752 DAL.AddFlagArg(A,
753 Opts.getOption(options::OPT_fomit_frame_pointer));
754 if (OptChar == '1' || OptChar == '2')
755 DAL.AddFlagArg(A,
756 Opts.getOption(options::OPT_ffunction_sections));
757 }
758 }
759 break;
760 case 'b':
Hans Wennborg3270bdb2016-05-24 21:23:29 +0000761 if (I + 1 != E && isdigit(OptStr[I + 1])) {
762 switch (OptStr[I + 1]) {
763 case '0':
764 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
765 break;
766 case '1':
Hans Wennborg44d061a2016-06-22 16:56:16 +0000767 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
Hans Wennborg3270bdb2016-05-24 21:23:29 +0000768 break;
769 case '2':
770 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
771 break;
772 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000773 ++I;
Hans Wennborg3270bdb2016-05-24 21:23:29 +0000774 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000775 break;
776 case 'g':
777 break;
778 case 'i':
779 if (I + 1 != E && OptStr[I + 1] == '-') {
780 ++I;
781 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
782 } else {
783 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
784 }
785 break;
786 case 's':
787 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
788 break;
789 case 't':
790 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
791 break;
792 case 'y': {
793 bool OmitFramePointer = true;
794 if (I + 1 != E && OptStr[I + 1] == '-') {
795 OmitFramePointer = false;
796 ++I;
797 }
798 if (SupportsForcingFramePointer) {
799 if (OmitFramePointer)
800 DAL.AddFlagArg(A,
801 Opts.getOption(options::OPT_fomit_frame_pointer));
802 else
803 DAL.AddFlagArg(
804 A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
Nico Weber9c3fca32016-03-23 15:37:41 +0000805 } else {
806 // Don't warn about /Oy- in 64-bit builds (where
807 // SupportsForcingFramePointer is false). The flag having no effect
808 // there is a compiler-internal optimization, and people shouldn't have
809 // to special-case their build files for 64-bit clang-cl.
810 A->claim();
Hans Wennborg21d73d22016-01-12 23:17:03 +0000811 }
812 break;
813 }
814 }
815 }
816}
817
818static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
819 const OptTable &Opts) {
820 assert(A->getOption().matches(options::OPT_D));
821
822 StringRef Val = A->getValue();
823 size_t Hash = Val.find('#');
824 if (Hash == StringRef::npos || Hash > Val.find('=')) {
825 DAL.append(A);
826 return;
827 }
828
829 std::string NewVal = Val;
830 NewVal[Hash] = '=';
831 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
832}
833
David Majnemer015ce0f2015-07-27 07:32:11 +0000834llvm::opt::DerivedArgList *
835MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
Samuel Antao31fef982016-10-27 17:39:44 +0000836 StringRef BoundArch, Action::OffloadKind) const {
David Majnemer015ce0f2015-07-27 07:32:11 +0000837 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
838 const OptTable &Opts = getDriver().getOpts();
839
David Majnemer7ab76f22015-08-25 00:46:45 +0000840 // /Oy and /Oy- only has an effect under X86-32.
841 bool SupportsForcingFramePointer = getArch() == llvm::Triple::x86;
842
David Majnemer015ce0f2015-07-27 07:32:11 +0000843 // The -O[12xd] flag actually expands to several flags. We must desugar the
844 // flags so that options embedded can be negated. For example, the '-O2' flag
845 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
846 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
847 // aspect of '-O2'.
848 //
849 // Note that this expansion logic only applies to the *last* of '[12xd]'.
850
851 // First step is to search for the character we'd like to expand.
852 const char *ExpandChar = nullptr;
853 for (Arg *A : Args) {
854 if (!A->getOption().matches(options::OPT__SLASH_O))
855 continue;
856 StringRef OptStr = A->getValue();
857 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
Hans Wennborgdebfed92016-05-25 00:43:45 +0000858 char OptChar = OptStr[I];
859 char PrevChar = I > 0 ? OptStr[I - 1] : '0';
860 if (PrevChar == 'b') {
861 // OptChar does not expand; it's an argument to the previous char.
862 continue;
863 }
David Majnemer015ce0f2015-07-27 07:32:11 +0000864 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
865 ExpandChar = OptStr.data() + I;
866 }
867 }
868
David Majnemer015ce0f2015-07-27 07:32:11 +0000869 for (Arg *A : Args) {
Hans Wennborg21d73d22016-01-12 23:17:03 +0000870 if (A->getOption().matches(options::OPT__SLASH_O)) {
871 // The -O flag actually takes an amalgam of other options. For example,
872 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
873 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
874 } else if (A->getOption().matches(options::OPT_D)) {
875 // Translate -Dfoo#bar into -Dfoo=bar.
876 TranslateDArg(A, *DAL, Opts);
877 } else {
David Majnemer015ce0f2015-07-27 07:32:11 +0000878 DAL->append(A);
David Majnemer015ce0f2015-07-27 07:32:11 +0000879 }
880 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000881
David Majnemer015ce0f2015-07-27 07:32:11 +0000882 return DAL;
883}