forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClangLinkerWrapper.cpp
More file actions
2934 lines (2575 loc) · 113 KB
/
ClangLinkerWrapper.cpp
File metadata and controls
2934 lines (2575 loc) · 113 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
//===-- clang-linker-wrapper/ClangLinkerWrapper.cpp -----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This tool works as a wrapper over a linking job. This tool is used to create
// linked device images for offloading. It scans the linker's input for embedded
// device offloading data stored in sections `.llvm.offloading` and extracts it
// as a temporary file. The extracted device files will then be passed to a
// device linking job to create a final device image.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Cuda.h"
#include "clang/Basic/TargetID.h"
#include "clang/Basic/Version.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/Frontend/Offloading/OffloadWrapper.h"
#include "llvm/Frontend/Offloading/SYCLOffloadWrapper.h"
#include "llvm/Frontend/Offloading/Utility.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/LTO/LTO.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/IRObjectFile.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/OffloadBinary.h"
#include "llvm/Object/SYCLBIN.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Plugins/PassPlugin.h"
#include "llvm/Remarks/HotnessThresholdParser.h"
#include "llvm/SYCLLowerIR/SpecConstants.h"
#include "llvm/SYCLPostLink/ModuleSplitter.h"
#include "llvm/SYCLPostLink/SYCLPostLink.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/TargetParser/Host.h"
#include <optional>
#define COMPILE_OPTS "compile-opts"
#define LINK_OPTS "link-opts"
using namespace llvm;
using namespace llvm::opt;
using namespace llvm::object;
// Various tools (e.g., llc and opt) duplicate this series of declarations for
// options related to passes and remarks.
static cl::opt<bool> RemarksWithHotness(
"pass-remarks-with-hotness",
cl::desc("With PGO, include profile count in optimization remarks"),
cl::Hidden);
static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
RemarksHotnessThreshold(
"pass-remarks-hotness-threshold",
cl::desc("Minimum profile count required for "
"an optimization remark to be output. "
"Use 'auto' to apply the threshold from profile summary."),
cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
static cl::opt<std::string>
RemarksFilename("pass-remarks-output",
cl::desc("Output filename for pass remarks"),
cl::value_desc("filename"));
static cl::opt<std::string>
RemarksPasses("pass-remarks-filter",
cl::desc("Only record optimization remarks from passes whose "
"names match the given regular expression"),
cl::value_desc("regex"));
static cl::opt<std::string> RemarksFormat(
"pass-remarks-format",
cl::desc("The format used for serializing remarks (default: YAML)"),
cl::value_desc("format"), cl::init("yaml"));
static cl::list<std::string>
PassPlugins("load-pass-plugin",
cl::desc("Load passes from plugin library"));
static cl::opt<std::string> PassPipeline(
"passes",
cl::desc(
"A textual description of the pass pipeline. To have analysis passes "
"available before a certain pass, add 'require<foo-analysis>'. "
"'-passes' overrides the pass pipeline (but not all effects) from "
"specifying '--opt-level=O?' (O2 is the default) to "
"clang-linker-wrapper. Be sure to include the corresponding "
"'default<O?>' in '-passes'."));
static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),
cl::desc("Alias for -passes"));
/// Path of the current binary.
static const char *LinkerExecutable;
/// Save intermediary results.
static bool SaveTemps = false;
/// Print arguments without executing.
static bool DryRun = false;
/// Print verbose output.
static bool Verbose = false;
/// Filename of the executable being created.
static StringRef ExecutableName;
/// Binary path for the CUDA installation.
static std::string CudaBinaryPath;
/// Mutex lock to protect writes to shared TempFiles in parallel.
static std::mutex TempFilesMutex;
/// Temporary files created by the linker wrapper.
static std::list<SmallString<128>> TempFiles;
/// Codegen flags for LTO backend.
static codegen::RegisterCodeGenFlags CodeGenFlags;
static std::optional<llvm::module_split::IRSplitMode> SYCLModuleSplitMode;
static bool UseSYCLPostLinkTool;
static bool OutputSYCLBIN = false;
static SYCLBIN::BundleState SYCLBINState = SYCLBIN::BundleState::Input;
static SmallString<128> OffloadImageDumpDir;
/// Whether or not to look through symlinks when resolving binaries.
static bool CanonicalPrefixes = true;
using OffloadingImage = OffloadBinary::OffloadingImage;
namespace llvm {
// Provide DenseMapInfo so that OffloadKind can be used in a DenseMap.
template <> struct DenseMapInfo<OffloadKind> {
static inline OffloadKind getEmptyKey() { return OFK_LAST; }
static inline OffloadKind getTombstoneKey() {
return static_cast<OffloadKind>(OFK_LAST + 1);
}
static unsigned getHashValue(const OffloadKind &Val) { return Val; }
static bool isEqual(const OffloadKind &LHS, const OffloadKind &RHS) {
return LHS == RHS;
}
};
} // namespace llvm
namespace {
using std::error_code;
/// Must not overlap with llvm::opt::DriverFlag.
enum WrapperFlags {
WrapperOnlyOption = (1 << 4), // Options only used by the linker wrapper.
DeviceOnlyOption = (1 << 5), // Options only used for device linking.
};
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
#include "LinkerWrapperOpts.inc"
LastOption
#undef OPTION
};
#define OPTTABLE_STR_TABLE_CODE
#include "LinkerWrapperOpts.inc"
#undef OPTTABLE_STR_TABLE_CODE
#define OPTTABLE_PREFIXES_TABLE_CODE
#include "LinkerWrapperOpts.inc"
#undef OPTTABLE_PREFIXES_TABLE_CODE
static constexpr OptTable::Info InfoTable[] = {
#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
#include "LinkerWrapperOpts.inc"
#undef OPTION
};
class WrapperOptTable : public opt::GenericOptTable {
public:
WrapperOptTable()
: opt::GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable) {}
};
const OptTable &getOptTable() {
static const WrapperOptTable Table;
return Table;
}
void printCommands(ArrayRef<StringRef> CmdArgs) {
if (CmdArgs.empty())
return;
llvm::errs() << " \"" << CmdArgs.front() << "\" ";
for (auto IC = std::next(CmdArgs.begin()), IE = CmdArgs.end(); IC != IE; ++IC)
llvm::errs() << *IC << (std::next(IC) != IE ? " " : "\n");
}
[[noreturn]] void reportError(Error E) {
outs().flush();
logAllUnhandledErrors(std::move(E),
WithColor::error(errs(), LinkerExecutable));
exit(EXIT_FAILURE);
}
/// Create an extra user-specified \p OffloadFile.
/// TODO: We should find a way to wrap these as libraries instead.
Expected<OffloadFile> getInputBitcodeLibrary(StringRef Input) {
auto [Device, Path] = StringRef(Input).split('=');
auto [String, Arch] = Device.rsplit('-');
auto [Kind, Triple] = String.split('-');
llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> ImageOrError =
llvm::MemoryBuffer::getFileOrSTDIN(Path);
if (std::error_code EC = ImageOrError.getError())
return createFileError(Path, EC);
OffloadingImage Image{};
Image.TheImageKind = IMG_Bitcode;
Image.TheOffloadKind = getOffloadKind(Kind);
Image.StringData["triple"] = Triple;
Image.StringData["arch"] = Arch;
Image.Image = std::move(*ImageOrError);
std::unique_ptr<MemoryBuffer> Binary = MemoryBuffer::getMemBufferCopy(
OffloadBinary::write(Image), Image.Image->getBufferIdentifier());
auto NewBinaryOrErr = OffloadBinary::create(*Binary);
if (!NewBinaryOrErr)
return NewBinaryOrErr.takeError();
return OffloadFile(std::move((*NewBinaryOrErr)[0]), std::move(Binary));
}
std::string getExecutableDir(const char *Name) {
if (!CanonicalPrefixes)
return sys::path::parent_path(LinkerExecutable).str();
void *Ptr = reinterpret_cast<void *>(&getExecutableDir);
return sys::path::parent_path(sys::fs::getMainExecutable(Name, Ptr)).str();
}
/// Get a temporary filename suitable for output.
Expected<StringRef> createOutputFile(const Twine &Prefix, StringRef Extension) {
std::scoped_lock<decltype(TempFilesMutex)> Lock(TempFilesMutex);
SmallString<128> OutputFile;
std::string PrefixStr = clang::sanitizeTargetIDInFileName(Prefix.str());
if (SaveTemps) {
// Generate a unique path name without creating a file
sys::fs::createUniquePath(Prefix + "-%%%%%%." + Extension, OutputFile,
/*MakeAbsolute=*/false);
(PrefixStr + "." + Extension).toNullTerminatedStringRef(OutputFile);
} else {
if (std::error_code EC =
sys::fs::createTemporaryFile(PrefixStr, Extension, OutputFile))
return createFileError(OutputFile, EC);
}
TempFiles.emplace_back(std::move(OutputFile));
return TempFiles.back();
}
Error containerizeRawImage(std::unique_ptr<MemoryBuffer> &Img, OffloadKind Kind,
const ArgList &Args) {
llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
if (Kind == OFK_OpenMP && Triple.isSPIRV() &&
Triple.getVendor() == llvm::Triple::Intel)
return offloading::intel::containerizeOpenMPSPIRVImage(Img);
return Error::success();
}
// TODO: Remove HasSYCLOffloadKind dependence when aligning with community code.
Expected<StringRef> writeOffloadFile(const OffloadFile &File,
bool HasSYCLOffloadKind = false) {
const OffloadBinary &Binary = *File.getBinary();
StringRef Prefix =
sys::path::stem(Binary.getMemoryBufferRef().getBufferIdentifier());
StringRef BinArch = (Binary.getArch() == "*") ? "any" : Binary.getArch();
auto TempFileOrErr = createOutputFile(
Prefix + "-" + Binary.getTriple() + "-" + BinArch,
HasSYCLOffloadKind ? getImageKindName(Binary.getImageKind()) : "o");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
Expected<std::unique_ptr<FileOutputBuffer>> OutputOrErr =
FileOutputBuffer::create(*TempFileOrErr, Binary.getImage().size());
if (!OutputOrErr)
return OutputOrErr.takeError();
std::unique_ptr<FileOutputBuffer> Output = std::move(*OutputOrErr);
llvm::copy(Binary.getImage(), Output->getBufferStart());
if (Error E = Output->commit())
return std::move(E);
return *TempFileOrErr;
}
/// Execute the command \p ExecutablePath with the arguments \p Args.
Error executeCommands(StringRef ExecutablePath, ArrayRef<StringRef> Args) {
if (Verbose || DryRun)
printCommands(Args);
if (DryRun)
return Error::success();
// If the command line fits within system limits, execute directly.
if (sys::commandLineFitsWithinSystemLimits(ExecutablePath, Args)) {
if (sys::ExecuteAndWait(ExecutablePath, Args))
return createStringError(
"'%s' failed", sys::path::filename(ExecutablePath).str().c_str());
return Error::success();
}
// Write the arguments to a response file and pass that instead.
auto TempFileOrErr = createOutputFile("response", "rsp");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
SmallString<256> Contents;
raw_svector_ostream OS(Contents);
for (StringRef Arg : llvm::drop_begin(Args)) {
sys::printArg(OS, Arg, /*Quote=*/true);
OS << " ";
}
if (std::error_code EC = sys::writeFileWithEncoding(*TempFileOrErr, Contents))
return createStringError("failed to write response file: %s",
EC.message().c_str());
std::string ResponseFile = ("@" + *TempFileOrErr).str();
SmallVector<StringRef, 2> NewArgs = {Args.front(), ResponseFile};
if (sys::ExecuteAndWait(ExecutablePath, NewArgs))
return createStringError("'%s' failed",
sys::path::filename(ExecutablePath).str().c_str());
return Error::success();
}
Expected<std::string> findProgram(StringRef Name, ArrayRef<StringRef> Paths) {
ErrorOr<std::string> Path = sys::findProgramByName(Name, Paths);
if (!Path)
Path = sys::findProgramByName(Name);
if (!Path && DryRun)
return Name.str();
if (!Path)
return createStringError(Path.getError(),
"Unable to find '" + Name + "' in path");
return *Path;
}
bool linkerSupportsLTO(const ArgList &Args) {
llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
return Triple.isNVPTX() || Triple.isAMDGPU() ||
(!Triple.isGPU() &&
Args.getLastArgValue(OPT_linker_path_EQ).ends_with("lld"));
}
/// Returns the hashed value for a constant string.
std::string getHash(StringRef Str) {
llvm::MD5 Hasher;
llvm::MD5::MD5Result Hash;
Hasher.update(Str);
Hasher.final(Hash);
return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
}
/// Renames offloading entry sections in a relocatable link so they do not
/// conflict with a later link job.
Error relocateOffloadSection(const ArgList &Args, StringRef Output) {
llvm::Triple Triple(
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
if (Triple.isOSWindows())
return createStringError(
"Relocatable linking is not supported on COFF targets");
Expected<std::string> ObjcopyPath =
findProgram("llvm-objcopy", {getExecutableDir("llvm-objcopy")});
if (!ObjcopyPath)
return ObjcopyPath.takeError();
// Use the linker output file to get a unique hash. This creates a unique
// identifier to rename the sections to that is deterministic to the contents.
auto BufferOrErr = DryRun ? MemoryBuffer::getMemBuffer("")
: MemoryBuffer::getFileOrSTDIN(Output);
if (!BufferOrErr)
return createStringError("Failed to open %s", Output.str().c_str());
std::string Suffix = "_" + getHash((*BufferOrErr)->getBuffer());
SmallVector<StringRef> ObjcopyArgs = {
*ObjcopyPath,
Output,
};
// Remove the old .llvm.offloading section to prevent further linking.
ObjcopyArgs.emplace_back("--remove-section");
ObjcopyArgs.emplace_back(".llvm.offloading");
StringRef Prefix = "llvm";
auto Section = (Prefix + "_offload_entries").str();
// Rename the offloading entries to make them private to this link unit.
ObjcopyArgs.emplace_back("--rename-section");
ObjcopyArgs.emplace_back(
Args.MakeArgString(Section + "=" + Section + Suffix));
// Rename the __start_ / __stop_ symbols appropriately to iterate over the
// newly renamed section containing the offloading entries.
ObjcopyArgs.emplace_back("--redefine-sym");
ObjcopyArgs.emplace_back(Args.MakeArgString("__start_" + Section + "=" +
"__start_" + Section + Suffix));
ObjcopyArgs.emplace_back("--redefine-sym");
ObjcopyArgs.emplace_back(Args.MakeArgString("__stop_" + Section + "=" +
"__stop_" + Section + Suffix));
if (Error Err = executeCommands(*ObjcopyPath, ObjcopyArgs))
return Err;
return Error::success();
}
/// Runs the wrapped linker job with the newly created input.
Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) {
llvm::TimeTraceScope TimeScope("Execute host linker");
// Render the linker arguments and add the newly created image. We add it
// after the output file to ensure it is linked with the correct libraries.
StringRef LinkerPath = Args.getLastArgValue(OPT_linker_path_EQ);
if (LinkerPath.empty())
return createStringError("linker path missing, must pass 'linker-path'");
ArgStringList NewLinkerArgs;
for (const opt::Arg *Arg : Args) {
// Do not forward arguments only intended for the linker wrapper.
if (Arg->getOption().hasFlag(WrapperOnlyOption))
continue;
Arg->render(Args, NewLinkerArgs);
if (Arg->getOption().matches(OPT_o) || Arg->getOption().matches(OPT_out))
llvm::transform(Files, std::back_inserter(NewLinkerArgs),
[&](StringRef A) { return Args.MakeArgString(A); });
}
SmallVector<StringRef> LinkerArgs({LinkerPath});
for (StringRef Arg : NewLinkerArgs)
LinkerArgs.push_back(Arg);
if (Error Err = executeCommands(LinkerPath, LinkerArgs))
return Err;
if (Args.hasArg(OPT_relocatable))
return relocateOffloadSection(Args, ExecutableName);
return Error::success();
}
void printVersion(raw_ostream &OS) {
OS << clang::getClangToolFullVersion("clang-linker-wrapper") << '\n';
}
namespace nvptx {
Expected<StringRef>
fatbinary(ArrayRef<std::pair<StringRef, StringRef>> InputFiles,
const ArgList &Args) {
llvm::TimeTraceScope TimeScope("NVPTX fatbinary");
// NVPTX uses the fatbinary program to bundle the linked images.
Expected<std::string> FatBinaryPath =
findProgram("fatbinary", {CudaBinaryPath + "/bin"});
if (!FatBinaryPath)
return FatBinaryPath.takeError();
llvm::Triple Triple(
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
// Create a new file to write the linked device image to.
auto TempFileOrErr =
createOutputFile(sys::path::filename(ExecutableName), "fatbin");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
SmallVector<StringRef, 16> CmdArgs;
CmdArgs.push_back(*FatBinaryPath);
CmdArgs.push_back(Triple.isArch64Bit() ? "-64" : "-32");
CmdArgs.push_back("--create");
CmdArgs.push_back(*TempFileOrErr);
for (const auto &[File, Arch] : InputFiles) {
StringRef Kind = "elf";
StringRef ArchId = Arch;
if (Arch.starts_with("sm_")) {
ArchId = Arch.drop_front(3);
} else if (Arch.starts_with("compute_")) {
Kind = "ptx";
ArchId = Arch.drop_front(8);
}
CmdArgs.push_back(Args.MakeArgString("--image3=kind=" + Kind +
",sm=" + ArchId + ",file=" + File));
}
if (Error Err = executeCommands(*FatBinaryPath, CmdArgs))
return std::move(Err);
return *TempFileOrErr;
}
// ptxas binary
Expected<StringRef> ptxas(StringRef InputFile, const ArgList &Args,
StringRef Arch) {
llvm::TimeTraceScope TimeScope("NVPTX ptxas");
// NVPTX uses the ptxas program to process assembly files.
Expected<std::string> PtxasPath =
findProgram("ptxas", {CudaBinaryPath + "/bin"});
if (!PtxasPath)
return PtxasPath.takeError();
llvm::Triple Triple(
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
// Create a new file to write the output to.
auto TempFileOrErr =
createOutputFile(sys::path::filename(ExecutableName), "cubin");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
SmallVector<StringRef, 16> CmdArgs;
CmdArgs.push_back(*PtxasPath);
CmdArgs.push_back(Triple.isArch64Bit() ? "-m64" : "-m32");
// Pass -v to ptxas if it was passed to the driver.
CmdArgs.push_back("--gpu-name");
CmdArgs.push_back(Arch);
CmdArgs.push_back("--output-file");
CmdArgs.push_back(*TempFileOrErr);
CmdArgs.push_back(InputFile);
if (Error Err = executeCommands(*PtxasPath, CmdArgs))
return std::move(Err);
return *TempFileOrErr;
}
} // namespace nvptx
namespace amdgcn {
// Constructs a triple string for clang offload bundler.
// NOTE: copied from HIPUtility.cpp.
static std::string normalizeForBundler(const llvm::Triple &T,
bool HasTargetID) {
return HasTargetID ? (T.getArchName() + "-" + T.getVendorName() + "-" +
T.getOSName() + "-" + T.getEnvironmentName())
.str()
: T.normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
}
Expected<StringRef>
fatbinary(ArrayRef<std::tuple<StringRef, StringRef, StringRef>> InputFiles,
const ArgList &Args) {
llvm::TimeTraceScope TimeScope("AMDGPU Fatbinary");
// AMDGPU uses the clang-offload-bundler to bundle the linked images.
Expected<std::string> OffloadBundlerPath = findProgram(
"clang-offload-bundler", {getExecutableDir("clang-offload-bundler")});
if (!OffloadBundlerPath)
return OffloadBundlerPath.takeError();
// Create a new file to write the linked device image to.
auto TempFileOrErr =
createOutputFile(sys::path::filename(ExecutableName), "hipfb");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
BumpPtrAllocator Alloc;
StringSaver Saver(Alloc);
SmallVector<StringRef, 16> CmdArgs;
CmdArgs.push_back(*OffloadBundlerPath);
CmdArgs.push_back("-type=o");
CmdArgs.push_back("-bundle-align=4096");
if (Args.hasArg(OPT_compress))
CmdArgs.push_back("-compress");
if (auto *Arg = Args.getLastArg(OPT_compression_level_eq))
CmdArgs.push_back(
Args.MakeArgString(Twine("-compression-level=") + Arg->getValue()));
llvm::Triple HostTriple(
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
SmallVector<StringRef> Targets = {
Saver.save("-targets=host-" + HostTriple.normalize())};
for (const auto &[File, TripleRef, Arch] : InputFiles) {
std::string NormalizedTriple =
normalizeForBundler(Triple(TripleRef), !Arch.empty());
Targets.push_back(Saver.save("hip-" + NormalizedTriple + "-" + Arch));
}
CmdArgs.push_back(Saver.save(llvm::join(Targets, ",")));
#ifdef _WIN32
CmdArgs.push_back("-input=NUL");
#else
CmdArgs.push_back("-input=/dev/null");
#endif
for (const auto &[File, Triple, Arch] : InputFiles)
CmdArgs.push_back(Saver.save("-input=" + File));
CmdArgs.push_back(Saver.save("-output=" + *TempFileOrErr));
if (Error Err = executeCommands(*OffloadBundlerPath, CmdArgs))
return std::move(Err);
return *TempFileOrErr;
}
} // namespace amdgcn
namespace sycl {
// This utility function is used to gather all SYCL device library files that
// will be linked with input device files.
// The list of files and its location are passed from driver.
static Error getSYCLDeviceLibs(SmallVector<std::string, 16> &DeviceLibFiles,
const ArgList &Args) {
StringRef SYCLDeviceLibLoc("");
if (Arg *A = Args.getLastArg(OPT_sycl_device_library_location_EQ))
SYCLDeviceLibLoc = A->getValue();
if (Arg *A = Args.getLastArg(OPT_sycl_device_lib_EQ)) {
if (A->getValues().size() == 0)
return createStringError(
inconvertibleErrorCode(),
"Number of device library files cannot be zero.");
for (StringRef Val : A->getValues()) {
SmallString<128> LibName(SYCLDeviceLibLoc);
llvm::sys::path::append(LibName, Val);
if (llvm::sys::fs::exists(LibName))
DeviceLibFiles.push_back(std::string(LibName));
else
return createStringError(inconvertibleErrorCode(),
std::string(LibName) +
" SYCL device library file is not found.");
}
}
return Error::success();
}
/// This routine is used to convert SPIR-V input files into LLVM IR files.
/// 'llvm-spirv -r' command is used for this purpose.
/// If input is not a SPIR-V file, then the original file is returned.
/// TODO: Add a check to identify SPIR-V files and exit early if the input is
/// not a SPIR-V file.
/// 'Filename' is the input file that could be a SPIR-V file.
/// 'Args' encompasses all arguments required for linking and wrapping device
/// code and will be parsed to generate options required to be passed into the
/// llvm-spirv tool.
static Expected<StringRef> convertSPIRVToIR(StringRef Filename,
const ArgList &Args) {
Expected<std::string> SPIRVToIRWrapperPath = findProgram(
"spirv-to-ir-wrapper", {getExecutableDir("spirv-to-ir-wrapper")});
if (!SPIRVToIRWrapperPath)
return SPIRVToIRWrapperPath.takeError();
// Create a new file to write the converted file to.
auto TempFileOrErr =
createOutputFile(sys::path::filename(ExecutableName), "bc");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
SmallVector<StringRef, 8> CmdArgs;
CmdArgs.push_back(*SPIRVToIRWrapperPath);
CmdArgs.push_back(Filename);
CmdArgs.push_back("-o");
CmdArgs.push_back(*TempFileOrErr);
CmdArgs.push_back("--llvm-spirv-opts");
CmdArgs.push_back("--spirv-preserve-auxdata --spirv-target-env=SPV-IR "
"--spirv-builtin-format=global");
if (Error Err = executeCommands(*SPIRVToIRWrapperPath, CmdArgs))
return std::move(Err);
return *TempFileOrErr;
}
/// \brief Creates and configures PostLinkSettings for SYCL post-link
/// processing.
///
/// This function analyzes command line arguments and target triple
/// to determine the settings for the SYCL post-link phase.
///
/// \param Args The command line argument list containing SYCL-specific flags
/// and options that influence post-link behavior.
/// \param Triple The target triple specifying the target architecture
/// (e.g., NVPTX, AMDGCN, SPIR, native CPU).
///
/// \return A configured PostLinkSettings object with target-specific and
/// argument-driven settings applied.
static sycl_post_link::PostLinkSettings
getSYCLPostLinkSettings(const ArgList &Args, const llvm::Triple Triple) {
sycl_post_link::PostLinkSettings Settings;
bool SpecConstsSupported = (!Triple.isNVPTX() && !Triple.isAMDGCN() &&
!Triple.isSPIRAOT() && !Triple.isNativeCPU());
if (SpecConstsSupported)
Settings.SpecConstMode = SpecConstantsPass::HandlingMode::native;
else
Settings.SpecConstMode = SpecConstantsPass::HandlingMode::emulation;
// On Intel targets we don't need non-kernel functions as entry points,
// because it only increases amount of code for device compiler to handle,
// without any actual benefits.
// TODO: Try to extend this feature for non-Intel GPUs.
if (!Args.hasFlag(OPT_no_sycl_remove_unused_external_funcs,
OPT_sycl_remove_unused_external_funcs, false) &&
!Args.hasArg(OPT_sycl_allow_device_image_dependencies) &&
!Triple.isNVPTX() && !Triple.isAMDGPU())
Settings.EmitOnlyKernelsAsEntryPoints = true;
if (!Triple.isAMDGCN())
Settings.EmitParamInfo = true;
if (Triple.isNVPTX() || Triple.isAMDGCN() || Triple.isNativeCPU())
Settings.EmitProgramMetadata = true;
if (Args.hasArg(OPT_syclbin_EQ))
Settings.EmitKernelNames = true;
// Specialization constant info generation is mandatory -
// add options unconditionally.
Settings.EmitExportedSymbols = true;
Settings.EmitImportedSymbols = true;
bool SplitEsimdByDefault = Triple.isSPIROrSPIRV();
if (Args.hasFlag(OPT_sycl_device_code_split_esimd,
OPT_no_sycl_device_code_split_esimd, SplitEsimdByDefault))
Settings.ESIMDOptions.SplitESIMD = true;
// If the code doesn't contain ESIMD intrinsics then lowering has no effect.
// Otherwise, it is mandatory to lower ESIMD intrinsics.
// Therefore, it is always set true.
Settings.ESIMDOptions.LowerESIMD = true;
bool IsAOT = Triple.isNVPTX() || Triple.isAMDGCN() || Triple.isSPIRAOT();
if (Args.hasFlag(OPT_sycl_add_default_spec_consts_image,
OPT_no_sycl_add_default_spec_consts_image, false) &&
IsAOT)
Settings.GenerateModuleDescWithDefaultSpecConsts = true;
Settings.SplitMode = Settings.ESIMDOptions.SplitMode = *SYCLModuleSplitMode;
// TODO: fill AllowDeviceImageDependencies, ESIMDOptions.OptLevel and
// ESIMDOptions.ForceDisableESIMDOpt
return Settings;
}
/// Add any sycl-post-link options that rely on a specific Triple in addition
/// to user supplied options.
/// NOTE: Any changes made here should be reflected in the similarly named
/// function in clang/lib/Driver/ToolChains/Clang.cpp.
static void
getTripleBasedSYCLPostLinkOpts(const ArgList &Args,
SmallVector<StringRef, 8> &PostLinkArgs,
const llvm::Triple Triple) {
const llvm::Triple HostTriple(Args.getLastArgValue(OPT_host_triple_EQ));
bool SpecConstsSupported = (!Triple.isNVPTX() && !Triple.isAMDGCN() &&
!Triple.isSPIRAOT() && !Triple.isNativeCPU());
if (SpecConstsSupported)
PostLinkArgs.push_back("-spec-const=native");
else
PostLinkArgs.push_back("-spec-const=emulation");
// TODO: If we ever pass -ir-output-only based on the triple,
// make sure we don't pass -properties.
PostLinkArgs.push_back("-properties");
// On Intel targets we don't need non-kernel functions as entry points,
// because it only increases amount of code for device compiler to handle,
// without any actual benefits.
// TODO: Try to extend this feature for non-Intel GPUs.
if (!Args.hasFlag(OPT_no_sycl_remove_unused_external_funcs,
OPT_sycl_remove_unused_external_funcs, false) &&
!Args.hasArg(OPT_sycl_allow_device_image_dependencies) &&
!Triple.isNVPTX() && !Triple.isAMDGPU())
PostLinkArgs.push_back("-emit-only-kernels-as-entry-points");
if (!Triple.isAMDGCN())
PostLinkArgs.push_back("-emit-param-info");
// Enable program metadata
if (Triple.isNVPTX() || Triple.isAMDGCN() || Triple.isNativeCPU())
PostLinkArgs.push_back("-emit-program-metadata");
bool SplitEsimdByDefault = Triple.isSPIROrSPIRV();
bool SplitEsimd =
Args.hasFlag(OPT_sycl_device_code_split_esimd,
OPT_no_sycl_device_code_split_esimd, SplitEsimdByDefault);
if (!Args.hasArg(OPT_sycl_thin_lto))
PostLinkArgs.push_back("-symbols");
// Emit kernel names if we are producing SYCLBIN.
if (Args.hasArg(OPT_syclbin_EQ))
PostLinkArgs.push_back("-emit-kernel-names");
// Specialization constant info generation is mandatory -
// add options unconditionally
PostLinkArgs.push_back("-emit-exported-symbols");
PostLinkArgs.push_back("-emit-imported-symbols");
if (SplitEsimd)
PostLinkArgs.push_back("-split-esimd");
PostLinkArgs.push_back("-lower-esimd");
bool IsAOT = Triple.isNVPTX() || Triple.isAMDGCN() || Triple.isSPIRAOT();
if (Args.hasFlag(OPT_sycl_add_default_spec_consts_image,
OPT_no_sycl_add_default_spec_consts_image, false) &&
IsAOT)
PostLinkArgs.push_back("-generate-device-image-default-spec-consts");
}
/// Run sycl-post-link tool for SYCL offloading.
/// 'InputFiles' is the list of input LLVM IR files.
/// 'Args' encompasses all arguments required for linking and wrapping device
/// code and will be parsed to generate options required to be passed into the
/// sycl-post-link tool.
/// 'IsDevicePassedWithSyclTargetBackend' indicates whether the device
/// architecture is already specified through -Xsycl-target-backend=spir64_gen
/// "-device <arch>" format.
static Expected<std::vector<module_split::SplitModule>>
runSYCLPostLinkTool(ArrayRef<StringRef> InputFiles, const ArgList &Args,
bool IsDevicePassedWithSyclTargetBackend) {
Expected<std::string> SYCLPostLinkPath =
findProgram("sycl-post-link", {getExecutableDir("sycl-post-link")});
if (!SYCLPostLinkPath)
return SYCLPostLinkPath.takeError();
// Create a new file to write the output of sycl-post-link to.
auto TempFileOrErr =
createOutputFile(sys::path::filename(ExecutableName), "table");
if (!TempFileOrErr)
return TempFileOrErr.takeError();
std::string OutputPathWithArch = TempFileOrErr->str();
// Enable the driver to invoke sycl-post-link with the device architecture
// when Intel GPU targets are passed in -fsycl-targets.
const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
if (Triple.getSubArch() == llvm::Triple::SPIRSubArch_gen && !Arch.empty() &&
!IsDevicePassedWithSyclTargetBackend && Arch != "*")
OutputPathWithArch = "intel_gpu_" + Arch.str() + "," + OutputPathWithArch;
else if (Triple.getSubArch() == llvm::Triple::SPIRSubArch_x86_64)
OutputPathWithArch = "spir64_x86_64," + OutputPathWithArch;
SmallVector<StringRef, 8> CmdArgs;
CmdArgs.push_back(*SYCLPostLinkPath);
Arg *SYCLDeviceLibLoc = Args.getLastArg(OPT_sycl_device_library_location_EQ);
if (SYCLDeviceLibLoc && !Triple.isSPIRAOT()) {
std::string SYCLDeviceLibLocParam = SYCLDeviceLibLoc->getValue();
std::string BF16DeviceLibLoc =
SYCLDeviceLibLocParam + "/libsycl-native-bfloat16.bc";
if (llvm::sys::fs::exists(BF16DeviceLibLoc)) {
SYCLDeviceLibLocParam = "--device-lib-dir=" + SYCLDeviceLibLocParam;
CmdArgs.push_back(Args.MakeArgString(StringRef(SYCLDeviceLibLocParam)));
}
}
getTripleBasedSYCLPostLinkOpts(Args, CmdArgs, Triple);
StringRef SYCLPostLinkOptions;
if (Arg *A = Args.getLastArg(OPT_sycl_post_link_options_EQ))
SYCLPostLinkOptions = A->getValue();
SYCLPostLinkOptions.split(CmdArgs, " ", /* MaxSplit = */ -1,
/* KeepEmpty = */ false);
CmdArgs.push_back("-o");
CmdArgs.push_back(Args.MakeArgString(OutputPathWithArch));
for (auto &File : InputFiles)
CmdArgs.push_back(File);
if (Error Err = executeCommands(*SYCLPostLinkPath, CmdArgs))
return std::move(Err);
if (DryRun) {
// In DryRun we need a dummy entry in order to continue the whole pipeline.
auto ImageFileOrErr = createOutputFile(
sys::path::filename(ExecutableName) + ".sycl.split.image", "bc");
if (!ImageFileOrErr)
return ImageFileOrErr.takeError();
std::vector Modules = {module_split::SplitModule(
*ImageFileOrErr, util::PropertySetRegistry())};
return Modules;
}
return llvm::sycl_post_link::parseSplitModulesFromFile(*TempFileOrErr);
}
/// Invokes SYCLPostLink library for SYCL offloading. Specialization constant's
/// processing mode is determined depending on the Triple encoded in \p Args.
///
/// \param InputFiles the list of input LLVM IR files.
/// \param Args Encompasses all arguments for linking and wrapping device code.
/// It will be parsed to generate options required to be passed to SYCL split
/// library.
/// \param Mode The splitting mode.
/// \returns The vector of split modules.
static Expected<std::vector<module_split::SplitModule>>
runSYCLPostLinkLibrary(ArrayRef<StringRef> InputFiles, const ArgList &Args,
module_split::IRSplitMode SplitMode) {
std::vector<module_split::SplitModule> SplitModules;
const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
sycl_post_link::PostLinkSettings Settings =
getSYCLPostLinkSettings(Args, Triple);
if (DryRun) {
auto OutputFileOrErr = createOutputFile(
sys::path::filename(ExecutableName) + ".sycl.split.image", "bc");
if (!OutputFileOrErr)
return OutputFileOrErr.takeError();
StringRef OutputFilePath = *OutputFileOrErr;
auto InputFilesStr = llvm::join(InputFiles.begin(), InputFiles.end(), ",");
errs() << formatv("sycl-post-link-library: input: {0}, output: {1}, {2}\n",
InputFilesStr, OutputFilePath,
sycl_post_link::convertSettingsToString(Settings));
SplitModules.emplace_back(OutputFilePath, util::PropertySetRegistry());
return SplitModules;
}
for (StringRef InputFile : InputFiles) {
SMDiagnostic Err;
LLVMContext C;
std::unique_ptr<Module> M = parseIRFile(InputFile, Err, C);
if (!M)
return createStringError(inconvertibleErrorCode(), Err.getMessage());
Expected<std::vector<module_split::SplitModule>> SplitModulesOrErr =
sycl_post_link::performPostLinkProcessing(std::move(M), Settings);
if (!SplitModulesOrErr)
return SplitModulesOrErr.takeError();
SplitModules.insert(SplitModules.end(), SplitModulesOrErr->begin(),
SplitModulesOrErr->end());
}
if (Verbose) {
auto InputFilesStr = llvm::join(InputFiles.begin(), InputFiles.end(), ",");
std::string OutputFilesStr;
for (size_t I = 0, E = SplitModules.size(); I != E; ++I) {
if (I > 0)
OutputFilesStr += ',';
OutputFilesStr += SplitModules[I].ModuleFilePath;
}
errs() << formatv(
"sycl-post-link-library: input: {0}, output: {1}, settings: {2}\n",
InputFilesStr, OutputFilesStr,
sycl_post_link::convertSettingsToString(Settings));
}
return SplitModules;
}
/// Add any llvm-spirv option that relies on a specific Triple in addition
/// to user supplied options.
/// NOTE: Any changes made here should be reflected in the similarly named
/// function in clang/lib/Driver/ToolChains/Clang.cpp.
static void
getTripleBasedSPIRVTransOpts(const ArgList &Args,
SmallVector<StringRef, 8> &TranslatorArgs,
const llvm::Triple Triple) {
bool IsCPU = Triple.isSPIR() &&
Triple.getSubArch() == llvm::Triple::SPIRSubArch_x86_64;
TranslatorArgs.push_back("-spirv-debug-info-version=nonsemantic-shader-200");
std::string UnknownIntrinsics("-spirv-allow-unknown-intrinsics=llvm.genx.");
if (IsCPU)
UnknownIntrinsics += ",llvm.fpbuiltin";
TranslatorArgs.push_back(Args.MakeArgString(UnknownIntrinsics));
// Disable all the extensions by default
std::string ExtArg("-spirv-ext=-all");
ExtArg +=
",+SPV_EXT_shader_atomic_float_add,+SPV_EXT_shader_atomic_float_min_max"
",+SPV_KHR_no_integer_wrap_decoration,+SPV_KHR_float_controls"
",+SPV_KHR_expect_assume,+SPV_KHR_linkonce_odr"
",+SPV_INTEL_subgroups,+SPV_INTEL_media_block_io"
",+SPV_INTEL_device_side_avc_motion_estimation"
",+SPV_INTEL_fpga_loop_controls,+SPV_INTEL_unstructured_loop_controls"
",+SPV_INTEL_fpga_reg,+SPV_INTEL_blocking_pipes"
",+SPV_INTEL_function_pointers,+SPV_INTEL_kernel_attributes"
",+SPV_INTEL_io_pipes,+SPV_INTEL_inline_assembly"
",+SPV_INTEL_arbitrary_precision_integers"
",+SPV_INTEL_float_controls2,+SPV_INTEL_vector_compute"
",+SPV_INTEL_arbitrary_precision_fixed_point"
",+SPV_INTEL_arbitrary_precision_floating_point"
",+SPV_INTEL_variable_length_array,+SPV_INTEL_fp_fast_math_mode"