-
Notifications
You must be signed in to change notification settings - Fork 822
Expand file tree
/
Copy pathSYCL.cpp
More file actions
1964 lines (1826 loc) · 80.2 KB
/
SYCL.cpp
File metadata and controls
1964 lines (1826 loc) · 80.2 KB
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
//===--- SYCL.cpp - SYCL Tool and ToolChain Implementations -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SYCL.h"
#include "clang/Driver/CommonArgs.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/SYCLLowerIR/DeviceConfigFile.hpp"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <sstream>
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;
SYCLInstallationDetector::SYCLInstallationDetector(
const Driver &D, const llvm::Triple &HostTriple,
const llvm::opt::ArgList &Args)
: D(D), InstallationCandidates() {
// Detect the presence of the SYCL runtime library (libsycl.so) in the
// filesystem. This is used to determine whether a usable SYCL installation
// is available for the current driver invocation.
StringRef SysRoot = D.SysRoot;
SmallString<128> DriverDir(D.Dir);
if (DriverDir.starts_with(SysRoot) &&
(Args.hasArg(options::OPT_fsycl) ||
D.getVFS().exists(DriverDir + "/../lib/libsycl.so"))) {
llvm::sys::path::append(DriverDir, "..", "lib");
SYCLRTLibPath = DriverDir;
}
InstallationCandidates.emplace_back(D.Dir + "/..");
}
static llvm::SmallString<64>
getLibSpirvBasename(const llvm::Triple &HostTriple) {
// Select remangled libclc variant.
// Decide long size based on host triple, because offloading targets are going
// to match that.
// All known windows environments except Cygwin use 32-bit long.
llvm::SmallString<64> Result(HostTriple.isOSWindows() &&
!HostTriple.isWindowsCygwinEnvironment()
? "remangled-l32-signed_char.libspirv.bc"
: "remangled-l64-signed_char.libspirv.bc");
return Result;
}
const char *SYCLInstallationDetector::findLibspirvPath(
const llvm::Triple &DeviceTriple, const llvm::opt::ArgList &Args,
const llvm::Triple &HostTriple) const {
// If -fsycl-libspirv-path= is specified, try to use that path directly.
if (Arg *A = Args.getLastArg(options::OPT_fsycl_libspirv_path_EQ)) {
if (D.getVFS().exists(A->getValue()))
return A->getValue();
return nullptr;
}
const SmallString<64> Basename = getLibSpirvBasename(HostTriple);
SmallString<256> LibclcPath(D.ResourceDir);
llvm::sys::path::append(LibclcPath, "lib", DeviceTriple.getTriple(),
Basename);
if (D.getVFS().exists(LibclcPath))
return Args.MakeArgString(LibclcPath);
return nullptr;
}
void SYCLInstallationDetector::addLibspirvLinkArgs(
const llvm::Triple &DeviceTriple, const llvm::opt::ArgList &DriverArgs,
const llvm::Triple &HostTriple, llvm::opt::ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_fno_sycl_libspirv)) {
// -fno-sycl-libspirv flag is reserved for very unusual cases where the
// libspirv library is not linked when required by the device: so output
// appropriate warnings.
D.Diag(diag::warn_flag_no_sycl_libspirv) << DeviceTriple.str();
return;
}
if (const char *LibSpirvFile =
findLibspirvPath(DeviceTriple, DriverArgs, HostTriple)) {
CC1Args.push_back("-mlink-builtin-bitcode");
CC1Args.push_back(LibSpirvFile);
return;
}
D.Diag(diag::err_drv_no_sycl_libspirv) << getLibSpirvBasename(HostTriple);
}
void SYCLInstallationDetector::getSYCLDeviceLibPath(
llvm::SmallVector<llvm::SmallString<128>, 4> &DeviceLibPaths) const {
for (const auto &IC : InstallationCandidates) {
llvm::SmallString<128> InstallLibPath(IC.str());
InstallLibPath.append("/lib");
DeviceLibPaths.emplace_back(InstallLibPath);
}
DeviceLibPaths.emplace_back(D.SysRoot + "/lib");
}
void SYCLInstallationDetector::addSYCLIncludeArgs(
const ArgList &DriverArgs, ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdinc)) {
return;
}
// Add the SYCL header search locations in the specified order.
// ../include/sycl/stl_wrappers
// ../include
SmallString<128> IncludePath(D.Dir);
llvm::sys::path::append(IncludePath, "..");
llvm::sys::path::append(IncludePath, "include");
// This is used to provide our wrappers around STL headers that provide
// additional functions/template specializations when the user includes those
// STL headers in their programs (e.g., <complex>).
SmallString<128> STLWrappersPath(IncludePath);
llvm::sys::path::append(STLWrappersPath, "sycl");
llvm::sys::path::append(STLWrappersPath, "stl_wrappers");
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(STLWrappersPath));
CC1Args.push_back("-internal-isystem");
CC1Args.push_back(DriverArgs.MakeArgString(IncludePath));
}
void SYCLInstallationDetector::print(llvm::raw_ostream &OS) const {
if (!InstallationCandidates.size())
return;
OS << "SYCL Installation Candidates: \n";
for (const auto &IC : InstallationCandidates) {
OS << IC << "\n";
}
}
void SYCL::constructLLVMForeachCommand(Compilation &C, const JobAction &JA,
std::unique_ptr<Command> InputCommand,
const InputInfoList &InputFiles,
const InputInfo &Output, const Tool *T,
StringRef Increment, StringRef Ext,
StringRef ParallelJobs) {
// Construct llvm-foreach command.
// The llvm-foreach command looks like this:
// llvm-foreach --in-file-list=a.list --in-replace='{}' -- echo '{}'
ArgStringList ForeachArgs;
std::string OutputFileName(T->getToolChain().getInputFilename(Output));
ForeachArgs.push_back(C.getArgs().MakeArgString("--out-ext=" + Ext));
for (auto &I : InputFiles) {
std::string Filename(T->getToolChain().getInputFilename(I));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--in-file-list=" + Filename));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--in-replace=" + Filename));
}
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-file-list=" + OutputFileName));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-replace=" + OutputFileName));
if (!Increment.empty())
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-increment=" + Increment));
if (!ParallelJobs.empty())
ForeachArgs.push_back(C.getArgs().MakeArgString("--jobs=" + ParallelJobs));
if (C.getDriver().isSaveTempsEnabled()) {
SmallString<128> OutputDirName;
if (C.getDriver().isSaveTempsObj()) {
OutputDirName =
T->getToolChain().GetFilePath(OutputFileName.c_str()).c_str();
llvm::sys::path::remove_filename(OutputDirName);
}
// Use the current dir if the `GetFilePath` returned en empty string, which
// is the case when the `OutputFileName` does not contain any directory
// information, or if in CWD mode. This is necessary for `llvm-foreach`, as
// it would disregard the parameter without it. Otherwise append separator.
if (OutputDirName.empty())
llvm::sys::path::native(OutputDirName = "./");
else
OutputDirName.append(llvm::sys::path::get_separator());
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-dir=" + OutputDirName));
}
// If save-offload-code is passed, put the PTX files
// into the path provided in save-offload-code.
if (T->getToolChain().getTriple().isNVPTX() &&
C.getDriver().isSaveOffloadCodeEnabled() && Ext == "s") {
SmallString<128> OutputDir;
Arg *SaveOffloadCodeArg =
C.getArgs().getLastArg(options::OPT_save_offload_code_EQ);
OutputDir = (SaveOffloadCodeArg ? SaveOffloadCodeArg->getValue() : "");
// If the output directory path is empty, put the PTX files in the
// current directory.
if (OutputDir.empty())
llvm::sys::path::native(OutputDir = "./");
else
OutputDir.append(llvm::sys::path::get_separator());
ForeachArgs.push_back(C.getArgs().MakeArgString("--out-dir=" + OutputDir));
}
ForeachArgs.push_back(C.getArgs().MakeArgString("--"));
ForeachArgs.push_back(
C.getArgs().MakeArgString(InputCommand->getExecutable()));
for (auto &Arg : InputCommand->getArguments())
ForeachArgs.push_back(Arg);
SmallString<128> ForeachPath(C.getDriver().Dir);
llvm::sys::path::append(ForeachPath, "llvm-foreach");
const char *Foreach = C.getArgs().MakeArgString(ForeachPath);
auto Cmd = std::make_unique<Command>(JA, *T, ResponseFileSupport::None(),
Foreach, ForeachArgs,
ArrayRef<InputInfo>{});
C.addCommand(std::move(Cmd));
}
bool SYCL::shouldDoPerObjectFileLinking(const Compilation &C) {
return !C.getArgs().hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
/*default=*/true);
}
// Return whether to use native bfloat16 library.
static bool selectBfloatLibs(const llvm::opt::ArgList &Args,
const llvm::Triple &Triple, const ToolChain &TC,
bool &UseNative) {
static llvm::SmallSet<StringRef, 8> GPUArchsWithNBF16{
"intel_gpu_pvc", "intel_gpu_acm_g10", "intel_gpu_acm_g11",
"intel_gpu_acm_g12", "intel_gpu_dg2_g10", "intel_gpu_dg2_g11",
"intel_dg2_g12", "intel_gpu_bmg_g21", "intel_gpu_lnl_m",
"intel_gpu_ptl_h", "intel_gpu_ptl_u", "intel_gpu_wcl",
"intel_gpu_cri"};
bool NeedLibs = false;
// spir64 target is actually JIT compilation, so we defer selection of
// bfloat16 libraries to runtime. For AOT we need libraries, but skip
// for Nvidia and AMD.
NeedLibs = Triple.getSubArch() != llvm::Triple::NoSubArch &&
!Triple.isNVPTX() && !Triple.isAMDGCN();
UseNative = false;
if (NeedLibs && Triple.getSubArch() == llvm::Triple::SPIRSubArch_gen) {
ArgStringList TargArgs;
const toolchains::SYCLToolChain &SYCLTC =
static_cast<const toolchains::SYCLToolChain &>(TC);
SYCLTC.TranslateBackendTargetArgs(Triple, Args, TargArgs);
// We need to select fallback/native bfloat16 devicelib in AOT compilation
// targetting for Intel GPU devices. Users have 2 ways to apply AOT,
// 1). clang++ -fsycl -fsycl-targets=spir64_gen -Xs "-device pvc,...,"
// 2). clang++ -fsycl -fsycl-targets=intel_gpu_pvc,...
// 3). clang++ -fsycl -fsycl-targets=spir64_gen,intel_gpu_pvc,...
// -Xsycl-target-backend=spir64_gen "-device dg2"
std::string Params;
for (const auto &Arg : TargArgs) {
Params += " ";
Params += Arg;
}
auto checkBF = [](StringRef Device) {
return Device.starts_with("pvc") || Device.starts_with("ats") ||
Device.starts_with("dg2") || Device.starts_with("bmg") ||
Device.starts_with("lnl") || Device.starts_with("ptl") ||
Device.starts_with("wcl") || Device.starts_with("cri");
};
auto checkSpirvJIT = [](StringRef Target) {
return Target.starts_with("spir64-") || Target.starts_with("spirv64-") ||
(Target == "spir64") || (Target == "spirv64");
};
size_t DevicesPos = Params.find("-device ");
// "-device xxx" is used to specify AOT target device, so user must apply
// -Xs "-device xxx" or -Xsycl-target-backend=spir64_gen "-device xxx"
if (DevicesPos != std::string::npos) {
UseNative = true;
std::istringstream Devices(Params.substr(DevicesPos + 8));
for (std::string S; std::getline(Devices, S, ',');)
UseNative &= checkBF(S);
// When "-device XXX" is applied to specify GPU type, user can still
// add -fsycl-targets=intel_gpu_pvc..., native bfloat16 devicelib can
// only be linked when all GPU types specified support.
// We need to filter CPU target here and only focus on GPU device.
if (Arg *SYCLTarget = Args.getLastArg(options::OPT_offload_targets_EQ)) {
for (auto TargetsV : SYCLTarget->getValues()) {
if (!checkSpirvJIT(StringRef(TargetsV)) &&
!StringRef(TargetsV).starts_with("spir64_gen") &&
!StringRef(TargetsV).starts_with("spir64_x86_64") &&
!GPUArchsWithNBF16.contains(StringRef(TargetsV))) {
UseNative = false;
break;
}
}
}
return NeedLibs;
} else {
// -fsycl-targets=intel_gpu_xxx is used to specify AOT target device.
// Multiple Intel GPU devices can be specified, native bfloat16 devicelib
// can be involved only when all GPU deivces specified support native
// bfloat16 native conversion.
UseNative = true;
if (Arg *SYCLTarget = Args.getLastArg(options::OPT_offload_targets_EQ)) {
for (auto TargetsV : SYCLTarget->getValues()) {
if (!checkSpirvJIT(StringRef(TargetsV)) &&
!GPUArchsWithNBF16.contains(StringRef(TargetsV))) {
UseNative = false;
break;
}
}
}
return NeedLibs;
}
}
return NeedLibs;
}
struct OclocInfo {
const char *DeviceName;
const char *PackageName;
const char *Version;
SmallVector<int, 8> HexValues;
};
// The PVCDevices data structure is organized by device name, with the
// corresponding ocloc split release, version and possible Hex representations
// of various PVC devices. This information is gathered from the following:
// https://github.com/intel/compute-runtime/blob/master/shared/source/dll/devices/devices_base.inl
// https://github.com/intel/compute-runtime/blob/master/shared/source/dll/devices/devices_additional.inl
static OclocInfo PVCDevices[] = {
{"pvc-sdv", "gen12+", "12.60.1", {}},
{"pvc",
"gen12+",
"12.60.7",
{0x0BD0, 0x0BD5, 0x0BD6, 0x0BD7, 0x0BD8, 0x0BD9, 0x0BDA, 0x0BDB}}};
static std::string getDeviceArg(const ArgStringList &CmdArgs) {
bool DeviceSeen = false;
std::string DeviceArg;
for (StringRef Arg : CmdArgs) {
// -device <arg> comes in as a single arg, split up all potential space
// separated values.
SmallVector<StringRef> SplitArgs;
Arg.split(SplitArgs, ' ');
for (StringRef SplitArg : SplitArgs) {
if (DeviceSeen) {
DeviceArg = SplitArg.str();
break;
}
if (SplitArg == "-device")
DeviceSeen = true;
}
if (DeviceSeen)
break;
}
return DeviceArg;
}
static bool checkPVCDevice(std::string SingleArg, std::string &DevArg) {
// Handle shortened versions.
bool CheckShortVersion = true;
for (auto Char : SingleArg) {
if (!std::isdigit(Char) && Char != '.') {
CheckShortVersion = false;
break;
}
}
// Check for device, version or hex (literal values)
for (unsigned int I = 0; I < std::size(PVCDevices); I++) {
if (StringRef(SingleArg).equals_insensitive(PVCDevices[I].DeviceName) ||
StringRef(SingleArg).equals_insensitive(PVCDevices[I].Version)) {
DevArg = SingleArg;
return true;
}
for (int HexVal : PVCDevices[I].HexValues) {
int Value = 0;
if (!StringRef(SingleArg).getAsInteger(0, Value) && Value == HexVal) {
// TODO: Pass back the hex string to use for -device_options when
// IGC is updated to allow. Currently -device_options only accepts
// the device ID (i.e. pvc) or the version (12.60.7).
return true;
}
}
if (CheckShortVersion &&
StringRef(PVCDevices[I].Version).starts_with(SingleArg)) {
DevArg = SingleArg;
return true;
}
}
return false;
}
#if !defined(_WIN32)
static void addSYCLDeviceSanitizerLibs(
const llvm::opt::ArgList &Args,
SmallVector<ToolChain::BitCodeLibraryInfo, 8> &LibraryList) {
enum { JIT = 0, AOT_CPU, AOT_DG2, AOT_PVC };
// TODO: Device code linking during the compilation phase provides the
// opportunity to link in the specific arch related sanitizer libraries
// without having to default to the fallback device sanitizer library when
// compiling for multiple targets.
// Default internalization to 'false' for these libraries, as they are
// expected to link with -mlink-bitcode-file, which does not link with
// only-needed.
auto addSingleLibrary = [&](StringRef DeviceLibName,
bool Internalize = false) {
std::string FullLibName(Args.MakeArgString(DeviceLibName + ".bc"));
ToolChain::BitCodeLibraryInfo BitCodeLibrary({FullLibName, Internalize});
LibraryList.push_back(BitCodeLibrary);
};
// This function is used to check whether there is only one GPU device
// (PVC or DG2) specified in AOT compilation mode. If yes, we can use
// corresponding libsycl-asan-* to improve device sanitizer performance,
// otherwise stick to fallback device sanitizer library used in JIT mode.
auto getSpecificGPUTarget = [](const ArgStringList &CmdArgs) -> size_t {
std::string DeviceArg = getDeviceArg(CmdArgs);
if ((DeviceArg.empty()) || (DeviceArg.find(",") != std::string::npos))
return JIT;
std::string Temp;
if (checkPVCDevice(DeviceArg, Temp))
return AOT_PVC;
if (DeviceArg == "dg2")
return AOT_DG2;
return JIT;
};
auto getSingleBuildTarget = [&]() -> size_t {
llvm::opt::Arg *SYCLTarget =
Args.getLastArg(options::OPT_offload_targets_EQ);
if (!SYCLTarget || (SYCLTarget->getValues().size() != 1))
return JIT;
StringRef SYCLTargetStr = SYCLTarget->getValue();
if (SYCLTargetStr.starts_with("spir64_x86_64"))
return AOT_CPU;
if (SYCLTargetStr == "intel_gpu_pvc")
return AOT_PVC;
if (SYCLTargetStr.starts_with("intel_gpu_dg2"))
return AOT_DG2;
if (SYCLTargetStr.starts_with("spir64_gen")) {
ArgStringList TargArgs;
Args.AddAllArgValues(TargArgs, options::OPT_Xs, options::OPT_Xs_separate);
Args.AddAllArgValues(TargArgs, options::OPT_Xsycl_backend);
llvm::opt::Arg *A = nullptr;
if ((A = Args.getLastArg(options::OPT_Xsycl_backend_EQ)) &&
StringRef(A->getValue()).starts_with("spir64_gen"))
TargArgs.push_back(A->getValue(1));
return getSpecificGPUTarget(TargArgs);
}
return JIT;
};
std::string SanitizeVal;
size_t sanitizer_lib_idx = getSingleBuildTarget();
if (Arg *A = Args.getLastArg(options::OPT_fsanitize_EQ,
options::OPT_fno_sanitize_EQ)) {
if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
A->getValues().size() == 1) {
SanitizeVal = A->getValue();
}
} else {
// User can pass -fsanitize=address to device compiler via
// -Xsycl-target-frontend, sanitize device library must be
// linked with user's device image if so.
std::vector<std::string> EnabledDeviceSanitizers;
// NOTE: "-fsanitize=" applies to all device targets
auto SyclFEArgVals = Args.getAllArgValues(options::OPT_Xsycl_frontend);
auto SyclFEEQArgVals = Args.getAllArgValues(options::OPT_Xsycl_frontend_EQ);
auto ArchDeviceVals = Args.getAllArgValues(options::OPT_Xarch_device);
std::vector<std::string> ArgVals(
SyclFEArgVals.size() + SyclFEEQArgVals.size() + ArchDeviceVals.size());
ArgVals.insert(ArgVals.end(), SyclFEArgVals.begin(), SyclFEArgVals.end());
ArgVals.insert(ArgVals.end(), SyclFEEQArgVals.begin(),
SyclFEEQArgVals.end());
ArgVals.insert(ArgVals.end(), ArchDeviceVals.begin(), ArchDeviceVals.end());
// Driver will report error if more than one of address sanitizer, memory
// sanitizer or thread sanitizer is enabled, so we only need to check first
// one here.
for (const std::string &Arg : ArgVals) {
if (Arg.find("-fsanitize=address") != std::string::npos) {
SanitizeVal = "address";
break;
}
if (Arg.find("-fsanitize=memory") != std::string::npos) {
SanitizeVal = "memory";
break;
}
if (Arg.find("-fsanitize=thread") != std::string::npos) {
SanitizeVal = "thread";
break;
}
}
}
const SmallVector<StringRef, 5> SYCLDeviceAsanLibs = {
"libsycl-asan", "libsycl-asan-cpu", "libsycl-asan-dg2",
"libsycl-asan-pvc"};
const SmallVector<StringRef, 5> SYCLDeviceMsanLibs = {
"libsycl-msan", "libsycl-msan-cpu",
// Currently, we only provide aot msan libdevice for PVC and CPU.
// For DG2, we just use libsycl-msan as placeholder.
"libsycl-msan", "libsycl-msan-pvc"};
const SmallVector<StringRef, 5> SYCLDeviceTsanLibs = {
"libsycl-tsan", "libsycl-tsan-cpu",
// Currently, we only provide aot tsan libdevice for PVC and CPU.
// For DG2, we just use libsycl-tsan as placeholder.
// TODO: replace "libsycl-tsan" with "libsycl-tsan-dg2" when DG2
// AOT support is added.
"libsycl-tsan", "libsycl-tsan-pvc"};
if (SanitizeVal == "address")
addSingleLibrary(SYCLDeviceAsanLibs[sanitizer_lib_idx]);
else if (SanitizeVal == "memory")
addSingleLibrary(SYCLDeviceMsanLibs[sanitizer_lib_idx]);
else if (SanitizeVal == "thread")
addSingleLibrary(SYCLDeviceTsanLibs[sanitizer_lib_idx]);
}
#endif
// Returns the list of SYCL device library names for the given target.
SmallVector<ToolChain::BitCodeLibraryInfo, 8>
SYCLToolChain::getDeviceLibNames(const Driver &D,
const llvm::opt::ArgList &Args,
const llvm::Triple &TargetTriple) const {
SmallVector<ToolChain::BitCodeLibraryInfo, 8> LibraryList;
bool NoOffloadLib =
!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true);
// Default internalization to 'true' for these libraries, as they are
// expected to link with -mlink-builtin-bitcode.
auto addLibToList = [&LibraryList](StringRef LibName,
bool Internalize = true) {
BitCodeLibraryInfo BitCodeLibrary({LibName, Internalize});
LibraryList.emplace_back(BitCodeLibrary);
};
if (TargetTriple.isNVPTX()) {
if (!NoOffloadLib)
addLibToList("devicelib-nvptx64-nvidia-cuda.bc");
return LibraryList;
}
if (TargetTriple.isAMDGCN()) {
if (!NoOffloadLib)
addLibToList("devicelib-amdgcn-amd-amdhsa.bc");
return LibraryList;
}
// Ignore no-offloadlib for NativeCPU device library, it provides some
// critical builtins which must be linked with user's device image.
if (TargetTriple.isNativeCPU()) {
addLibToList("libsycl-nativecpu_utils.bc");
return LibraryList;
}
using SYCLDeviceLibsList = SmallVector<StringRef>;
const SYCLDeviceLibsList SYCLDeviceLibs = {"libsycl-crt",
"libsycl-complex",
"libsycl-complex-fp64",
"libsycl-cmath",
"libsycl-cmath-fp64",
#if defined(_WIN32)
"libsycl-msvc-math",
#endif
"libsycl-imf",
"libsycl-imf-fp64",
"libsycl-imf-bf16",
"libsycl-fallback-cstring",
"libsycl-fallback-complex",
"libsycl-fallback-complex-fp64",
"libsycl-fallback-cmath",
"libsycl-fallback-cmath-fp64",
#if !defined(_WIN32)
"libclang_rt.builtins",
#endif
"libsycl-fallback-imf",
"libsycl-fallback-imf-fp64",
"libsycl-fallback-imf-bf16"};
auto addLibraries = [&](const SYCLDeviceLibsList &LibsList) {
for (const StringRef &Lib : LibsList)
addLibToList(Args.MakeArgString(Lib + ".bc"));
};
if (!NoOffloadLib)
addLibraries(SYCLDeviceLibs);
// ITT annotation libraries are linked in separately whenever the device
// code instrumentation is enabled.
const SYCLDeviceLibsList SYCLDeviceAnnotationLibs = {
"libsycl-itt-user-wrappers", "libsycl-itt-compiler-wrappers",
"libsycl-itt-stubs"};
if (Args.hasFlag(options::OPT_fsycl_instrument_device_code,
options::OPT_fno_sycl_instrument_device_code, true))
addLibraries(SYCLDeviceAnnotationLibs);
const SYCLDeviceLibsList SYCLDeviceBfloat16FallbackLib = {
"libsycl-fallback-bfloat16"};
const SYCLDeviceLibsList SYCLDeviceBfloat16NativeLib = {
"libsycl-native-bfloat16"};
bool NativeBfloatLibs;
bool NeedBfloatLibs =
selectBfloatLibs(Args, TargetTriple, *this, NativeBfloatLibs);
if (NeedBfloatLibs && !NoOffloadLib) {
// Add native or fallback bfloat16 library.
if (NativeBfloatLibs)
addLibraries(SYCLDeviceBfloat16NativeLib);
else
addLibraries(SYCLDeviceBfloat16FallbackLib);
}
// Currently, device sanitizer support is required by some developers on
// Linux platform only, so compiler only provides device sanitizer libraries
// on Linux platform.
#if !defined(_WIN32)
addSYCLDeviceSanitizerLibs(Args, LibraryList);
#endif
return LibraryList;
}
/// Reads device config file to find information about the SYCL targets in
/// `Targets`, and defines device traits macros accordingly.
void SYCL::populateSYCLDeviceTraitsMacrosArgs(
Compilation &C, const llvm::opt::ArgList &Args,
const SmallVectorImpl<std::pair<const ToolChain *, StringRef>> &Targets) {
if (Targets.empty())
return;
const auto &TargetTable = DeviceConfigFile::TargetTable;
std::map<StringRef, unsigned int> AllDevicesHave;
std::map<StringRef, bool> AnyDeviceHas;
bool AnyDeviceHasAnyAspect = false;
unsigned int ValidTargets = 0;
for (const auto &[TC, BoundArch] : Targets) {
assert(TC && "Invalid SYCL Offload Toolchain");
// Try and find the device arch, if it's empty, try to search for either
// the whole Triple or just the 'ArchName' string.
auto TargetIt = TargetTable.end();
const llvm::Triple &TargetTriple = TC->getTriple();
const StringRef TargetArch{BoundArch};
if (!TargetArch.empty()) {
TargetIt = llvm::find_if(TargetTable, [&](const auto &Value) {
using namespace tools::SYCL;
StringRef Device{Value.first};
if (Device.consume_front(gen::AmdGPU))
return TargetArch == Device && TargetTriple.isAMDGCN();
if (Device.consume_front(gen::NvidiaGPU))
return TargetArch == Device && TargetTriple.isNVPTX();
if (Device.consume_front(gen::IntelGPU))
return TargetArch == Device && TargetTriple.isSPIRAOT();
return TargetArch == Device;
});
} else {
TargetIt = TargetTable.find(TargetTriple.str());
if (TargetIt == TargetTable.end())
TargetIt = TargetTable.find(TargetTriple.getArchName().str());
}
if (TargetIt != TargetTable.end()) {
const DeviceConfigFile::TargetInfo &Info = (*TargetIt).second;
++ValidTargets;
const auto &AspectList = Info.aspects;
const auto &MaySupportOtherAspects = Info.maySupportOtherAspects;
if (!AnyDeviceHasAnyAspect)
AnyDeviceHasAnyAspect = MaySupportOtherAspects;
for (const auto &Aspect : AspectList) {
// If target has an entry in the config file, the set of aspects
// supported by all devices supporting the target is 'AspectList'.
// If there's no entry, such set is empty.
const auto &AspectIt = AllDevicesHave.find(Aspect);
if (AspectIt != AllDevicesHave.end())
++AllDevicesHave[Aspect];
else
AllDevicesHave[Aspect] = 1;
// If target has an entry in the config file AND
// 'MaySupportOtherAspects' is false, the set of aspects supported
// by any device supporting the target is 'AspectList'. If there's
// no entry OR 'MaySupportOtherAspects' is true, such set contains
// all the aspects.
AnyDeviceHas[Aspect] = true;
}
}
}
// If there's no entry for the target in the device config file, the set
// of aspects supported by any device supporting the target contains all
// the aspects.
if (ValidTargets == 0)
AnyDeviceHasAnyAspect = true;
const Driver &D = C.getDriver();
if (AnyDeviceHasAnyAspect) {
// There exists some target that supports any given aspect.
constexpr static StringRef MacroAnyDeviceAnyAspect{
"-D__SYCL_ANY_DEVICE_HAS_ANY_ASPECT__=1"};
D.addSYCLDeviceTraitsMacroArg(Args, MacroAnyDeviceAnyAspect);
} else {
// Some of the aspects are not supported at all by any of the targets.
// Thus, we need to define individual macros for each supported aspect.
for (const auto &[TargetKey, SupportedTarget] : AnyDeviceHas) {
assert(SupportedTarget);
const SmallString<64> MacroAnyDevice{
{"-D__SYCL_ANY_DEVICE_HAS_", TargetKey, "__=1"}};
D.addSYCLDeviceTraitsMacroArg(Args, MacroAnyDevice);
}
}
for (const auto &[TargetKey, SupportedTargets] : AllDevicesHave) {
if (SupportedTargets != ValidTargets)
continue;
const SmallString<64> MacroAllDevices{
{"-D__SYCL_ALL_DEVICES_HAVE_", TargetKey, "__=1"}};
D.addSYCLDeviceTraitsMacroArg(Args, MacroAllDevices);
}
}
// The list should match pre-built SYCL device library files located in
// compiler package. Once we add or remove any SYCL device library files,
// the list should be updated accordingly.
static llvm::SmallVector<StringRef, 16> SYCLDeviceLibList{
"bfloat16",
"crt",
"cmath",
"cmath-fp64",
"complex",
"complex-fp64",
#if defined(_WIN32)
"msvc-math",
#else
"asan",
"asan-pvc",
"asan-cpu",
"asan-dg2",
"msan",
"msan-pvc",
"msan-cpu",
"tsan",
"tsan-pvc",
"tsan-cpu",
#endif
"imf",
"imf-fp64",
"imf-bf16",
"itt-compiler-wrappers",
"itt-stubs",
"itt-user-wrappers",
"fallback-cstring",
"fallback-cmath",
"fallback-cmath-fp64",
"fallback-complex",
"fallback-complex-fp64",
"fallback-imf",
"fallback-imf-fp64",
"fallback-imf-bf16",
"fallback-bfloat16",
"native-bfloat16"};
const char *SYCL::Linker::constructLLVMLinkCommand(
Compilation &C, const JobAction &JA, const InputInfo &Output,
const ArgList &Args, StringRef SubArchName, StringRef OutputFilePrefix,
const InputInfoList &InputFiles) const {
// Split inputs into libraries which have 'archive' type and other inputs
// which can be either objects or list files. Object files are linked together
// in a usual way, but the libraries/list files need to be linked differently.
// We need to fetch only required symbols from the libraries. With the current
// llvm-link command line interface that can be achieved with two step
// linking: at the first step we will link objects into an intermediate
// partially linked image which on the second step will be linked with the
// libraries with --only-needed option.
ArgStringList Opts;
ArgStringList Objs;
ArgStringList Libs;
// Add the input bc's created by compile step.
// When offloading, the input file(s) could be from unbundled partially
// linked archives. The unbundled information is a list of files and not
// an actual object/archive. Take that list and pass those to the linker
// instead of the original object.
if (JA.isDeviceOffloading(Action::OFK_SYCL)) {
bool IsRDC = !shouldDoPerObjectFileLinking(C);
auto isNoRDCDeviceCodeLink = [&](const InputInfo &II) {
if (IsRDC)
return false;
if (II.getType() != clang::driver::types::TY_LLVM_BC)
return false;
if (InputFiles.size() != 2)
return false;
return &II == &InputFiles[1];
};
auto isSYCLDeviceLib = [&](const InputInfo &II) {
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
const bool IsNVPTX = this->getToolChain().getTriple().isNVPTX();
const bool IsAMDGCN = this->getToolChain().getTriple().isAMDGCN();
const bool IsSYCLNativeCPU =
this->getToolChain().getTriple().isNativeCPU();
StringRef LibPostfix = ".bc";
StringRef NewLibPostfix = ".new.o";
if (HostTC->getTriple().isWindowsMSVCEnvironment() &&
C.getDriver().IsCLMode())
NewLibPostfix = ".new.obj";
std::string FileName = this->getToolChain().getInputFilename(II);
StringRef InputFilename = llvm::sys::path::filename(FileName);
// NativeCPU links against libclc (libspirv)
if (IsSYCLNativeCPU && InputFilename.contains("libspirv"))
return true;
// AMDGCN links against our libdevice (devicelib)
if (IsAMDGCN && InputFilename.starts_with("devicelib-"))
return true;
// NVPTX links against our libclc (libspirv), our libdevice (devicelib),
// and the CUDA libdevice
if (IsNVPTX && (InputFilename.starts_with("devicelib-") ||
InputFilename.contains("libspirv") ||
InputFilename.contains("libdevice")))
return true;
if (InputFilename.starts_with("libclang_rt.builtins"))
return true;
StringRef LibSyclPrefix("libsycl-");
if (!InputFilename.starts_with(LibSyclPrefix) ||
!InputFilename.ends_with(LibPostfix) ||
InputFilename.ends_with(NewLibPostfix))
return false;
// Skip the prefix "libsycl-"
std::string PureLibName =
InputFilename.substr(LibSyclPrefix.size()).str();
if (isNoRDCDeviceCodeLink(II)) {
// Skip the final - until the . because we linked all device libs into a
// single BC in a previous action so we have a temp file name.
auto FinalDashPos = PureLibName.find_last_of('-');
auto DotPos = PureLibName.find_last_of('.');
assert((FinalDashPos != std::string::npos &&
DotPos != std::string::npos) &&
"Unexpected filename");
PureLibName =
PureLibName.substr(0, FinalDashPos) + PureLibName.substr(DotPos);
}
for (const auto &L : SYCLDeviceLibList) {
std::string DeviceLibName(L);
DeviceLibName.append(LibPostfix);
if (StringRef(PureLibName) == DeviceLibName ||
(IsNVPTX && StringRef(PureLibName).starts_with(L)))
return true;
}
return false;
};
size_t InputFileNum = InputFiles.size();
bool LinkSYCLDeviceLibs = (InputFileNum >= 2);
LinkSYCLDeviceLibs = LinkSYCLDeviceLibs && !isSYCLDeviceLib(InputFiles[0]);
for (size_t Idx = 1; Idx < InputFileNum; ++Idx)
LinkSYCLDeviceLibs =
LinkSYCLDeviceLibs && isSYCLDeviceLib(InputFiles[Idx]);
if (LinkSYCLDeviceLibs) {
Opts.push_back("-only-needed");
}
// Go through the Inputs to the link. When a listfile is encountered, we
// know it is an unbundled generated list.
for (const auto &II : InputFiles) {
std::string FileName = getToolChain().getInputFilename(II);
if (II.getType() == types::TY_Tempfilelist) {
if (IsRDC) {
// Pass the unbundled list with '@' to be processed.
Libs.push_back(C.getArgs().MakeArgString("@" + FileName));
} else {
assert(InputFiles.size() == 2 &&
"Unexpected inputs for no-RDC with temp file list");
// If we're in no-RDC mode and the input is a temp file list,
// we want to link multiple object files each against device libs,
// so we should consider this input as an object and not pass '@'.
Objs.push_back(C.getArgs().MakeArgString(FileName));
}
} else if (II.getType() == types::TY_Archive && !LinkSYCLDeviceLibs) {
Libs.push_back(C.getArgs().MakeArgString(FileName));
} else
Objs.push_back(C.getArgs().MakeArgString(FileName));
}
} else
for (const auto &II : InputFiles)
Objs.push_back(
C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
// Get llvm-link path.
SmallString<128> ExecPath(C.getDriver().Dir);
llvm::sys::path::append(ExecPath, "llvm-link");
const char *Exec = C.getArgs().MakeArgString(ExecPath);
auto AddLinkCommand = [this, &C, &JA, Exec](const char *Output,
const ArgStringList &Inputs,
const ArgStringList &Options) {
ArgStringList CmdArgs;
llvm::copy(Options, std::back_inserter(CmdArgs));
llvm::copy(Inputs, std::back_inserter(CmdArgs));
CmdArgs.push_back("-o");
CmdArgs.push_back(Output);
// TODO: temporary workaround for a problem with warnings reported by
// llvm-link when driver links LLVM modules with empty modules
CmdArgs.push_back("--suppress-warnings");
C.addCommand(std::make_unique<Command>(JA, *this,
ResponseFileSupport::AtFileUTF8(),
Exec, CmdArgs,
ArrayRef<InputInfo>{}));
};
// Add an intermediate output file.
const char *OutputFileName =
C.getArgs().MakeArgString(getToolChain().getInputFilename(Output));
if (Libs.empty())
AddLinkCommand(OutputFileName, Objs, Opts);
else {
assert(Opts.empty() && "unexpected options");
// Linker will be invoked twice if inputs contain libraries. First time we
// will link input objects into an intermediate temporary file, and on the
// second invocation intermediate temporary object will be linked with the
// libraries, but now only required symbols will be added to the final
// output.
std::string TempFile =
C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-link", "bc");
const char *LinkOutput = C.addTempFile(C.getArgs().MakeArgString(TempFile));
AddLinkCommand(LinkOutput, Objs, {});
// Now invoke linker for the second time to link required symbols from the
// input libraries.
ArgStringList LinkInputs{LinkOutput};
llvm::copy(Libs, std::back_inserter(LinkInputs));
AddLinkCommand(OutputFileName, LinkInputs, {"--only-needed"});
}
return OutputFileName;
}
// For SYCL the inputs of the linker job are SPIR-V binaries and output is
// a single SPIR-V binary. Input can also be bitcode when specified by
// the user.
void SYCL::Linker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
assert((getToolChain().getTriple().isSPIROrSPIRV() ||
getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN() ||
getToolChain().getTriple().isNativeCPU()) &&
"Unsupported target");
std::string SubArchName =
std::string(getToolChain().getTriple().getArchName());
// Prefix for temporary file name.
std::string Prefix = std::string(llvm::sys::path::stem(SubArchName));
// For CUDA, we want to link all BC files before resuming the normal
// compilation path
if (getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN()) {
InputInfoList NvptxInputs;
for (const auto &II : Inputs) {
if (!II.isFilename())
continue;
NvptxInputs.push_back(II);
}
constructLLVMLinkCommand(C, JA, Output, Args, SubArchName, Prefix,
NvptxInputs);
return;
}
InputInfoList SpirvInputs;
for (const auto &II : Inputs) {
if (!II.isFilename())
continue;
SpirvInputs.push_back(II);
}
constructLLVMLinkCommand(C, JA, Output, Args, SubArchName, Prefix,
SpirvInputs);
}