LLVM 24.0.0git
OffloadBinary.h
Go to the documentation of this file.
1//===- OffloadBinary.h - Utilities for handling offloading code -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the binary format used for bundling device metadata with
10// an associated device image. The data can then be stored inside a host object
11// file to create a fat binary and read by the linker. This is intended to be a
12// thin wrapper around the image itself. If this format becomes sufficiently
13// complex it should be moved to a standard binary format like msgpack or ELF.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_OBJECT_OFFLOADBINARY_H
18#define LLVM_OBJECT_OFFLOADBINARY_H
19
20#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/Hashing.h"
23#include "llvm/ADT/MapVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Object/Binary.h"
29#include "llvm/Support/Error.h"
31#include <memory>
32
33namespace llvm {
34
35namespace object {
36
37/// The producer of the associated offloading image.
40 OFK_FIRST = (1 << 0),
41 OFK_OpenMP = (1 << 0),
42 OFK_Cuda = (1 << 1),
43 OFK_HIP = (1 << 2),
44 OFK_SYCL = (1 << 3),
45 OFK_OpenACC = (1 << 4),
46 OFK_LAST = (1 << 5),
47};
48
49/// The type of contents the offloading image contains.
61
62/// Flags associated with the Entry.
65 // Entry doesn't contain an image. Used to keep metadata only entries.
66 OIF_Metadata = (1 << 0),
67};
68
69/// A simple binary serialization of an offloading file. We use this format to
70/// embed the offloading image into the host executable so it can be extracted
71/// and used by the linker.
72///
73/// Many of these could be stored in the same section by the time the linker
74/// sees it so we mark this information with a header. The version is used to
75/// detect ABI stability and the size is used to find other offloading entries
76/// that may exist in the same section. All offsets are given as absolute byte
77/// offsets from the beginning of the file.
78class OffloadBinary : public Binary {
79public:
82
83 /// The current version of the binary used for backwards compatibility.
84 static const uint32_t Version = 3;
85
86 /// The offloading metadata that will be serialized to a memory buffer.
94
95 struct Header {
96 uint8_t Magic[4] = {0x10, 0xFF, 0x10, 0xAD}; // 0x10FF10AD magic bytes.
97 uint32_t Version = OffloadBinary::Version; // Version identifier.
98 uint64_t Size; // Size in bytes of this entire binary.
99 uint64_t EntriesOffset; // Offset in bytes to the start of entries block.
100 uint64_t EntriesCount; // Number of metadata entries in the binary.
101 uint64_t InflatedSize; // Original size of the binary if compressed.
102 };
103
104 struct Entry {
105 ImageKind TheImageKind; // The kind of the image stored.
106 OffloadKind TheOffloadKind; // The producer of this image.
107 uint32_t Flags; // Additional flags associated with the entry.
108 uint64_t StringOffset; // Offset in bytes to the string map.
109 uint64_t NumStrings; // Number of entries in the string map.
110 uint64_t ImageOffset; // Offset in bytes of the actual binary image.
111 uint64_t ImageSize; // Size in bytes of the binary image.
112 };
113
114 struct StringEntry {
117 uint64_t ValueSize; // Size of the value in bytes.
118 };
119
124
125 /// True if \p Buf is a compressed offload package, false otherwise.
126 LLVM_ABI static bool isCompressed(MemoryBufferRef Buf);
127
128 /// Attempt to extract and validate the header from the offloading binary in
129 /// \p Buf.
132
133 /// Attempt to parse the offloading binary stored in \p Buf.
134 /// For version 1 binaries, always returns a single OffloadBinary.
135 /// For version 2+ binaries:
136 /// - If \p Index is provided, returns the OffloadBinary at that index.
137 /// - If \p Index is std::nullopt, returns all OffloadBinary entries.
138 /// \param Buf The memory buffer containing the offload binary.
139 /// \param Index Optional index to select a specific entry. If not provided,
140 /// all entries are returned (version 2+ only).
141 /// \returns An array of unique pointers to OffloadBinary objects, or an
142 /// error.
144 create(MemoryBufferRef Buf, std::optional<uint64_t> Index = std::nullopt);
145
146 /// Serialize the contents of \p OffloadingData to a binary buffer to be read
147 /// later.
149 write(ArrayRef<OffloadingImage> OffloadingData);
150
151 /// Serialize \p OffloadingData to a compressed binary with \p Compress.
153 write(ArrayRef<OffloadingImage> OffloadingData, compression::Params Compress);
154
155 static uint64_t getAlignment() { return 8; }
156
157 ImageKind getImageKind() const { return TheEntry->TheImageKind; }
158 OffloadKind getOffloadKind() const { return TheEntry->TheOffloadKind; }
159 uint32_t getVersion() const { return TheHeader->Version; }
160 uint32_t getFlags() const { return TheEntry->Flags; }
161 uint64_t getSize() const { return TheHeader->Size; }
162 uint64_t getIndex() const { return Index; }
163
164 StringRef getTriple() const { return getString("triple"); }
165 StringRef getArch() const { return getString("arch"); }
167 return StringRef(&Buffer[TheEntry->ImageOffset], TheEntry->ImageSize);
168 }
169
170 // Iterator over all the key and value pairs in the binary.
171 string_iterator_range strings() const { return StringData; }
172
173 StringRef getString(StringRef Key) const { return StringData.lookup(Key); }
174
175 static bool classof(const Binary *V) { return V->isOffloadFile(); }
176
177private:
178 OffloadBinary(std::shared_ptr<MemoryBuffer> Owned, const Header *TheHeader,
179 const Entry *TheEntry, const uint64_t Index = 0)
180 : Binary(Binary::ID_Offload, *Owned), OwnedBuffer(std::move(Owned)),
181 Buffer(OwnedBuffer->getBufferStart()), TheHeader(TheHeader),
182 TheEntry(TheEntry), Index(Index) {
183 // StringEntryV1 and StringEntry have ABI compatible Key/ValueOffset fields,
184 // but different sizes, so we need to manually calculate offset.
185 const char *StringMapBegin = &Buffer[TheEntry->StringOffset];
186 const size_t StringEntrySize =
187 TheHeader->Version == 1 ? sizeof(StringEntryV1) : sizeof(StringEntry);
188 for (uint64_t I = 0, E = TheEntry->NumStrings; I != E; ++I) {
189 const char *StringEntryPtr = StringMapBegin + I * StringEntrySize;
190 const StringEntryV1 *EntryV1 =
191 reinterpret_cast<const StringEntryV1 *>(StringEntryPtr);
192 StringRef Key = &Buffer[EntryV1->KeyOffset];
193 if (TheHeader->Version == 1) {
194 StringData[Key] = &Buffer[EntryV1->ValueOffset];
195 } else {
196 const StringEntry *Entry =
197 reinterpret_cast<const StringEntry *>(StringEntryPtr);
198 StringData[Key] =
199 StringRef(&Buffer[Entry->ValueOffset], Entry->ValueSize);
200 }
201 }
202 }
203
204 OffloadBinary(const OffloadBinary &Other) = delete;
205
206 /// Owned uncompressed binary. Shared between entries parsed from one blob.
207 std::shared_ptr<MemoryBuffer> OwnedBuffer;
208 /// Map from keys to offsets in the binary.
209 MapVector<StringRef, StringRef> StringData;
210 /// Raw pointer to the MemoryBufferRef for convenience.
211 const char *Buffer;
212 /// Location of the header within the binary.
213 const Header *TheHeader;
214 /// Location of the metadata entries within the binary.
215 const Entry *TheEntry;
216 /// Index of the entry in the list of entries serialized in the Buffer.
217 const uint64_t Index;
218};
219
220/// A handle to a single OffloadBinary.
222public:
223 struct TargetID {
225 /// The architecture, e.g. "sm_70" or "igca_30r".
227 /// The real devices to compile for ahead of time, e.g. "xe-mtl-h,xe-mtl-u".
228 /// Empty if the device image lists none.
230
231 TargetID() = default;
234
235 bool operator==(const TargetID &Other) const {
236 return Triple == Other.Triple && Arch == Other.Arch && Code == Other.Code;
237 }
238 bool operator!=(const TargetID &Other) const { return !(*this == Other); }
239 };
240
241 OffloadFile() = default;
242 OffloadFile(std::unique_ptr<OffloadBinary> Binary)
243 : Binary(std::move(Binary)) {}
244
245 OffloadBinary *getBinary() { return Binary.get(); }
246 const OffloadBinary *getBinary() const { return Binary.get(); }
247
248 /// Make a deep copy of this offloading file.
250 auto NewBinaryOrErr = OffloadBinary::create(
251 getBinary()->getMemoryBufferRef(), getBinary()->getIndex());
252 assert(NewBinaryOrErr && "Failed to parse a copy of the binary?");
253 if (!NewBinaryOrErr)
254 llvm::consumeError(NewBinaryOrErr.takeError());
255 return OffloadFile(std::move((*NewBinaryOrErr)[0]));
256 }
257
258 /// We use the target to group device images together. This conversion
259 /// function lets us use them in a hash-map.
260 operator TargetID() const {
261 return {getBinary()->getTriple(), getBinary()->getArch(),
262 getBinary()->getString("code")};
263 }
264
265private:
266 std::unique_ptr<OffloadBinary> Binary;
267};
268
269/// Extracts embedded device offloading code from a memory \p Buffer to a list
270/// of \p Binaries.
271LLVM_ABI Error extractOffloadBinaries(MemoryBufferRef Buffer,
273
274/// Convert a string \p Name to an image kind.
275LLVM_ABI ImageKind getImageKind(StringRef Name);
276
277/// Convert an image kind to its string representation.
278LLVM_ABI StringRef getImageKindName(ImageKind Name);
279
280/// Convert a string \p Name to an offload kind.
281LLVM_ABI OffloadKind getOffloadKind(StringRef Name);
282
283/// Convert an offload kind to its string representation.
284LLVM_ABI StringRef getOffloadKindName(OffloadKind Name);
285
286/// Returns true if an image built for target \p Provided can provide the device
287/// code for a request for target \p Requested. This is directional: a
288/// feature-unspecified or generic image serves a more specific request (e.g. a
289/// generic static-archive member pulled into a specific device-image group),
290/// but not vice versa. Unless \p Provided is generic, both must also have
291/// identical "code" lists. For AMDGPU a target id is a string conforming to the
292/// following BNF syntax:
293///
294/// target-id ::= '<arch> ( : <feature> ( '+' | '-' ) )*'
295///
296/// The features 'xnack' and 'sramecc' are currently supported. These can be in
297/// the state of on, off, and any when unspecified. A provided target marked as
298/// any can bind with either on or off.
299LLVM_ABI bool areTargetsCompatible(const OffloadFile::TargetID &Provided,
300 const OffloadFile::TargetID &Requested);
301
302/// Returns true if \p LHS and \p RHS denote the same logical target, i.e. the
303/// same processor and features, and identical "code" lists.
304LLVM_ABI bool areTargetsEquivalent(const OffloadFile::TargetID &LHS,
305 const OffloadFile::TargetID &RHS);
306
307} // namespace object
308
309template <> struct DenseMapInfo<object::OffloadFile::TargetID> {
311 static unsigned getHashValue(const TargetID &ID) {
312 return hash_combine(ID.Triple, ID.Arch, ID.Code);
313 }
314 static bool isEqual(const TargetID &LHS, const TargetID &RHS) {
315 return LHS == RHS;
316 }
317};
318
319} // namespace llvm
320#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This file defines DenseMapInfo traits for DenseMap.
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file defines the SmallString class.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
typename VectorType::const_iterator const_iterator
Definition MapVector.h:46
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A range adaptor for a pair of iterators.
Binary(unsigned int Type, MemoryBufferRef Source)
Definition Binary.cpp:20
A simple binary serialization of an offloading file.
static uint64_t getAlignment()
OffloadKind getOffloadKind() const
iterator_range< string_iterator > string_iterator_range
static LLVM_ABI Expected< SmallVector< std::unique_ptr< OffloadBinary > > > create(MemoryBufferRef Buf, std::optional< uint64_t > Index=std::nullopt)
Attempt to parse the offloading binary stored in Buf.
static LLVM_ABI SmallString< 0 > write(ArrayRef< OffloadingImage > OffloadingData)
Serialize the contents of OffloadingData to a binary buffer to be read later.
StringRef getString(StringRef Key) const
static LLVM_ABI bool isCompressed(MemoryBufferRef Buf)
True if Buf is a compressed offload package, false otherwise.
static LLVM_ABI Expected< const Header * > extractHeader(MemoryBufferRef Buf)
Attempt to extract and validate the header from the offloading binary in Buf.
StringRef getTriple() const
ImageKind getImageKind() const
static bool classof(const Binary *V)
string_iterator_range strings() const
static const uint32_t Version
The current version of the binary used for backwards compatibility.
MapVector< StringRef, StringRef >::const_iterator string_iterator
const OffloadBinary * getBinary() const
OffloadFile copy() const
Make a deep copy of this offloading file.
OffloadFile(std::unique_ptr< OffloadBinary > Binary)
OffloadBinary * getBinary()
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
OffloadEntryFlags
Flags associated with the Entry.
OffloadKind
The producer of the associated offloading image.
ImageKind
The type of contents the offloading image contains.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
static unsigned getHashValue(const TargetID &ID)
static bool isEqual(const TargetID &LHS, const TargetID &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
The offloading metadata that will be serialized to a memory buffer.
std::unique_ptr< MemoryBuffer > Image
MapVector< StringRef, StringRef > StringData
StringRef Code
The real devices to compile for ahead of time, e.g.
bool operator==(const TargetID &Other) const
bool operator!=(const TargetID &Other) const
StringRef Arch
The architecture, e.g. "sm_70" or "igca_30r".
TargetID(StringRef Triple, StringRef Arch, StringRef Code="")