forked from llvm-mirror/clang
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathMSVC.cpp
1546 lines (1375 loc) · 55.9 KB
/
MSVC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MSVC.h"
#include "CommonArgs.h"
#include "Darwin.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/SanitizerArgs.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include <cstdio>
// Include the necessary headers to interface with the Windows registry and
// environment.
#if defined(LLVM_ON_WIN32)
#define USE_WIN32
#endif
#ifdef USE_WIN32
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#ifdef _MSC_VER
// Don't support SetupApi on MinGW.
#define USE_MSVC_SETUP_API
// Make sure this comes before MSVCSetupApi.h
#include <comdef.h>
#include "MSVCSetupApi.h"
#include "llvm/Support/COM.h"
_COM_SMARTPTR_TYPEDEF(ISetupConfiguration, __uuidof(ISetupConfiguration));
_COM_SMARTPTR_TYPEDEF(ISetupConfiguration2, __uuidof(ISetupConfiguration2));
_COM_SMARTPTR_TYPEDEF(ISetupHelper, __uuidof(ISetupHelper));
_COM_SMARTPTR_TYPEDEF(IEnumSetupInstances, __uuidof(IEnumSetupInstances));
_COM_SMARTPTR_TYPEDEF(ISetupInstance, __uuidof(ISetupInstance));
_COM_SMARTPTR_TYPEDEF(ISetupInstance2, __uuidof(ISetupInstance2));
#endif
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;
// Defined below.
// Forward declare this so there aren't too many things above the constructor.
static bool getSystemRegistryString(const char *keyPath, const char *valueName,
std::string &value, std::string *phValue);
// Check various environment variables to try and find a toolchain.
static bool findVCToolChainViaEnvironment(std::string &Path,
MSVCToolChain::ToolsetLayout &VSLayout) {
// These variables are typically set by vcvarsall.bat
// when launching a developer command prompt.
if (llvm::Optional<std::string> VCToolsInstallDir =
llvm::sys::Process::GetEnv("VCToolsInstallDir")) {
// This is only set by newer Visual Studios, and it leads straight to
// the toolchain directory.
Path = std::move(*VCToolsInstallDir);
VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
return true;
}
if (llvm::Optional<std::string> VCInstallDir =
llvm::sys::Process::GetEnv("VCINSTALLDIR")) {
// If the previous variable isn't set but this one is, then we've found
// an older Visual Studio. This variable is set by newer Visual Studios too,
// so this check has to appear second.
// In older Visual Studios, the VC directory is the toolchain.
Path = std::move(*VCInstallDir);
VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
return true;
}
// We couldn't find any VC environment variables. Let's walk through PATH and
// see if it leads us to a VC toolchain bin directory. If it does, pick the
// first one that we find.
if (llvm::Optional<std::string> PathEnv =
llvm::sys::Process::GetEnv("PATH")) {
llvm::SmallVector<llvm::StringRef, 8> PathEntries;
llvm::StringRef(*PathEnv).split(PathEntries, llvm::sys::EnvPathSeparator);
for (llvm::StringRef PathEntry : PathEntries) {
if (PathEntry.empty())
continue;
llvm::SmallString<256> ExeTestPath;
// If cl.exe doesn't exist, then this definitely isn't a VC toolchain.
ExeTestPath = PathEntry;
llvm::sys::path::append(ExeTestPath, "cl.exe");
if (!llvm::sys::fs::exists(ExeTestPath))
continue;
// cl.exe existing isn't a conclusive test for a VC toolchain; clang also
// has a cl.exe. So let's check for link.exe too.
ExeTestPath = PathEntry;
llvm::sys::path::append(ExeTestPath, "link.exe");
if (!llvm::sys::fs::exists(ExeTestPath))
continue;
// whatever/VC/bin --> old toolchain, VC dir is toolchain dir.
llvm::StringRef TestPath = PathEntry;
bool IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin");
if (!IsBin) {
// Strip any architecture subdir like "amd64".
TestPath = llvm::sys::path::parent_path(TestPath);
IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin");
}
if (IsBin) {
llvm::StringRef ParentPath = llvm::sys::path::parent_path(TestPath);
llvm::StringRef ParentFilename = llvm::sys::path::filename(ParentPath);
if (ParentFilename == "VC") {
Path = ParentPath;
VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
return true;
}
if (ParentFilename == "x86ret" || ParentFilename == "x86chk"
|| ParentFilename == "amd64ret" || ParentFilename == "amd64chk") {
Path = ParentPath;
VSLayout = MSVCToolChain::ToolsetLayout::DevDivInternal;
return true;
}
} else {
// This could be a new (>=VS2017) toolchain. If it is, we should find
// path components with these prefixes when walking backwards through
// the path.
// Note: empty strings match anything.
llvm::StringRef ExpectedPrefixes[] = {"", "Host", "bin", "",
"MSVC", "Tools", "VC"};
auto It = llvm::sys::path::rbegin(PathEntry);
auto End = llvm::sys::path::rend(PathEntry);
for (llvm::StringRef Prefix : ExpectedPrefixes) {
if (It == End)
goto NotAToolChain;
if (!It->startswith(Prefix))
goto NotAToolChain;
++It;
}
// We've found a new toolchain!
// Back up 3 times (/bin/Host/arch) to get the root path.
llvm::StringRef ToolChainPath(PathEntry);
for (int i = 0; i < 3; ++i)
ToolChainPath = llvm::sys::path::parent_path(ToolChainPath);
Path = ToolChainPath;
VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
return true;
}
NotAToolChain:
continue;
}
}
return false;
}
// Query the Setup Config server for installs, then pick the newest version
// and find its default VC toolchain.
// This is the preferred way to discover new Visual Studios, as they're no
// longer listed in the registry.
static bool findVCToolChainViaSetupConfig(std::string &Path,
MSVCToolChain::ToolsetLayout &VSLayout) {
#if !defined(USE_MSVC_SETUP_API)
return false;
#else
// FIXME: This really should be done once in the top-level program's main
// function, as it may have already been initialized with a different
// threading model otherwise.
llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::SingleThreaded);
HRESULT HR;
// _com_ptr_t will throw a _com_error if a COM calls fail.
// The LLVM coding standards forbid exception handling, so we'll have to
// stop them from being thrown in the first place.
// The destructor will put the regular error handler back when we leave
// this scope.
struct SuppressCOMErrorsRAII {
static void __stdcall handler(HRESULT hr, IErrorInfo *perrinfo) {}
SuppressCOMErrorsRAII() { _set_com_error_handler(handler); }
~SuppressCOMErrorsRAII() { _set_com_error_handler(_com_raise_error); }
} COMErrorSuppressor;
ISetupConfigurationPtr Query;
HR = Query.CreateInstance(__uuidof(SetupConfiguration));
if (FAILED(HR))
return false;
IEnumSetupInstancesPtr EnumInstances;
HR = ISetupConfiguration2Ptr(Query)->EnumAllInstances(&EnumInstances);
if (FAILED(HR))
return false;
ISetupInstancePtr Instance;
HR = EnumInstances->Next(1, &Instance, nullptr);
if (HR != S_OK)
return false;
ISetupInstancePtr NewestInstance;
Optional<uint64_t> NewestVersionNum;
do {
bstr_t VersionString;
uint64_t VersionNum;
HR = Instance->GetInstallationVersion(VersionString.GetAddress());
if (FAILED(HR))
continue;
HR = ISetupHelperPtr(Query)->ParseVersion(VersionString, &VersionNum);
if (FAILED(HR))
continue;
if (!NewestVersionNum || (VersionNum > NewestVersionNum)) {
NewestInstance = Instance;
NewestVersionNum = VersionNum;
}
} while ((HR = EnumInstances->Next(1, &Instance, nullptr)) == S_OK);
if (!NewestInstance)
return false;
bstr_t VCPathWide;
HR = NewestInstance->ResolvePath(L"VC", VCPathWide.GetAddress());
if (FAILED(HR))
return false;
std::string VCRootPath;
llvm::convertWideToUTF8(std::wstring(VCPathWide), VCRootPath);
llvm::SmallString<256> ToolsVersionFilePath(VCRootPath);
llvm::sys::path::append(ToolsVersionFilePath, "Auxiliary", "Build",
"Microsoft.VCToolsVersion.default.txt");
auto ToolsVersionFile = llvm::MemoryBuffer::getFile(ToolsVersionFilePath);
if (!ToolsVersionFile)
return false;
llvm::SmallString<256> ToolchainPath(VCRootPath);
llvm::sys::path::append(ToolchainPath, "Tools", "MSVC",
ToolsVersionFile->get()->getBuffer().rtrim());
if (!llvm::sys::fs::is_directory(ToolchainPath))
return false;
Path = ToolchainPath.str();
VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer;
return true;
#endif
}
// Look in the registry for Visual Studio installs, and use that to get
// a toolchain path. VS2017 and newer don't get added to the registry.
// So if we find something here, we know that it's an older version.
static bool findVCToolChainViaRegistry(std::string &Path,
MSVCToolChain::ToolsetLayout &VSLayout) {
std::string VSInstallPath;
if (getSystemRegistryString(R"(SOFTWARE\Microsoft\VisualStudio\$VERSION)",
"InstallDir", VSInstallPath, nullptr) ||
getSystemRegistryString(R"(SOFTWARE\Microsoft\VCExpress\$VERSION)",
"InstallDir", VSInstallPath, nullptr)) {
if (!VSInstallPath.empty()) {
llvm::SmallString<256> VCPath(llvm::StringRef(
VSInstallPath.c_str(), VSInstallPath.find(R"(\Common7\IDE)")));
llvm::sys::path::append(VCPath, "VC");
Path = VCPath.str();
VSLayout = MSVCToolChain::ToolsetLayout::OlderVS;
return true;
}
}
return false;
}
// Try to find Exe from a Visual Studio distribution. This first tries to find
// an installed copy of Visual Studio and, failing that, looks in the PATH,
// making sure that whatever executable that's found is not a same-named exe
// from clang itself to prevent clang from falling back to itself.
static std::string FindVisualStudioExecutable(const ToolChain &TC,
const char *Exe) {
const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
SmallString<128> FilePath(MSVC.getSubDirectoryPath(
toolchains::MSVCToolChain::SubDirectoryType::Bin));
llvm::sys::path::append(FilePath, Exe);
return llvm::sys::fs::can_execute(FilePath) ? FilePath.str() : Exe;
}
void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
ArgStringList CmdArgs;
auto &TC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
assert((Output.isFilename() || Output.isNothing()) && "invalid output");
if (Output.isFilename())
CmdArgs.push_back(
Args.MakeArgString(std::string("-out:") + Output.getFilename()));
if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
!C.getDriver().IsCLMode() && !C.getDriver().IsFortranMode())
CmdArgs.push_back("-defaultlib:libcmt");
if (!llvm::sys::Process::GetEnv("LIB")) {
// If the VC environment hasn't been configured (perhaps because the user
// did not run vcvarsall), try to build a consistent link environment. If
// the environment variable is set however, assume the user knows what
// they're doing.
CmdArgs.push_back(Args.MakeArgString(
Twine("-libpath:") +
TC.getSubDirectoryPath(
toolchains::MSVCToolChain::SubDirectoryType::Lib)));
if (TC.useUniversalCRT()) {
std::string UniversalCRTLibPath;
if (TC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
CmdArgs.push_back(
Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath));
}
std::string WindowsSdkLibPath;
if (TC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
CmdArgs.push_back(
Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
}
if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
CmdArgs.push_back("-nologo");
if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
options::OPT__SLASH_Zd))
CmdArgs.push_back("-debug");
bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
options::OPT_shared);
if (DLL) {
CmdArgs.push_back(Args.MakeArgString("-dll"));
SmallString<128> ImplibName(Output.getFilename());
llvm::sys::path::replace_extension(ImplibName, "lib");
CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
}
if (TC.getSanitizerArgs().needsAsanRt()) {
CmdArgs.push_back(Args.MakeArgString("-debug"));
CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
if (TC.getSanitizerArgs().needsSharedRt() ||
Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
// Make sure the dynamic runtime thunk is not optimized out at link time
// to ensure proper SEH handling.
CmdArgs.push_back(Args.MakeArgString(
TC.getArch() == llvm::Triple::x86
? "-include:___asan_seh_interceptor"
: "-include:__asan_seh_interceptor"));
// Make sure the linker consider all object files from the dynamic runtime
// thunk.
CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk")));
} else if (DLL) {
CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
} else {
for (const auto &Lib : {"asan", "asan_cxx"}) {
CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
// Make sure the linker consider all object files from the static lib.
// This is necessary because instrumented dlls need access to all the
// interface exported by the static lib in the main executable.
CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
TC.getCompilerRT(Args, Lib)));
}
}
}
Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
options::OPT_fno_openmp, false)) {
CmdArgs.push_back("-nodefaultlib:vcomp.lib");
CmdArgs.push_back("-nodefaultlib:vcompd.lib");
CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
TC.getDriver().Dir + "/../lib"));
switch (TC.getDriver().getOpenMPRuntime(Args)) {
case Driver::OMPRT_OMP:
CmdArgs.push_back("-defaultlib:libomp.lib");
break;
case Driver::OMPRT_IOMP5:
CmdArgs.push_back("-defaultlib:libiomp5md.lib");
break;
case Driver::OMPRT_GOMP:
break;
case Driver::OMPRT_Unknown:
// Already diagnosed.
break;
}
}
if (C.getDriver().IsFortranMode()) {
CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
TC.getDriver().Dir + "/../lib"));
}
// Add compiler-rt lib in case if it was explicitly
// specified as an argument for --rtlib option.
if (!Args.hasArg(options::OPT_nostdlib)) {
AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
}
// Add filenames, libraries, and other linker inputs.
for (const auto &Input : Inputs) {
if (Input.isFilename()) {
CmdArgs.push_back(Input.getFilename());
continue;
}
const Arg &A = Input.getInputArg();
// Render -l options differently for the MSVC linker.
if (A.getOption().matches(options::OPT_l)) {
StringRef Lib = A.getValue();
const char *LinkLibArg;
if (Lib.endswith(".lib"))
LinkLibArg = Args.MakeArgString(Lib);
else
LinkLibArg = Args.MakeArgString(Lib + ".lib");
CmdArgs.push_back(LinkLibArg);
continue;
}
// Otherwise, this is some other kind of linker input option like -Wl, -z,
// or -L. Render it, even if MSVC doesn't understand it.
A.renderAsInput(Args, CmdArgs);
}
TC.addProfileRTLibs(Args, CmdArgs);
std::vector<const char *> Environment;
// We need to special case some linker paths. In the case of lld, we need to
// translate 'lld' into 'lld-link', and in the case of the regular msvc
// linker, we need to use a special search algorithm.
llvm::SmallString<128> linkPath;
StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
if (Linker.equals_lower("lld"))
Linker = "lld-link";
if (Linker.equals_lower("link")) {
// If we're using the MSVC linker, it's not sufficient to just use link
// from the program PATH, because other environments like GnuWin32 install
// their own link.exe which may come first.
linkPath = FindVisualStudioExecutable(TC, "link.exe");
#ifdef USE_WIN32
// When cross-compiling with VS2017 or newer, link.exe expects to have
// its containing bin directory at the top of PATH, followed by the
// native target bin directory.
// e.g. when compiling for x86 on an x64 host, PATH should start with:
// /bin/HostX64/x86;/bin/HostX64/x64
// This doesn't attempt to handle ToolsetLayout::DevDivInternal.
if (TC.getIsVS2017OrNewer() &&
llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
auto EnvBlockWide =
std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
GetEnvironmentStringsW(), FreeEnvironmentStringsW);
if (!EnvBlockWide)
goto SkipSettingEnvironment;
size_t EnvCount = 0;
size_t EnvBlockLen = 0;
while (EnvBlockWide[EnvBlockLen] != L'\0') {
++EnvCount;
EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
1 /*string null-terminator*/;
}
++EnvBlockLen; // add the block null-terminator
std::string EnvBlock;
if (!llvm::convertUTF16ToUTF8String(
llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
EnvBlockLen * sizeof(EnvBlockWide[0])),
EnvBlock))
goto SkipSettingEnvironment;
Environment.reserve(EnvCount);
// Now loop over each string in the block and copy them into the
// environment vector, adjusting the PATH variable as needed when we
// find it.
for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
llvm::StringRef EnvVar(Cursor);
if (EnvVar.startswith_lower("path=")) {
using SubDirectoryType = toolchains::MSVCToolChain::SubDirectoryType;
constexpr size_t PrefixLen = 5; // strlen("path=")
Environment.push_back(Args.MakeArgString(
EnvVar.substr(0, PrefixLen) +
TC.getSubDirectoryPath(SubDirectoryType::Bin) +
llvm::Twine(llvm::sys::EnvPathSeparator) +
TC.getSubDirectoryPath(SubDirectoryType::Bin, HostArch) +
(EnvVar.size() > PrefixLen
? llvm::Twine(llvm::sys::EnvPathSeparator) +
EnvVar.substr(PrefixLen)
: "")));
} else {
Environment.push_back(Args.MakeArgString(EnvVar));
}
Cursor += EnvVar.size() + 1 /*null-terminator*/;
}
}
SkipSettingEnvironment:;
#endif
} else {
linkPath = TC.GetProgramPath(Linker.str().c_str());
}
auto LinkCmd = llvm::make_unique<Command>(
JA, *this, Args.MakeArgString(linkPath), CmdArgs, Inputs);
if (!Environment.empty())
LinkCmd->setEnvironment(Environment);
C.addCommand(std::move(LinkCmd));
}
void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
}
std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
Compilation &C, const JobAction &JA, const InputInfo &Output,
const InputInfoList &Inputs, const ArgList &Args,
const char *LinkingOutput) const {
ArgStringList CmdArgs;
CmdArgs.push_back("/nologo");
CmdArgs.push_back("/c"); // Compile only.
CmdArgs.push_back("/W0"); // No warnings.
// The goal is to be able to invoke this tool correctly based on
// any flag accepted by clang-cl.
// These are spelled the same way in clang and cl.exe,.
Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
// Optimization level.
if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
: "/Oi-");
if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
if (A->getOption().getID() == options::OPT_O0) {
CmdArgs.push_back("/Od");
} else {
CmdArgs.push_back("/Og");
StringRef OptLevel = A->getValue();
if (OptLevel == "s" || OptLevel == "z")
CmdArgs.push_back("/Os");
else
CmdArgs.push_back("/Ot");
CmdArgs.push_back("/Ob2");
}
}
if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
options::OPT_fno_omit_frame_pointer))
CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
? "/Oy"
: "/Oy-");
if (!Args.hasArg(options::OPT_fwritable_strings))
CmdArgs.push_back("/GF");
// Flags for which clang-cl has an alias.
// FIXME: How can we ensure this stays in sync with relevant clang-cl options?
if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
/*default=*/false))
CmdArgs.push_back("/GR-");
if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
/*default=*/false))
CmdArgs.push_back("/GS-");
if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
options::OPT_fno_function_sections))
CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
? "/Gy"
: "/Gy-");
if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
options::OPT_fno_data_sections))
CmdArgs.push_back(
A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
if (Args.hasArg(options::OPT_fsyntax_only))
CmdArgs.push_back("/Zs");
if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
options::OPT__SLASH_Z7))
CmdArgs.push_back("/Z7");
std::vector<std::string> Includes =
Args.getAllArgValues(options::OPT_include);
for (const auto &Include : Includes)
CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
// Flags that can simply be passed through.
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
// The order of these flags is relevant, so pick the last one.
if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
A->render(Args, CmdArgs);
// Use MSVC's default threadsafe statics behaviour unless there was a flag.
if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
options::OPT_fno_threadsafe_statics)) {
CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
? "/Zc:threadSafeInit"
: "/Zc:threadSafeInit-");
}
// Pass through all unknown arguments so that the fallback command can see
// them too.
Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
// Input filename.
assert(Inputs.size() == 1);
const InputInfo &II = Inputs[0];
assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
if (II.isFilename())
CmdArgs.push_back(II.getFilename());
else
II.getInputArg().renderAsInput(Args, CmdArgs);
// Output filename.
assert(Output.getType() == types::TY_Object);
const char *Fo =
Args.MakeArgString(std::string("/Fo") + Output.getFilename());
CmdArgs.push_back(Fo);
std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe");
return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
CmdArgs, Inputs);
}
MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
: ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) {
getProgramPaths().push_back(getDriver().getInstalledDir());
if (getDriver().getInstalledDir() != getDriver().Dir)
getProgramPaths().push_back(getDriver().Dir);
// Check the environment first, since that's probably the user telling us
// what they want to use.
// Failing that, just try to find the newest Visual Studio version we can
// and use its default VC toolchain.
findVCToolChainViaEnvironment(VCToolChainPath, VSLayout) ||
findVCToolChainViaSetupConfig(VCToolChainPath, VSLayout) ||
findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
}
Tool *MSVCToolChain::buildLinker() const {
if (VCToolChainPath.empty())
getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
return new tools::visualstudio::Linker(*this);
}
Tool *MSVCToolChain::buildAssembler() const {
if (getTriple().isOSBinFormatMachO())
return new tools::darwin::Assembler(*this);
getDriver().Diag(clang::diag::err_no_external_assembler);
return nullptr;
}
bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
return true;
}
bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
// Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
// such as ARM and PPC actually require unwind tables, but LLVM doesn't know
// how to generate them yet.
// Don't emit unwind tables by default for MachO targets.
if (getTriple().isOSBinFormatMachO())
return false;
return getArch() == llvm::Triple::x86_64;
}
bool MSVCToolChain::isPICDefault() const {
return getArch() == llvm::Triple::x86_64;
}
bool MSVCToolChain::isPIEDefault() const {
return false;
}
bool MSVCToolChain::isPICDefaultForced() const {
return getArch() == llvm::Triple::x86_64;
}
void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
}
void MSVCToolChain::AddFortranStdlibLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
bool staticFlangLibs = false;
bool useOpenMP = false;
if (Args.hasArg(options::OPT_staticFlangLibs)) {
for (auto *A: Args.filtered(options::OPT_staticFlangLibs)) {
A->claim();
staticFlangLibs = true;
}
}
Arg *A = Args.getLastArg(options::OPT_mp, options::OPT_nomp,
options::OPT_fopenmp, options::OPT_fno_openmp);
if (A &&
(A->getOption().matches(options::OPT_mp) ||
A->getOption().matches(options::OPT_fopenmp))) {
useOpenMP = true;
}
if (needFortranMain(getDriver(), Args)) {
// flangmain is always static
CmdArgs.push_back("-linker");
CmdArgs.push_back("/subsystem:console");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:flangmain.lib");
}
if (staticFlangLibs) {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libflang.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libflangrti.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libpgmath.lib");
} else {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:flang.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:flangrti.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:pgmath.lib");
}
if (useOpenMP) {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/nodefaultlib:vcomp.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/nodefaultlib:vcompd.lib");
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libomp.lib");
}
else {
if (staticFlangLibs) {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libompstub.lib");
} else {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:ompstub.lib");
}
}
// Allways link Fortran executables with Pthreads
// CmdArgs.push_back("-lpthread");
// These options are added clang-cl in Clang.cpp for C/C++
// In clang-cl.exe -MD and -MT control these options, but in
// flang.exe like clang.exe these are different options for
// dependency tracking. Let's assume that if somebody needs
// static flang libs, they need static runtime libs as well.
if (staticFlangLibs) {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:libcmt.lib");
} else {
CmdArgs.push_back("-linker");
CmdArgs.push_back("/defaultlib:msvcrt.lib");
}
}
void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
CudaInstallation.print(OS);
}
// Windows SDKs and VC Toolchains group their contents into subdirectories based
// on the target architecture. This function converts an llvm::Triple::ArchType
// to the corresponding subdirectory name.
static const char *llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch) {
using ArchType = llvm::Triple::ArchType;
switch (Arch) {
case ArchType::x86:
return "x86";
case ArchType::x86_64:
return "x64";
case ArchType::arm:
return "arm";
default:
return "";
}
}
// Similar to the above function, but for Visual Studios before VS2017.
static const char *llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch) {
using ArchType = llvm::Triple::ArchType;
switch (Arch) {
case ArchType::x86:
// x86 is default in legacy VC toolchains.
// e.g. x86 libs are directly in /lib as opposed to /lib/x86.
return "";
case ArchType::x86_64:
return "amd64";
case ArchType::arm:
return "arm";
default:
return "";
}
}
// Similar to the above function, but for DevDiv internal builds.
static const char *llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch) {
using ArchType = llvm::Triple::ArchType;
switch (Arch) {
case ArchType::x86:
return "i386";
case ArchType::x86_64:
return "amd64";
case ArchType::arm:
return "arm";
default:
return "";
}
}
// Get the path to a specific subdirectory in the current toolchain for
// a given target architecture.
// VS2017 changed the VC toolchain layout, so this should be used instead
// of hardcoding paths.
std::string
MSVCToolChain::getSubDirectoryPath(SubDirectoryType Type,
llvm::Triple::ArchType TargetArch) const {
const char *SubdirName;
const char *IncludeName;
switch (VSLayout) {
case ToolsetLayout::OlderVS:
SubdirName = llvmArchToLegacyVCArch(TargetArch);
IncludeName = "include";
break;
case ToolsetLayout::VS2017OrNewer:
SubdirName = llvmArchToWindowsSDKArch(TargetArch);
IncludeName = "include";
break;
case ToolsetLayout::DevDivInternal:
SubdirName = llvmArchToDevDivInternalArch(TargetArch);
IncludeName = "inc";
break;
}
llvm::SmallString<256> Path(VCToolChainPath);
switch (Type) {
case SubDirectoryType::Bin:
if (VSLayout == ToolsetLayout::VS2017OrNewer) {
const bool HostIsX64 =
llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
const char *const HostName = HostIsX64 ? "HostX64" : "HostX86";
llvm::sys::path::append(Path, "bin", HostName, SubdirName);
} else { // OlderVS or DevDivInternal
llvm::sys::path::append(Path, "bin", SubdirName);
}
break;
case SubDirectoryType::Include:
llvm::sys::path::append(Path, IncludeName);
break;
case SubDirectoryType::Lib:
llvm::sys::path::append(Path, "lib", SubdirName);
break;
}
return Path.str();
}
#ifdef USE_WIN32
static bool readFullStringValue(HKEY hkey, const char *valueName,
std::string &value) {
std::wstring WideValueName;
if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
return false;
DWORD result = 0;
DWORD valueSize = 0;
DWORD type = 0;
// First just query for the required size.
result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
&valueSize);
if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
return false;
std::vector<BYTE> buffer(valueSize);
result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
&valueSize);
if (result == ERROR_SUCCESS) {
std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
valueSize / sizeof(wchar_t));
if (valueSize && WideValue.back() == L'\0') {
WideValue.pop_back();
}
// The destination buffer must be empty as an invariant of the conversion
// function; but this function is sometimes called in a loop that passes in
// the same buffer, however. Simply clear it out so we can overwrite it.
value.clear();
return llvm::convertWideToUTF8(WideValue, value);
}
return false;
}
#endif
/// \brief Read registry string.
/// This also supports a means to look for high-versioned keys by use
/// of a $VERSION placeholder in the key path.
/// $VERSION in the key path is a placeholder for the version number,
/// causing the highest value path to be searched for and used.
/// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
/// There can be additional characters in the component. Only the numeric
/// characters are compared. This function only searches HKLM.
static bool getSystemRegistryString(const char *keyPath, const char *valueName,
std::string &value, std::string *phValue) {
#ifndef USE_WIN32
return false;
#else
HKEY hRootKey = HKEY_LOCAL_MACHINE;
HKEY hKey = NULL;
long lResult;
bool returnValue = false;
const char *placeHolder = strstr(keyPath, "$VERSION");
std::string bestName;
// If we have a $VERSION placeholder, do the highest-version search.
if (placeHolder) {
const char *keyEnd = placeHolder - 1;
const char *nextKey = placeHolder;
// Find end of previous key.
while ((keyEnd > keyPath) && (*keyEnd != '\\'))
keyEnd--;
// Find end of key containing $VERSION.
while (*nextKey && (*nextKey != '\\'))
nextKey++;
size_t partialKeyLength = keyEnd - keyPath;
char partialKey[256];
if (partialKeyLength >= sizeof(partialKey))
partialKeyLength = sizeof(partialKey) - 1;
strncpy(partialKey, keyPath, partialKeyLength);
partialKey[partialKeyLength] = '\0';
HKEY hTopKey = NULL;
lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
&hTopKey);
if (lResult == ERROR_SUCCESS) {
char keyName[256];
double bestValue = 0.0;
DWORD index, size = sizeof(keyName) - 1;
for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
NULL, NULL) == ERROR_SUCCESS;