-
Notifications
You must be signed in to change notification settings - Fork 848
Expand file tree
/
Copy pathOffloadBundler.cpp
More file actions
2716 lines (2307 loc) · 98.4 KB
/
Copy pathOffloadBundler.cpp
File metadata and controls
2716 lines (2307 loc) · 98.4 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
//===- OffloadBundler.cpp - File Bundling and Unbundling ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements an offload bundling API that bundles different files
/// that relate with the same source code but different targets into a single
/// one. Also the implements the opposite functionality, i.e. unbundle files
/// previous created by this API.
///
//===----------------------------------------------------------------------===//
#include "clang/Driver/OffloadBundler.h"
#include "clang/Basic/Cuda.h"
#include "clang/Basic/TargetID.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/ArchiveWriter.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/Error.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/TargetParser/Host.h"
#include "llvm/TargetParser/Triple.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <forward_list>
#include <llvm/Support/Process.h>
#include <memory>
#include <set>
#include <string>
#include <system_error>
#include <unordered_set>
#include <utility>
using namespace llvm;
using namespace llvm::object;
using namespace clang;
namespace {
struct CreateClangOffloadBundlerTimerGroup {
static void *call() {
return new TimerGroup("Clang Offload Bundler Timer Group",
"Timer group for clang offload bundler");
}
};
} // namespace
static llvm::ManagedStatic<llvm::TimerGroup,
CreateClangOffloadBundlerTimerGroup>
ClangOffloadBundlerTimerGroup;
/// Magic string that marks the existence of offloading data.
#define OFFLOAD_BUNDLER_MAGIC_STR "__CLANG_OFFLOAD_BUNDLE__"
/// Section name which holds target symbol names.
#define SYMBOLS_SECTION_NAME ".tgtsym"
#define DEBUG_TYPE "clang-offload-bundler"
OffloadTargetInfo::OffloadTargetInfo(const StringRef Target,
const OffloadBundlerConfig &BC)
: BundlerConfig(BC) {
// <kind>-<triple>[-<target id>[:target features]]
// <triple> := <arch>-<vendor>-<os>-<env>
SmallVector<StringRef, 6> Components;
Target.split(Components, '-', /*MaxSplit=*/5);
if (Components.size() < 5) {
// Handle target inputs that do not fit the <arch>-<vendor>-<os>-<env>
// triple format.
auto TargetFeatures = Target.split(':');
auto TripleOrGPU = TargetFeatures.first.rsplit('-');
if (clang::StringToOffloadArch(TripleOrGPU.second) !=
clang::OffloadArch::Unknown) {
auto KindTriple = TripleOrGPU.first.split('-');
this->OffloadKind = KindTriple.first;
// Enforce optional env field to standardize bundles
llvm::Triple t = llvm::Triple(KindTriple.second);
this->Triple = llvm::Triple(t.getArchName(), t.getVendorName(),
t.getOSName(), t.getEnvironmentName());
this->TargetID = Target.substr(Target.find(TripleOrGPU.second));
} else {
auto KindTriple = TargetFeatures.first.split('-');
this->OffloadKind = KindTriple.first;
// Enforce optional env field to standardize bundles
llvm::Triple t = llvm::Triple(KindTriple.second);
this->Triple = llvm::Triple(t.getArchName(), t.getVendorName(),
t.getOSName(), t.getEnvironmentName());
this->TargetID = "";
}
return;
}
assert((Components.size() == 5 || Components.size() == 6) &&
"malformed target string");
StringRef TargetIdWithFeature =
Components.size() == 6 ? Components.back() : "";
StringRef TargetId = TargetIdWithFeature.split(':').first;
if (!TargetId.empty() &&
clang::StringToOffloadArch(TargetId) != clang::OffloadArch::Unknown)
this->TargetID = TargetIdWithFeature;
else
this->TargetID = "";
this->OffloadKind = Components.front();
ArrayRef<StringRef> TripleSlice{&Components[1], /*length=*/4};
llvm::Triple T = llvm::Triple(llvm::join(TripleSlice, "-"));
this->Triple = llvm::Triple(T.getArchName(), T.getVendorName(), T.getOSName(),
T.getEnvironmentName());
}
bool OffloadTargetInfo::hasHostKind() const {
return this->OffloadKind == "host";
}
bool OffloadTargetInfo::isOffloadKindValid() const {
return OffloadKind == "host" || OffloadKind == "openmp" ||
OffloadKind == "sycl" || OffloadKind == "hip" ||
OffloadKind == "hipv4";
}
bool OffloadTargetInfo::isOffloadKindCompatible(
const StringRef TargetOffloadKind) const {
if ((OffloadKind == TargetOffloadKind) ||
(OffloadKind == "hip" && TargetOffloadKind == "hipv4") ||
(OffloadKind == "hipv4" && TargetOffloadKind == "hip"))
return true;
if (BundlerConfig.HipOpenmpCompatible) {
bool HIPCompatibleWithOpenMP = OffloadKind.starts_with_insensitive("hip") &&
TargetOffloadKind == "openmp";
bool OpenMPCompatibleWithHIP =
OffloadKind == "openmp" &&
TargetOffloadKind.starts_with_insensitive("hip");
return HIPCompatibleWithOpenMP || OpenMPCompatibleWithHIP;
}
return false;
}
bool OffloadTargetInfo::isTripleValid() const {
return !Triple.str().empty() && Triple.getArch() != Triple::UnknownArch;
}
bool OffloadTargetInfo::operator==(const OffloadTargetInfo &Target) const {
return OffloadKind == Target.OffloadKind &&
Triple.isCompatibleWith(Target.Triple) && TargetID == Target.TargetID;
}
std::string OffloadTargetInfo::str() const {
std::string NormalizedTriple;
// Unfortunately we need some special sauce for AMDHSA because all the runtime
// assumes the triple to be "amdgcn/spirv64-amd-amdhsa-" (empty environment)
// instead of "amdgcn/spirv64-amd-amdhsa-unknown". It's gonna be very tricky
// to patch different layers of runtime.
if (Triple.getOS() == Triple::OSType::AMDHSA) {
NormalizedTriple = Triple.normalize(Triple::CanonicalForm::THREE_IDENT);
NormalizedTriple.push_back('-');
} else {
NormalizedTriple = Triple.normalize(Triple::CanonicalForm::FOUR_IDENT);
}
return Twine(OffloadKind + "-" + NormalizedTriple + "-" + TargetID).str();
}
static Triple getTargetTriple(StringRef Target,
const OffloadBundlerConfig &BC) {
auto OffloadInfo = OffloadTargetInfo(Target, BC);
return Triple(OffloadInfo.getTriple());
}
static StringRef getDeviceFileExtension(StringRef Device,
StringRef BundleFileName) {
if (Device.contains("gfx"))
return ".bc";
if (Device.contains("sm_"))
return ".cubin";
return sys::path::extension(BundleFileName);
}
static std::string getDeviceLibraryFileName(StringRef BundleFileName,
StringRef Device) {
StringRef LibName = sys::path::stem(BundleFileName);
StringRef Extension = getDeviceFileExtension(Device, BundleFileName);
std::string Result;
Result += LibName;
Result += Extension;
return Result;
}
namespace {
/// Generic file handler interface.
class FileHandler {
public:
struct BundleInfo {
StringRef BundleID;
};
FileHandler() {}
virtual ~FileHandler() {}
/// Update the file handler with information from the header of the bundled
/// file.
virtual Error ReadHeader(StringRef FC) = 0;
/// Read the marker of the next bundled to be read in the file. The bundle
/// name is returned if there is one in the file, or `std::nullopt` if there
/// are no more bundles to be read.
virtual Expected<std::optional<StringRef>>
ReadBundleStart(StringRef Input) = 0;
/// Read the marker that closes the current bundle.
virtual Error ReadBundleEnd(MemoryBuffer &Input) = 0;
/// Read the current bundle and write the result into the stream \a OS.
virtual Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) = 0;
/// Write the header of the bundled file to \a OS based on the information
/// gathered from \a Inputs.
virtual Error WriteHeader(raw_ostream &OS,
ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) = 0;
/// Write the marker that initiates a bundle for the triple \a TargetTriple to
/// \a OS.
virtual Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) = 0;
/// Write the marker that closes a bundle for the triple \a TargetTriple to \a
/// OS.
virtual Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) = 0;
/// Write the bundle from \a Input into \a OS.
virtual Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) = 0;
/// Finalize output file.
virtual Error finalizeOutputFile() { return Error::success(); }
/// Sets a base name for temporary filename generation.
void SetTempFileNameBase(StringRef Base) {
TempFileNameBase = std::string(Base);
}
/// List bundle IDs in \a Input.
virtual Error listBundleIDs(MemoryBuffer &Input) {
size_t NextBundleStart = 0;
StringRef BufferString = Input.getBuffer();
while (NextBundleStart != StringRef::npos) {
// Drop the data that has already been processed/read.
BufferString = BufferString.drop_front(NextBundleStart);
// Read the header.
Error Err = ReadHeader(BufferString);
if (Err)
return Err;
Err = forEachBundle(BufferString, [&](const BundleInfo &Info) -> Error {
llvm::outs() << Info.BundleID << '\n';
Error Err = listBundleIDsCallback(Input, Info);
if (Err)
return Err;
return Error::success();
});
if (Err)
return Err;
// Find the beginning of the next Bundle, if it exists.
NextBundleStart = BufferString.find(StringRef(OFFLOAD_BUNDLER_MAGIC_STR),
sizeof(OFFLOAD_BUNDLER_MAGIC_STR));
}
return Error::success();
}
/// Get bundle IDs in \a Input in \a BundleIds.
virtual Error getBundleIDs(MemoryBuffer &Input,
std::set<StringRef> &BundleIds) {
if (Error Err = ReadHeader(Input.getBuffer()))
return Err;
return forEachBundle(Input.getBuffer(),
[&](const BundleInfo &Info) -> Error {
BundleIds.insert(Info.BundleID);
Error Err = listBundleIDsCallback(Input, Info);
if (Err)
return Err;
return Error::success();
});
}
/// For each bundle in \a Input, do \a Func.
Error forEachBundle(StringRef Input,
std::function<Error(const BundleInfo &)> Func) {
while (true) {
Expected<std::optional<StringRef>> CurTripleOrErr =
ReadBundleStart(Input);
if (!CurTripleOrErr)
return CurTripleOrErr.takeError();
// No more bundles.
if (!*CurTripleOrErr)
break;
StringRef CurTriple = **CurTripleOrErr;
assert(!CurTriple.empty());
BundleInfo Info{CurTriple};
if (Error Err = Func(Info))
return Err;
}
return Error::success();
}
protected:
/// Serves as a base name for temporary filename generation.
std::string TempFileNameBase;
virtual Error listBundleIDsCallback(MemoryBuffer &Input,
const BundleInfo &Info) {
return Error::success();
}
};
/// Handler for binary files. The bundled file will have the following format
/// (all integers are stored in little-endian format):
///
/// "OFFLOAD_BUNDLER_MAGIC_STR" (ASCII encoding of the string)
///
/// NumberOfOffloadBundles (8-byte integer)
///
/// OffsetOfBundle1 (8-byte integer)
/// SizeOfBundle1 (8-byte integer)
/// NumberOfBytesInTripleOfBundle1 (8-byte integer)
/// TripleOfBundle1 (byte length defined before)
///
/// ...
///
/// OffsetOfBundleN (8-byte integer)
/// SizeOfBundleN (8-byte integer)
/// NumberOfBytesInTripleOfBundleN (8-byte integer)
/// TripleOfBundleN (byte length defined before)
///
/// Bundle1
/// ...
/// BundleN
/// Read 8-byte integers from a buffer in little-endian format.
static uint64_t Read8byteIntegerFromBuffer(StringRef Buffer, size_t pos) {
return llvm::support::endian::read64le(Buffer.data() + pos);
}
/// Write 8-byte integers to a buffer in little-endian format.
static void Write8byteIntegerToBuffer(raw_ostream &OS, uint64_t Val) {
llvm::support::endian::write(OS, Val, llvm::endianness::little);
}
class BinaryFileHandler final : public FileHandler {
/// Information about the bundles extracted from the header.
struct BinaryBundleInfo final : public BundleInfo {
/// Size of the bundle.
uint64_t Size = 0u;
/// Offset at which the bundle starts in the bundled file.
uint64_t Offset = 0u;
BinaryBundleInfo() {}
BinaryBundleInfo(uint64_t Size, uint64_t Offset)
: Size(Size), Offset(Offset) {}
};
/// Map between a triple and the corresponding bundle information.
StringMap<BinaryBundleInfo> BundlesInfo;
/// Iterator for the bundle information that is being read.
StringMap<BinaryBundleInfo>::iterator CurBundleInfo;
StringMap<BinaryBundleInfo>::iterator NextBundleInfo;
/// Current bundle target to be written.
std::string CurWriteBundleTarget;
/// Configuration options and arrays for this bundler job
const OffloadBundlerConfig &BundlerConfig;
public:
// TODO: Add error checking from ClangOffloadBundler.cpp
BinaryFileHandler(const OffloadBundlerConfig &BC) : BundlerConfig(BC) {}
~BinaryFileHandler() final {}
Error ReadHeader(StringRef FC) final {
// Initialize the current bundle with the end of the container.
CurBundleInfo = BundlesInfo.end();
// Check if buffer is smaller than magic string.
size_t ReadChars = sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1;
if (ReadChars > FC.size())
return Error::success();
// Check if no magic was found.
if (llvm::identify_magic(FC) != llvm::file_magic::offload_bundle)
return Error::success();
// Read number of bundles.
if (ReadChars + 8 > FC.size())
return Error::success();
uint64_t NumberOfBundles = Read8byteIntegerFromBuffer(FC, ReadChars);
ReadChars += 8;
// Read bundle offsets, sizes and triples.
for (uint64_t i = 0; i < NumberOfBundles; ++i) {
// Read offset.
if (ReadChars + 8 > FC.size())
return Error::success();
uint64_t Offset = Read8byteIntegerFromBuffer(FC, ReadChars);
ReadChars += 8;
// Read size.
if (ReadChars + 8 > FC.size())
return Error::success();
uint64_t Size = Read8byteIntegerFromBuffer(FC, ReadChars);
ReadChars += 8;
// Read triple size.
if (ReadChars + 8 > FC.size())
return Error::success();
uint64_t TripleSize = Read8byteIntegerFromBuffer(FC, ReadChars);
ReadChars += 8;
// Read triple.
if (ReadChars + TripleSize > FC.size())
return Error::success();
StringRef Triple(&FC.data()[ReadChars], TripleSize);
ReadChars += TripleSize;
// Check if the offset and size make sense.
if (!Offset || Offset + Size > FC.size())
return Error::success();
BundlesInfo[Triple] = BinaryBundleInfo(Size, Offset);
}
// Set the iterator to where we will start to read.
CurBundleInfo = BundlesInfo.end();
NextBundleInfo = BundlesInfo.begin();
return Error::success();
}
Expected<std::optional<StringRef>> ReadBundleStart(StringRef Input) final {
if (NextBundleInfo == BundlesInfo.end())
return std::nullopt;
CurBundleInfo = NextBundleInfo++;
return CurBundleInfo->first();
}
Error ReadBundleEnd(MemoryBuffer &Input) final {
assert(CurBundleInfo != BundlesInfo.end() && "Invalid reader info!");
return Error::success();
}
Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
assert(CurBundleInfo != BundlesInfo.end() && "Invalid reader info!");
StringRef FC = Input.getBuffer();
OS.write(FC.data() + CurBundleInfo->second.Offset,
CurBundleInfo->second.Size);
return Error::success();
}
Error WriteHeader(raw_ostream &OS,
ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) final {
// Compute size of the header.
uint64_t HeaderSize = 0;
HeaderSize += sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1;
HeaderSize += 8; // Number of Bundles
for (auto &T : BundlerConfig.TargetNames) {
HeaderSize += 3 * 8; // Bundle offset, Size of bundle and size of triple.
HeaderSize += T.size(); // The triple.
}
// Write to the buffer the header.
OS << OFFLOAD_BUNDLER_MAGIC_STR;
Write8byteIntegerToBuffer(OS, BundlerConfig.TargetNames.size());
unsigned Idx = 0;
for (auto &T : BundlerConfig.TargetNames) {
MemoryBuffer &MB = *Inputs[Idx++];
HeaderSize = alignTo(HeaderSize, BundlerConfig.BundleAlignment);
// Bundle offset.
Write8byteIntegerToBuffer(OS, HeaderSize);
// Size of the bundle (adds to the next bundle's offset)
Write8byteIntegerToBuffer(OS, MB.getBufferSize());
BundlesInfo[T] = BinaryBundleInfo(MB.getBufferSize(), HeaderSize);
HeaderSize += MB.getBufferSize();
// Size of the triple
Write8byteIntegerToBuffer(OS, T.size());
// Triple
OS << T;
}
return Error::success();
}
Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) final {
CurWriteBundleTarget = TargetTriple.str();
return Error::success();
}
Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) final {
return Error::success();
}
Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) final {
auto BI = BundlesInfo[CurWriteBundleTarget];
// Pad with 0 to reach specified offset.
size_t CurrentPos = OS.tell();
size_t PaddingSize = BI.Offset > CurrentPos ? BI.Offset - CurrentPos : 0;
for (size_t I = 0; I < PaddingSize; ++I)
OS.write('\0');
assert(OS.tell() == BI.Offset);
OS.write(Input.getBufferStart(), Input.getBufferSize());
return Error::success();
}
};
// This class implements a list of temporary files that are removed upon
// object destruction.
class TempFileHandlerRAII {
public:
~TempFileHandlerRAII() {
for (const auto &File : Files)
sys::fs::remove(File);
}
// Creates temporary file with given contents.
Expected<StringRef> Create(std::optional<ArrayRef<char>> Contents) {
SmallString<128u> File;
if (std::error_code EC =
sys::fs::createTemporaryFile("clang-offload-bundler", "tmp", File))
return createFileError(File, EC);
Files.push_front(File);
if (Contents) {
std::error_code EC;
raw_fd_ostream OS(File, EC);
if (EC)
return createFileError(File, EC);
OS.write(Contents->data(), Contents->size());
}
return Files.front().str();
}
private:
std::forward_list<SmallString<128u>> Files;
};
/// Handler for object files. The bundles are organized by sections with a
/// designated name.
///
/// To unbundle, we just copy the contents of the designated section.
///
/// The bundler produces object file in host target native format (e.g. ELF for
/// Linux). The sections it creates are:
///
/// <OFFLOAD_BUNDLER_MAGIC_STR><target triple 1>
/// |
/// | binary data for the <target 1>'s bundle
/// |
/// ...
/// <OFFLOAD_BUNDLER_MAGIC_STR><target triple N>
/// |
/// | binary data for the <target N>'s bundle
/// |
/// ...
/// <OFFLOAD_BUNDLER_MAGIC_STR><host target>
/// | 0 (1 byte long)
/// ...
///
/// The alignment of all the added sections is set to one to avoid padding
/// between concatenated parts.
///
class ObjectFileHandler final : public FileHandler {
/// The object file we are currently dealing with.
std::unique_ptr<ObjectFile> Obj;
/// Return the input file contents.
StringRef getInputFileContents() const { return Obj->getData(); }
/// Return bundle name (<kind>-<triple>) if the provided section is an offload
/// section.
static Expected<std::optional<StringRef>>
IsOffloadSection(SectionRef CurSection) {
Expected<StringRef> NameOrErr = CurSection.getName();
if (!NameOrErr)
return NameOrErr.takeError();
// If it does not start with the reserved suffix, just skip this section.
if (llvm::identify_magic(*NameOrErr) != llvm::file_magic::offload_bundle)
return std::nullopt;
// Return the triple that is right after the reserved prefix.
return NameOrErr->substr(sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1);
}
/// Total number of inputs.
unsigned NumberOfInputs = 0;
/// Total number of processed inputs, i.e, inputs that were already
/// read from the buffers.
unsigned NumberOfProcessedInputs = 0;
/// Iterator of the current and next section.
section_iterator CurrentSection;
section_iterator NextSection;
/// Configuration options and arrays for this bundler job
const OffloadBundlerConfig &BundlerConfig;
// Return a buffer with symbol names that are defined in target objects.
// Each symbol name is prefixed by a target name <kind>-<triple> to uniquely
// identify the target it belongs to, and symbol names are separated from each
// other by '\0' characters.
Expected<SmallVector<char, 0>> makeTargetSymbolTable() {
SmallVector<char, 0> SymbolsBuf;
raw_svector_ostream SymbolsOS(SymbolsBuf);
LLVMContext Context;
for (unsigned I = 0; I < NumberOfInputs; ++I) {
if (I == BundlerConfig.HostInputIndex)
continue;
// Get the list of symbols defined in the target object. Open file and
// check if it is a symbolic file.
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
MemoryBuffer::getFileOrSTDIN(BundlerConfig.InputFileNames[I]);
if (!BufOrErr)
return createFileError(BundlerConfig.InputFileNames[I], BufOrErr.getError());
std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
// Workaround for the absence of assembly parser for spir target. If this
// input is a bitcode for spir target we need to remove module-level
// inline asm from it, if there is one, and recreate the buffer with new
// contents.
// TODO: remove this workaround once spir/spirv target gets asm parser.
if (isBitcode((const unsigned char *)Buf->getBufferStart(),
(const unsigned char *)Buf->getBufferEnd()))
if (getTargetTriple(BundlerConfig.TargetNames[I], BundlerConfig)
.isSPIROrSPIRV()) {
SMDiagnostic Err;
std::unique_ptr<Module> Mod = parseIR(*Buf, Err, Context);
if (!Mod)
return createStringError(inconvertibleErrorCode(),
Err.getMessage());
bool UpdateBuf = false;
if (!Mod->getModuleInlineAsm().empty()) {
Mod->setModuleInlineAsm("");
UpdateBuf = true;
}
for (auto I = Mod->global_begin(), E = Mod->global_end(); I != E;) {
GlobalVariable &GV = *I++;
// Do not add globals with constant address space to the tgtsym.
if (!GV.isDeclaration() && !GV.hasLocalLinkage() &&
GV.getAddressSpace() == 2) {
GV.replaceAllUsesWith(UndefValue::get(GV.getType()));
GV.dropAllReferences();
GV.eraseFromParent();
UpdateBuf = true;
}
}
if (UpdateBuf) {
SmallVector<char, 0> ModuleBuf;
raw_svector_ostream ModuleOS(ModuleBuf);
WriteBitcodeToFile(*Mod, ModuleOS);
Buf = MemoryBuffer::getMemBufferCopy(ModuleOS.str(),
Buf->getBufferIdentifier());
}
}
Expected<std::unique_ptr<Binary>> BinOrErr =
createBinary(Buf->getMemBufferRef(), &Context);
// If it is not a symbolic file just ignore it since we cannot do anything
// with it.
if (!BinOrErr) {
if (auto Err = isNotObjectErrorInvalidFileType(BinOrErr.takeError()))
return std::move(Err);
continue;
}
auto *SF = dyn_cast<SymbolicFile>(&**BinOrErr);
if (!SF)
continue;
for (BasicSymbolRef Symbol : SF->symbols()) {
Expected<uint32_t> FlagsOrErr = Symbol.getFlags();
if (!FlagsOrErr)
return FlagsOrErr.takeError();
// We are interested in externally visible and defined symbols only, so
// ignore it if this is not such a symbol.
bool Undefined = *FlagsOrErr & SymbolRef::SF_Undefined;
bool Global = *FlagsOrErr & SymbolRef::SF_Global;
if (Undefined || !Global)
continue;
// Get symbol name.
std::string Name;
raw_string_ostream NameOS(Name);
if (Error Err = Symbol.printName(NameOS))
return std::move(Err);
// If we are dealing with a bitcode file do not add special globals to
// the list of defined symbols.
if (SF->isIR() &&
(Name == "llvm.used" || Name == "llvm.compiler.used" ||
Name == "__AsanDeviceGlobalMetadata" ||
Name == "__MsanDeviceGlobalMetadata" ||
Name == "__TsanDeviceGlobalMetadata" ||
Name == "__AsanKernelMetadata" || Name == "__MsanKernelMetadata" ||
Name == "__TsanKernelMetadata"))
continue;
// Add symbol name with the target prefix to the buffer.
SymbolsOS << BundlerConfig.TargetNames[I] << "." << Name << '\0';
}
}
return SymbolsBuf;
}
public:
// TODO: Add error checking from ClangOffloadBundler.cpp
ObjectFileHandler(std::unique_ptr<ObjectFile> ObjIn,
const OffloadBundlerConfig &BC)
: Obj(std::move(ObjIn)), CurrentSection(Obj->section_begin()),
NextSection(Obj->section_begin()), BundlerConfig(BC) {}
~ObjectFileHandler() final {}
Error ReadHeader(StringRef Input) final { return Error::success(); }
Expected<std::optional<StringRef>> ReadBundleStart(StringRef Input) final {
while (NextSection != Obj->section_end()) {
CurrentSection = NextSection;
++NextSection;
// Check if the current section name starts with the reserved prefix. If
// so, return the triple.
Expected<std::optional<StringRef>> TripleOrErr =
IsOffloadSection(*CurrentSection);
if (!TripleOrErr)
return TripleOrErr.takeError();
if (*TripleOrErr)
return **TripleOrErr;
}
return std::nullopt;
}
Error ReadBundleEnd(MemoryBuffer &Input) final { return Error::success(); }
Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
Expected<StringRef> ContentOrErr = CurrentSection->getContents();
if (!ContentOrErr)
return ContentOrErr.takeError();
StringRef Content = *ContentOrErr;
// Copy fat object contents to the output when extracting host bundle.
std::string ModifiedContent;
if (Content.size() == 1u && Content.front() == 0) {
auto HostBundleOrErr = getHostBundle(
StringRef(Input.getBufferStart(), Input.getBufferSize()));
if (!HostBundleOrErr)
return HostBundleOrErr.takeError();
ModifiedContent = std::move(*HostBundleOrErr);
Content = ModifiedContent;
}
OS.write(Content.data(), Content.size());
return Error::success();
}
Error WriteHeader(raw_ostream &OS,
ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) final {
assert(BundlerConfig.HostInputIndex != ~0u &&
"Host input index not defined.");
// Record number of inputs.
NumberOfInputs = Inputs.size();
return Error::success();
}
Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) final {
++NumberOfProcessedInputs;
return Error::success();
}
Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) final {
return Error::success();
}
Error finalizeOutputFile() final {
assert(NumberOfProcessedInputs <= NumberOfInputs &&
"Processing more inputs that actually exist!");
assert(BundlerConfig.HostInputIndex != ~0u &&
"Host input index not defined.");
// If this is not the last output, we don't have to do anything.
if (NumberOfProcessedInputs != NumberOfInputs)
return Error::success();
// We will use llvm-objcopy to add target objects sections to the output
// fat object. These sections should have 'exclude' flag set which tells
// link editor to remove them from linker inputs when linking executable or
// shared library.
assert(BundlerConfig.ObjcopyPath != "" &&
"llvm-objcopy path not specified");
// Temporary files that need to be removed.
TempFileHandlerRAII TempFiles;
// Compose llvm-objcopy command line for add target objects' sections with
// appropriate flags.
BumpPtrAllocator Alloc;
StringSaver SS{Alloc};
SmallVector<StringRef, 8u> ObjcopyArgs{"llvm-objcopy"};
for (unsigned I = 0; I < NumberOfInputs; ++I) {
StringRef InputFile = BundlerConfig.InputFileNames[I];
if (I == BundlerConfig.HostInputIndex) {
// Special handling for the host bundle. We do not need to add a
// standard bundle for the host object since we are going to use fat
// object as a host object. Therefore use dummy contents (one zero byte)
// when creating section for the host bundle.
Expected<StringRef> TempFileOrErr = TempFiles.Create(ArrayRef<char>(0));
if (!TempFileOrErr)
return TempFileOrErr.takeError();
InputFile = *TempFileOrErr;
}
ObjcopyArgs.push_back(
SS.save(Twine("--add-section=") + OFFLOAD_BUNDLER_MAGIC_STR +
BundlerConfig.TargetNames[I] + "=" + InputFile));
ObjcopyArgs.push_back(
SS.save(Twine("--set-section-flags=") + OFFLOAD_BUNDLER_MAGIC_STR +
BundlerConfig.TargetNames[I] + "=readonly,exclude"));
}
if (BundlerConfig.AddTargetSymbols) {
// Add a section with symbol names that are defined in target objects to
// the output fat object.
Expected<SmallVector<char, 0>> SymbolsOrErr = makeTargetSymbolTable();
if (!SymbolsOrErr)
return SymbolsOrErr.takeError();
if (!SymbolsOrErr->empty()) {
// Add section with symbols names to fat object.
Expected<StringRef> SymbolsFileOrErr =
TempFiles.Create(ArrayRef<char>(*SymbolsOrErr));
if (!SymbolsFileOrErr)
return SymbolsFileOrErr.takeError();
ObjcopyArgs.push_back(SS.save(Twine("--add-section=") +
SYMBOLS_SECTION_NAME + "=" +
*SymbolsFileOrErr));
}
}
ObjcopyArgs.push_back("--");
ObjcopyArgs.push_back(
BundlerConfig.InputFileNames[BundlerConfig.HostInputIndex]);
ObjcopyArgs.push_back(BundlerConfig.OutputFileNames.front());
if (Error Err = executeObjcopy(BundlerConfig.ObjcopyPath, ObjcopyArgs))
return Err;
return Error::success();
}
Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) final {
return Error::success();
}
private:
Error executeObjcopy(StringRef Objcopy, ArrayRef<StringRef> Args) {
// If the user asked for the commands to be printed out, we do that
// instead of executing it.
if (BundlerConfig.PrintExternalCommands) {
errs() << "\"" << Objcopy << "\"";
for (StringRef Arg : drop_begin(Args, 1))
errs() << " \"" << Arg << "\"";
errs() << "\n";
} else {
if (sys::ExecuteAndWait(Objcopy, Args))
return createStringError(inconvertibleErrorCode(),
"'llvm-objcopy' tool failed");
}
return Error::success();
}
Expected<std::string> getHostBundle(StringRef Input) {
TempFileHandlerRAII TempFiles;
auto ModifiedObjPathOrErr = TempFiles.Create(std::nullopt);
if (!ModifiedObjPathOrErr)
return ModifiedObjPathOrErr.takeError();
StringRef ModifiedObjPath = *ModifiedObjPathOrErr;
BumpPtrAllocator Alloc;
StringSaver SS{Alloc};
SmallVector<StringRef, 16> ObjcopyArgs{"llvm-objcopy"};
ObjcopyArgs.push_back("--regex");
ObjcopyArgs.push_back("--remove-section=__CLANG_OFFLOAD_BUNDLE__.*");
ObjcopyArgs.push_back("--");
StringRef ObjcopyInputFileName;
// When unbundling an archive, the content of each object file in the
// archive is passed to this function by parameter Input, which is different
// from the content of the original input archive file, therefore it needs
// to be saved to a temporary file before passed to llvm-objcopy. Otherwise,
// Input is the same as the content of the original input file, therefore
// temporary file is not needed.
if (StringRef(BundlerConfig.FilesType).starts_with("a")) {
auto InputFileOrErr = TempFiles.Create(ArrayRef<char>(Input));
if (!InputFileOrErr)
return InputFileOrErr.takeError();
ObjcopyInputFileName = *InputFileOrErr;
} else
ObjcopyInputFileName = BundlerConfig.InputFileNames.front();
ObjcopyArgs.push_back(ObjcopyInputFileName);
ObjcopyArgs.push_back(ModifiedObjPath);
if (Error Err = executeObjcopy(BundlerConfig.ObjcopyPath, ObjcopyArgs))
return std::move(Err);
auto BufOrErr = MemoryBuffer::getFile(ModifiedObjPath);
if (!BufOrErr)
return createStringError(BufOrErr.getError(),
"Failed to read back the modified object file");
return BufOrErr->get()->getBuffer().str();
}
Expected<std::string> getHostBundle() {
TempFileHandlerRAII TempFiles;
auto ModifiedObjPathOrErr = TempFiles.Create(std::nullopt);
if (!ModifiedObjPathOrErr)
return ModifiedObjPathOrErr.takeError();