Coverage Report

Created: 2017-03-08 01:53

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/clang/lib/Driver/MSVCToolChain.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- 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"
11
#include "Tools.h"
12
#include "clang/Basic/CharInfo.h"
13
#include "clang/Basic/Version.h"
14
#include "clang/Driver/Compilation.h"
15
#include "clang/Driver/Driver.h"
16
#include "clang/Driver/DriverDiagnostic.h"
17
#include "clang/Driver/Options.h"
18
#include "llvm/ADT/StringExtras.h"
19
#include "llvm/ADT/StringSwitch.h"
20
#include "llvm/Config/llvm-config.h"
21
#include "llvm/Option/Arg.h"
22
#include "llvm/Option/ArgList.h"
23
#include "llvm/Support/ConvertUTF.h"
24
#include "llvm/Support/ErrorHandling.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/Path.h"
27
#include "llvm/Support/Process.h"
28
#include <cstdio>
29
30
// Include the necessary headers to interface with the Windows registry and
31
// environment.
32
#if defined(LLVM_ON_WIN32)
33
#define USE_WIN32
34
#endif
35
36
#ifdef USE_WIN32
37
  #define WIN32_LEAN_AND_MEAN
38
  #define NOGDI
39
  #ifndef NOMINMAX
40
    #define NOMINMAX
41
  #endif
42
  #include <windows.h>
43
#endif
44
45
using namespace clang::driver;
46
using namespace clang::driver::toolchains;
47
using namespace clang;
48
using namespace llvm::opt;
49
50
MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
51
                             const ArgList &Args)
52
488
    : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) {
53
488
  getProgramPaths().push_back(getDriver().getInstalledDir());
54
488
  if (getDriver().getInstalledDir() != getDriver().Dir)
55
478
    getProgramPaths().push_back(getDriver().Dir);
56
488
}
57
58
268
Tool *MSVCToolChain::buildLinker() const {
59
268
  return new tools::visualstudio::Linker(*this);
60
268
}
61
62
3
Tool *MSVCToolChain::buildAssembler() const {
63
3
  if (getTriple().isOSBinFormatMachO())
64
2
    return new tools::darwin::Assembler(*this);
65
1
  getDriver().Diag(clang::diag::err_no_external_assembler);
66
1
  return nullptr;
67
3
}
68
69
2.06k
bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
70
2.06k
  return true;
71
2.06k
}
72
73
492
bool MSVCToolChain::IsUnwindTablesDefault() const {
74
492
  // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
75
492
  // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
76
492
  // how to generate them yet.
77
492
78
492
  // Don't emit unwind tables by default for MachO targets.
79
492
  if (getTriple().isOSBinFormatMachO())
80
5
    return false;
81
492
82
487
  return getArch() == llvm::Triple::x86_64;
83
492
}
84
85
509
bool MSVCToolChain::isPICDefault() const {
86
509
  return getArch() == llvm::Triple::x86_64;
87
509
}
88
89
509
bool MSVCToolChain::isPIEDefault() const {
90
509
  return false;
91
509
}
92
93
501
bool MSVCToolChain::isPICDefaultForced() const {
94
501
  return getArch() == llvm::Triple::x86_64;
95
501
}
96
97
void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
98
4
                                       ArgStringList &CC1Args) const {
99
4
  CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
100
4
}
101
102
2
void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
103
2
  CudaInstallation.print(OS);
104
2
}
105
106
#ifdef USE_WIN32
107
static bool readFullStringValue(HKEY hkey, const char *valueName,
108
                                std::string &value) {
109
  std::wstring WideValueName;
110
  if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
111
    return false;
112
113
  DWORD result = 0;
114
  DWORD valueSize = 0;
115
  DWORD type = 0;
116
  // First just query for the required size.
117
  result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
118
                            &valueSize);
119
  if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
120
    return false;
121
  std::vector<BYTE> buffer(valueSize);
122
  result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
123
                            &valueSize);
124
  if (result == ERROR_SUCCESS) {
125
    std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
126
                           valueSize / sizeof(wchar_t));
127
    if (valueSize && WideValue.back() == L'\0') {
128
      WideValue.pop_back();
129
    }
130
    // The destination buffer must be empty as an invariant of the conversion
131
    // function; but this function is sometimes called in a loop that passes in
132
    // the same buffer, however. Simply clear it out so we can overwrite it.
133
    value.clear();
134
    return llvm::convertWideToUTF8(WideValue, value);
135
  }
136
  return false;
137
}
138
#endif
139
140
/// \brief Read registry string.
141
/// This also supports a means to look for high-versioned keys by use
142
/// of a $VERSION placeholder in the key path.
143
/// $VERSION in the key path is a placeholder for the version number,
144
/// causing the highest value path to be searched for and used.
145
/// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
146
/// There can be additional characters in the component.  Only the numeric
147
/// characters are compared.  This function only searches HKLM.
148
static bool getSystemRegistryString(const char *keyPath, const char *valueName,
149
2.36k
                                    std::string &value, std::string *phValue) {
150
2.36k
#ifndef USE_WIN32
151
2.36k
  return false;
152
2.36k
#else
153
  HKEY hRootKey = HKEY_LOCAL_MACHINE;
154
  HKEY hKey = NULL;
155
  long lResult;
156
  bool returnValue = false;
157
158
  const char *placeHolder = strstr(keyPath, "$VERSION");
159
  std::string bestName;
160
  // If we have a $VERSION placeholder, do the highest-version search.
161
  if (placeHolder) {
162
    const char *keyEnd = placeHolder - 1;
163
    const char *nextKey = placeHolder;
164
    // Find end of previous key.
165
    while ((keyEnd > keyPath) && (*keyEnd != '\\'))
166
      keyEnd--;
167
    // Find end of key containing $VERSION.
168
    while (*nextKey && (*nextKey != '\\'))
169
      nextKey++;
170
    size_t partialKeyLength = keyEnd - keyPath;
171
    char partialKey[256];
172
    if (partialKeyLength >= sizeof(partialKey))
173
      partialKeyLength = sizeof(partialKey) - 1;
174
    strncpy(partialKey, keyPath, partialKeyLength);
175
    partialKey[partialKeyLength] = '\0';
176
    HKEY hTopKey = NULL;
177
    lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
178
                            &hTopKey);
179
    if (lResult == ERROR_SUCCESS) {
180
      char keyName[256];
181
      double bestValue = 0.0;
182
      DWORD index, size = sizeof(keyName) - 1;
183
      for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
184
                                    NULL, NULL) == ERROR_SUCCESS;
185
           index++) {
186
        const char *sp = keyName;
187
        while (*sp && !isDigit(*sp))
188
          sp++;
189
        if (!*sp)
190
          continue;
191
        const char *ep = sp + 1;
192
        while (*ep && (isDigit(*ep) || (*ep == '.')))
193
          ep++;
194
        char numBuf[32];
195
        strncpy(numBuf, sp, sizeof(numBuf) - 1);
196
        numBuf[sizeof(numBuf) - 1] = '\0';
197
        double dvalue = strtod(numBuf, NULL);
198
        if (dvalue > bestValue) {
199
          // Test that InstallDir is indeed there before keeping this index.
200
          // Open the chosen key path remainder.
201
          bestName = keyName;
202
          // Append rest of key.
203
          bestName.append(nextKey);
204
          lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
205
                                  KEY_READ | KEY_WOW64_32KEY, &hKey);
206
          if (lResult == ERROR_SUCCESS) {
207
            if (readFullStringValue(hKey, valueName, value)) {
208
              bestValue = dvalue;
209
              if (phValue)
210
                *phValue = bestName;
211
              returnValue = true;
212
            }
213
            RegCloseKey(hKey);
214
          }
215
        }
216
        size = sizeof(keyName) - 1;
217
      }
218
      RegCloseKey(hTopKey);
219
    }
220
  } else {
221
    lResult =
222
        RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
223
    if (lResult == ERROR_SUCCESS) {
224
      if (readFullStringValue(hKey, valueName, value))
225
        returnValue = true;
226
      if (phValue)
227
        phValue->clear();
228
      RegCloseKey(hKey);
229
    }
230
  }
231
  return returnValue;
232
#endif // USE_WIN32
233
2.36k
}
234
235
// Convert LLVM's ArchType
236
// to the corresponding name of Windows SDK libraries subfolder
237
static StringRef getWindowsSDKArch(llvm::Triple::ArchType Arch) {
238
  switch (Arch) {
239
  case llvm::Triple::x86:
240
    return "x86";
241
  case llvm::Triple::x86_64:
242
    return "x64";
243
  case llvm::Triple::arm:
244
    return "arm";
245
  default:
246
    return "";
247
  }
248
}
249
250
// Find the most recent version of Universal CRT or Windows 10 SDK.
251
// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
252
// directory by name and uses the last one of the list.
253
// So we compare entry names lexicographically to find the greatest one.
254
static bool getWindows10SDKVersion(const std::string &SDKPath,
255
0
                                   std::string &SDKVersion) {
256
0
  SDKVersion.clear();
257
0
258
0
  std::error_code EC;
259
0
  llvm::SmallString<128> IncludePath(SDKPath);
260
0
  llvm::sys::path::append(IncludePath, "Include");
261
0
  for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
262
0
       
DirIt != DirEnd && 0
!EC0
;
DirIt.increment(EC)0
)
{0
263
0
    if (!llvm::sys::fs::is_directory(DirIt->path()))
264
0
      continue;
265
0
    StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
266
0
    // If WDK is installed, there could be subfolders like "wdf" in the
267
0
    // "Include" directory.
268
0
    // Allow only directories which names start with "10.".
269
0
    if (!CandidateName.startswith("10."))
270
0
      continue;
271
0
    
if (0
CandidateName > SDKVersion0
)
272
0
      SDKVersion = CandidateName;
273
0
  }
274
0
275
0
  return !SDKVersion.empty();
276
0
}
277
278
/// \brief Get Windows SDK installation directory.
279
bool MSVCToolChain::getWindowsSDKDir(std::string &Path, int &Major,
280
                                     std::string &WindowsSDKIncludeVersion,
281
266
                                     std::string &WindowsSDKLibVersion) const {
282
266
  std::string RegistrySDKVersion;
283
266
  // Try the Windows registry.
284
266
  if (!getSystemRegistryString(
285
266
          "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
286
266
          "InstallationFolder", Path, &RegistrySDKVersion))
287
266
    return false;
288
0
  
if (0
Path.empty() || 0
RegistrySDKVersion.empty()0
)
289
0
    return false;
290
0
291
0
  WindowsSDKIncludeVersion.clear();
292
0
  WindowsSDKLibVersion.clear();
293
0
  Major = 0;
294
0
  std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
295
0
  if (Major <= 7)
296
0
    return true;
297
0
  
if (0
Major == 80
)
{0
298
0
    // Windows SDK 8.x installs libraries in a folder whose names depend on the
299
0
    // version of the OS you're targeting.  By default choose the newest, which
300
0
    // usually corresponds to the version of the OS you've installed the SDK on.
301
0
    const char *Tests[] = {"winv6.3", "win8", "win7"};
302
0
    for (const char *Test : Tests) {
303
0
      llvm::SmallString<128> TestPath(Path);
304
0
      llvm::sys::path::append(TestPath, "Lib", Test);
305
0
      if (
llvm::sys::fs::exists(TestPath.c_str())0
)
{0
306
0
        WindowsSDKLibVersion = Test;
307
0
        break;
308
0
      }
309
0
    }
310
0
    return !WindowsSDKLibVersion.empty();
311
0
  }
312
0
  
if (0
Major == 100
)
{0
313
0
    if (!getWindows10SDKVersion(Path, WindowsSDKIncludeVersion))
314
0
      return false;
315
0
    WindowsSDKLibVersion = WindowsSDKIncludeVersion;
316
0
    return true;
317
0
  }
318
0
  // Unsupported SDK version
319
0
  return false;
320
0
}
321
322
// Gets the library path required to link against the Windows SDK.
323
266
bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
324
266
  std::string sdkPath;
325
266
  int sdkMajor = 0;
326
266
  std::string windowsSDKIncludeVersion;
327
266
  std::string windowsSDKLibVersion;
328
266
329
266
  path.clear();
330
266
  if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
331
266
                        windowsSDKLibVersion))
332
266
    return false;
333
266
334
0
  llvm::SmallString<128> libPath(sdkPath);
335
0
  llvm::sys::path::append(libPath, "Lib");
336
0
  if (
sdkMajor <= 70
)
{0
337
0
    switch (getArch()) {
338
0
    // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
339
0
    case llvm::Triple::x86:
340
0
      break;
341
0
    case llvm::Triple::x86_64:
342
0
      llvm::sys::path::append(libPath, "x64");
343
0
      break;
344
0
    case llvm::Triple::arm:
345
0
      // It is not necessary to link against Windows SDK 7.x when targeting ARM.
346
0
      return false;
347
0
    default:
348
0
      return false;
349
0
    }
350
0
  } else {
351
0
    const StringRef archName = getWindowsSDKArch(getArch());
352
0
    if (archName.empty())
353
0
      return false;
354
0
    llvm::sys::path::append(libPath, windowsSDKLibVersion, "um", archName);
355
0
  }
356
0
357
0
  path = libPath.str();
358
0
  return true;
359
0
}
360
361
// Check if the Include path of a specified version of Visual Studio contains
362
// specific header files. If not, they are probably shipped with Universal CRT.
363
bool clang::driver::toolchains::MSVCToolChain::useUniversalCRT(
364
0
    std::string &VisualStudioDir) const {
365
0
  llvm::SmallString<128> TestPath(VisualStudioDir);
366
0
  llvm::sys::path::append(TestPath, "VC\\include\\stdlib.h");
367
0
368
0
  return !llvm::sys::fs::exists(TestPath);
369
0
}
370
371
bool MSVCToolChain::getUniversalCRTSdkDir(std::string &Path,
372
0
                                          std::string &UCRTVersion) const {
373
0
  // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
374
0
  // for the specific key "KitsRoot10". So do we.
375
0
  if (!getSystemRegistryString(
376
0
          "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
377
0
          Path, nullptr))
378
0
    return false;
379
0
380
0
  return getWindows10SDKVersion(Path, UCRTVersion);
381
0
}
382
383
0
bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
384
0
  std::string UniversalCRTSdkPath;
385
0
  std::string UCRTVersion;
386
0
387
0
  Path.clear();
388
0
  if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
389
0
    return false;
390
0
391
0
  StringRef ArchName = getWindowsSDKArch(getArch());
392
0
  if (ArchName.empty())
393
0
    return false;
394
0
395
0
  llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
396
0
  llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
397
0
398
0
  Path = LibPath.str();
399
0
  return true;
400
0
}
401
402
// Get the location to use for Visual Studio binaries.  The location priority
403
// is: %VCINSTALLDIR% > %PATH% > newest copy of Visual Studio installed on
404
// system (as reported by the registry).
405
bool MSVCToolChain::getVisualStudioBinariesFolder(const char *clangProgramPath,
406
281
                                                  std::string &path) const {
407
281
  path.clear();
408
281
409
281
  SmallString<128> BinDir;
410
281
411
281
  // First check the environment variables that vsvars32.bat sets.
412
281
  llvm::Optional<std::string> VcInstallDir =
413
281
      llvm::sys::Process::GetEnv("VCINSTALLDIR");
414
281
  if (
VcInstallDir.hasValue()281
)
{0
415
0
    BinDir = VcInstallDir.getValue();
416
0
    llvm::sys::path::append(BinDir, "bin");
417
281
  } else {
418
281
    // Next walk the PATH, trying to find a cl.exe in the path.  If we find one,
419
281
    // use that.  However, make sure it's not clang's cl.exe.
420
281
    llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
421
281
    if (
OptPath.hasValue()281
)
{281
422
281
      const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
423
281
      SmallVector<StringRef, 8> PathSegments;
424
281
      llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
425
281
426
1.68k
      for (StringRef PathSegment : PathSegments) {
427
1.68k
        if (PathSegment.empty())
428
0
          continue;
429
1.68k
430
1.68k
        SmallString<128> FilePath(PathSegment);
431
1.68k
        llvm::sys::path::append(FilePath, "cl.exe");
432
1.68k
        // Checking if cl.exe exists is a small optimization over calling
433
1.68k
        // can_execute, which really only checks for existence but will also do
434
1.68k
        // extra checks for cl.exe.exe.  These add up when walking a long path.
435
1.68k
        if (llvm::sys::fs::exists(FilePath.c_str()) &&
436
0
            
!llvm::sys::fs::equivalent(FilePath.c_str(), clangProgramPath)0
)
{0
437
0
          // If we found it on the PATH, use it exactly as is with no
438
0
          // modifications.
439
0
          path = PathSegment;
440
0
          return true;
441
0
        }
442
1.68k
      }
443
281
    }
444
281
445
281
    std::string installDir;
446
281
    // With no VCINSTALLDIR and nothing on the PATH, if we can't find it in the
447
281
    // registry then we have no choice but to fail.
448
281
    if (!getVisualStudioInstallDir(installDir))
449
281
      return false;
450
281
451
281
    // Regardless of what binary we're ultimately trying to find, we make sure
452
281
    // that this is a Visual Studio directory by checking for cl.exe.  We use
453
281
    // cl.exe instead of other binaries like link.exe because programs such as
454
281
    // GnuWin32 also have a utility called link.exe, so cl.exe is the least
455
281
    // ambiguous.
456
0
    BinDir = installDir;
457
0
    llvm::sys::path::append(BinDir, "VC", "bin");
458
0
    SmallString<128> ClPath(BinDir);
459
0
    llvm::sys::path::append(ClPath, "cl.exe");
460
0
461
0
    if (!llvm::sys::fs::can_execute(ClPath.c_str()))
462
0
      return false;
463
0
  }
464
281
465
0
  
if (0
BinDir.empty()0
)
466
0
    return false;
467
0
468
0
  switch (getArch()) {
469
0
  case llvm::Triple::x86:
470
0
    break;
471
0
  case llvm::Triple::x86_64:
472
0
    llvm::sys::path::append(BinDir, "amd64");
473
0
    break;
474
0
  case llvm::Triple::arm:
475
0
    llvm::sys::path::append(BinDir, "arm");
476
0
    break;
477
0
  default:
478
0
    // Whatever this is, Visual Studio doesn't have a toolchain for it.
479
0
    return false;
480
0
  }
481
0
  path = BinDir.str();
482
0
  return true;
483
0
}
484
485
1.22k
VersionTuple MSVCToolChain::getMSVCVersionFromTriple() const {
486
1.22k
  unsigned Major, Minor, Micro;
487
1.22k
  getTriple().getEnvironmentVersion(Major, Minor, Micro);
488
1.22k
  if (
Major || 1.22k
Minor1.22k
||
Micro1.22k
)
489
4
    return VersionTuple(Major, Minor, Micro);
490
1.22k
  return VersionTuple();
491
1.22k
}
492
493
1.22k
VersionTuple MSVCToolChain::getMSVCVersionFromExe() const {
494
1.22k
  VersionTuple Version;
495
1.22k
#ifdef USE_WIN32
496
  std::string BinPath;
497
  if (!getVisualStudioBinariesFolder("", BinPath))
498
    return Version;
499
  SmallString<128> ClExe(BinPath);
500
  llvm::sys::path::append(ClExe, "cl.exe");
501
502
  std::wstring ClExeWide;
503
  if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
504
    return Version;
505
506
  const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
507
                                                      nullptr);
508
  if (VersionSize == 0)
509
    return Version;
510
511
  SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
512
  if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
513
                             VersionBlock.data()))
514
    return Version;
515
516
  VS_FIXEDFILEINFO *FileInfo = nullptr;
517
  UINT FileInfoSize = 0;
518
  if (!::VerQueryValueW(VersionBlock.data(), L"\\",
519
                        reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
520
      FileInfoSize < sizeof(*FileInfo))
521
    return Version;
522
523
  const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
524
  const unsigned Minor = (FileInfo->dwFileVersionMS      ) & 0xFFFF;
525
  const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
526
527
  Version = VersionTuple(Major, Minor, Micro);
528
#endif
529
1.22k
  return Version;
530
1.22k
}
531
532
// Get Visual Studio installation directory.
533
1.05k
bool MSVCToolChain::getVisualStudioInstallDir(std::string &path) const {
534
1.05k
  // First check the environment variables that vsvars32.bat sets.
535
1.05k
  if (llvm::Optional<std::string> VcInstallDir =
536
0
          llvm::sys::Process::GetEnv("VCINSTALLDIR")) {
537
0
    path = std::move(*VcInstallDir);
538
0
    path = path.substr(0, path.find("\\VC"));
539
0
    return true;
540
0
  }
541
1.05k
542
1.05k
  std::string vsIDEInstallDir;
543
1.05k
  std::string vsExpressIDEInstallDir;
544
1.05k
  // Then try the windows registry.
545
1.05k
  bool hasVCDir =
546
1.05k
      getSystemRegistryString("SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
547
1.05k
                              "InstallDir", vsIDEInstallDir, nullptr);
548
1.05k
  if (
hasVCDir && 1.05k
!vsIDEInstallDir.empty()0
)
{0
549
0
    path = vsIDEInstallDir.substr(0, vsIDEInstallDir.find("\\Common7\\IDE"));
550
0
    return true;
551
0
  }
552
1.05k
553
1.05k
  bool hasVCExpressDir =
554
1.05k
      getSystemRegistryString("SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
555
1.05k
                              "InstallDir", vsExpressIDEInstallDir, nullptr);
556
1.05k
  if (
hasVCExpressDir && 1.05k
!vsExpressIDEInstallDir.empty()0
)
{0
557
0
    path = vsExpressIDEInstallDir.substr(
558
0
        0, vsIDEInstallDir.find("\\Common7\\IDE"));
559
0
    return true;
560
0
  }
561
1.05k
562
1.05k
  // Try the environment.
563
1.05k
  std::string vcomntools;
564
1.05k
  if (llvm::Optional<std::string> vs120comntools =
565
1.05k
          llvm::sys::Process::GetEnv("VS120COMNTOOLS"))
566
0
    vcomntools = std::move(*vs120comntools);
567
1.05k
  else 
if (llvm::Optional<std::string> 1.05k
vs100comntools1.05k
=
568
1.05k
               llvm::sys::Process::GetEnv("VS100COMNTOOLS"))
569
0
    vcomntools = std::move(*vs100comntools);
570
1.05k
  else 
if (llvm::Optional<std::string> 1.05k
vs90comntools1.05k
=
571
1.05k
               llvm::sys::Process::GetEnv("VS90COMNTOOLS"))
572
0
    vcomntools = std::move(*vs90comntools);
573
1.05k
  else 
if (llvm::Optional<std::string> 1.05k
vs80comntools1.05k
=
574
1.05k
               llvm::sys::Process::GetEnv("VS80COMNTOOLS"))
575
0
    vcomntools = std::move(*vs80comntools);
576
1.05k
577
1.05k
  // Find any version we can.
578
1.05k
  if (
!vcomntools.empty()1.05k
)
{0
579
0
    size_t p = vcomntools.find("\\Common7\\Tools");
580
0
    if (p != std::string::npos)
581
0
      vcomntools.resize(p);
582
0
    path = std::move(vcomntools);
583
0
    return true;
584
0
  }
585
1.05k
  return false;
586
1.05k
}
587
588
void MSVCToolChain::AddSystemIncludeWithSubfolder(
589
    const ArgList &DriverArgs, ArgStringList &CC1Args,
590
    const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
591
503
    const Twine &subfolder3) const {
592
503
  llvm::SmallString<128> path(folder);
593
503
  llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
594
503
  addSystemInclude(DriverArgs, CC1Args, path);
595
503
}
596
597
void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
598
503
                                              ArgStringList &CC1Args) const {
599
503
  if (DriverArgs.hasArg(options::OPT_nostdinc))
600
0
    return;
601
503
602
503
  
if (503
!DriverArgs.hasArg(options::OPT_nobuiltininc)503
)
{503
603
503
    AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
604
503
                                  "include");
605
503
  }
606
503
607
503
  // Add %INCLUDE%-like directories from the -imsvc flag.
608
503
  for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
609
2
    addSystemInclude(DriverArgs, CC1Args, Path);
610
503
611
503
  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
612
0
    return;
613
503
614
503
  // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
615
503
  
if (llvm::Optional<std::string> 503
cl_include_dir503
=
616
0
          llvm::sys::Process::GetEnv("INCLUDE")) {
617
0
    SmallVector<StringRef, 8> Dirs;
618
0
    StringRef(*cl_include_dir)
619
0
        .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
620
0
    for (StringRef Dir : Dirs)
621
0
      addSystemInclude(DriverArgs, CC1Args, Dir);
622
0
    if (!Dirs.empty())
623
0
      return;
624
0
  }
625
503
626
503
  std::string VSDir;
627
503
628
503
  // When built with access to the proper Windows APIs, try to actually find
629
503
  // the correct include paths first.
630
503
  if (
getVisualStudioInstallDir(VSDir)503
)
{0
631
0
    AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, VSDir, "VC\\include");
632
0
633
0
    if (
useUniversalCRT(VSDir)0
)
{0
634
0
      std::string UniversalCRTSdkPath;
635
0
      std::string UCRTVersion;
636
0
      if (
getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)0
)
{0
637
0
        AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
638
0
                                      "Include", UCRTVersion, "ucrt");
639
0
      }
640
0
    }
641
0
642
0
    std::string WindowsSDKDir;
643
0
    int major;
644
0
    std::string windowsSDKIncludeVersion;
645
0
    std::string windowsSDKLibVersion;
646
0
    if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
647
0
                         windowsSDKLibVersion)) {
648
0
      if (
major >= 80
)
{0
649
0
        // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
650
0
        // Anyway, llvm::sys::path::append is able to manage it.
651
0
        AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
652
0
                                      "include", windowsSDKIncludeVersion,
653
0
                                      "shared");
654
0
        AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
655
0
                                      "include", windowsSDKIncludeVersion,
656
0
                                      "um");
657
0
        AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
658
0
                                      "include", windowsSDKIncludeVersion,
659
0
                                      "winrt");
660
0
      } else {
661
0
        AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
662
0
                                      "include");
663
0
      }
664
0
    } else {
665
0
      addSystemInclude(DriverArgs, CC1Args, VSDir);
666
0
    }
667
0
    return;
668
0
  }
669
503
670
503
#if defined(LLVM_ON_WIN32)
671
  // As a fallback, select default install paths.
672
  // FIXME: Don't guess drives and paths like this on Windows.
673
  const StringRef Paths[] = {
674
    "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
675
    "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
676
    "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
677
    "C:/Program Files/Microsoft Visual Studio 8/VC/include",
678
    "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
679
  };
680
  addSystemIncludes(DriverArgs, CC1Args, Paths);
681
#endif
682
503
}
683
684
void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
685
122
                                                 ArgStringList &CC1Args) const {
686
122
  // FIXME: There should probably be logic here to find libc++ on Windows.
687
122
}
688
689
VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
690
1.27k
                                               const ArgList &Args) const {
691
1.27k
  bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
692
1.27k
  VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
693
1.27k
  if (
MSVT.empty()1.27k
)
MSVT = getMSVCVersionFromTriple()1.22k
;
694
1.27k
  if (
MSVT.empty() && 1.27k
IsWindowsMSVC1.22k
)
MSVT = getMSVCVersionFromExe()1.22k
;
695
1.27k
  if (MSVT.empty() &&
696
1.22k
      Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
697
1.22k
                   IsWindowsMSVC)) {
698
1.22k
    // -fms-compatibility-version=18.00 is default.
699
1.22k
    // FIXME: Consider bumping this to 19 (MSVC2015) soon.
700
1.22k
    MSVT = VersionTuple(18);
701
1.22k
  }
702
1.27k
  return MSVT;
703
1.27k
}
704
705
std::string
706
MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
707
779
                                           types::ID InputType) const {
708
779
  // The MSVC version doesn't care about the architecture, even though it
709
779
  // may look at the triple internally.
710
779
  VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
711
779
  MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
712
779
                      MSVT.getSubminor().getValueOr(0));
713
779
714
779
  // For the rest of the triple, however, a computed architecture name may
715
779
  // be needed.
716
779
  llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
717
779
  if (
Triple.getEnvironment() == llvm::Triple::MSVC779
)
{772
718
772
    StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
719
772
    if (ObjFmt.empty())
720
771
      Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
721
772
    else
722
1
      Triple.setEnvironmentName(
723
1
          (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
724
772
  }
725
779
  return Triple.getTriple();
726
779
}
727
728
478
SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
729
478
  SanitizerMask Res = ToolChain::getSupportedSanitizers();
730
478
  Res |= SanitizerKind::Address;
731
478
  return Res;
732
478
}
733
734
static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
735
                            bool SupportsForcingFramePointer,
736
19
                            const char *ExpandChar, const OptTable &Opts) {
737
19
  assert(A->getOption().matches(options::OPT__SLASH_O));
738
19
739
19
  StringRef OptStr = A->getValue();
740
44
  for (size_t I = 0, E = OptStr.size(); 
I != E44
;
++I25
)
{25
741
25
    const char &OptChar = *(OptStr.data() + I);
742
25
    switch (OptChar) {
743
3
    default:
744
3
      break;
745
11
    case '1':
746
11
    case '2':
747
11
    case 'x':
748
11
    case 'd':
749
11
      if (
&OptChar == ExpandChar11
)
{11
750
11
        if (
OptChar == 'd'11
)
{2
751
2
          DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
752
9
        } else {
753
9
          if (
OptChar == '1'9
)
{1
754
1
            DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
755
8
          } else 
if (8
OptChar == '2' || 8
OptChar == 'x'4
)
{8
756
8
            DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
757
8
            DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
758
8
          }
759
9
          if (SupportsForcingFramePointer &&
760
7
              !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
761
6
            DAL.AddFlagArg(A,
762
6
                           Opts.getOption(options::OPT_fomit_frame_pointer));
763
9
          if (
OptChar == '1' || 9
OptChar == '2'8
)
764
5
            DAL.AddFlagArg(A,
765
5
                           Opts.getOption(options::OPT_ffunction_sections));
766
9
        }
767
11
      }
768
11
      break;
769
6
    case 'b':
770
6
      if (
I + 1 != E && 6
isdigit(OptStr[I + 1])6
)
{6
771
6
        switch (OptStr[I + 1]) {
772
1
        case '0':
773
1
          DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
774
1
          break;
775
2
        case '1':
776
2
          DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
777
2
          break;
778
3
        case '2':
779
3
          DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
780
3
          break;
781
6
        }
782
6
        ++I;
783
6
      }
784
6
      break;
785
0
    case 'g':
786
0
      break;
787
0
    case 'i':
788
0
      if (
I + 1 != E && 0
OptStr[I + 1] == '-'0
)
{0
789
0
        ++I;
790
0
        DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
791
0
      } else {
792
0
        DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
793
0
      }
794
0
      break;
795
1
    case 's':
796
1
      DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
797
1
      break;
798
0
    case 't':
799
0
      DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
800
0
      break;
801
4
    case 'y': {
802
4
      bool OmitFramePointer = true;
803
4
      if (
I + 1 != E && 4
OptStr[I + 1] == '-'3
)
{3
804
3
        OmitFramePointer = false;
805
3
        ++I;
806
3
      }
807
4
      if (
SupportsForcingFramePointer4
)
{3
808
3
        if (OmitFramePointer)
809
0
          DAL.AddFlagArg(A,
810
0
                         Opts.getOption(options::OPT_fomit_frame_pointer));
811
3
        else
812
3
          DAL.AddFlagArg(
813
3
              A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
814
1
      } else {
815
1
        // Don't warn about /Oy- in 64-bit builds (where
816
1
        // SupportsForcingFramePointer is false).  The flag having no effect
817
1
        // there is a compiler-internal optimization, and people shouldn't have
818
1
        // to special-case their build files for 64-bit clang-cl.
819
1
        A->claim();
820
1
      }
821
4
      break;
822
6
    }
823
25
    }
824
25
  }
825
19
}
826
827
static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
828
10
                          const OptTable &Opts) {
829
10
  assert(A->getOption().matches(options::OPT_D));
830
10
831
10
  StringRef Val = A->getValue();
832
10
  size_t Hash = Val.find('#');
833
10
  if (
Hash == StringRef::npos || 10
Hash > Val.find('=')4
)
{7
834
7
    DAL.append(A);
835
7
    return;
836
7
  }
837
10
838
3
  std::string NewVal = Val;
839
3
  NewVal[Hash] = '=';
840
3
  DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
841
3
}
842
843
llvm::opt::DerivedArgList *
844
MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
845
481
                             StringRef BoundArch, Action::OffloadKind) const {
846
481
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
847
481
  const OptTable &Opts = getDriver().getOpts();
848
481
849
481
  // /Oy and /Oy- only has an effect under X86-32.
850
481
  bool SupportsForcingFramePointer = getArch() == llvm::Triple::x86;
851
481
852
481
  // The -O[12xd] flag actually expands to several flags.  We must desugar the
853
481
  // flags so that options embedded can be negated.  For example, the '-O2' flag
854
481
  // enables '-Oy'.  Expanding '-O2' into its constituent flags allows us to
855
481
  // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
856
481
  // aspect of '-O2'.
857
481
  //
858
481
  // Note that this expansion logic only applies to the *last* of '[12xd]'.
859
481
860
481
  // First step is to search for the character we'd like to expand.
861
481
  const char *ExpandChar = nullptr;
862
3.12k
  for (Arg *A : Args) {
863
3.12k
    if (!A->getOption().matches(options::OPT__SLASH_O))
864
3.10k
      continue;
865
19
    StringRef OptStr = A->getValue();
866
53
    for (size_t I = 0, E = OptStr.size(); 
I != E53
;
++I34
)
{34
867
34
      char OptChar = OptStr[I];
868
19
      char PrevChar = I > 0 ? 
OptStr[I - 1]15
:
'0'19
;
869
34
      if (
PrevChar == 'b'34
)
{6
870
6
        // OptChar does not expand; it's an argument to the previous char.
871
6
        continue;
872
6
      }
873
28
      
if (28
OptChar == '1' || 28
OptChar == '2'27
||
OptChar == 'x'23
||
OptChar == 'd'19
)
874
11
        ExpandChar = OptStr.data() + I;
875
28
    }
876
19
  }
877
481
878
3.12k
  for (Arg *A : Args) {
879
3.12k
    if (
A->getOption().matches(options::OPT__SLASH_O)3.12k
)
{19
880
19
      // The -O flag actually takes an amalgam of other options.  For example,
881
19
      // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
882
19
      TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
883
3.10k
    } else 
if (3.10k
A->getOption().matches(options::OPT_D)3.10k
)
{10
884
10
      // Translate -Dfoo#bar into -Dfoo=bar.
885
10
      TranslateDArg(A, *DAL, Opts);
886
3.09k
    } else {
887
3.09k
      DAL->append(A);
888
3.09k
    }
889
3.12k
  }
890
481
891
481
  return DAL;
892
481
}