LLVM 20.0.0git
Utility.cpp
Go to the documentation of this file.
1//===- Utility.cpp ------ Collection of generic offloading utilities ------===//
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
13#include "llvm/IR/Constants.h"
14#include "llvm/IR/GlobalValue.h"
16#include "llvm/IR/Value.h"
21
22using namespace llvm;
23using namespace llvm::offloading;
24
26 LLVMContext &C = M.getContext();
27 StructType *EntryTy =
28 StructType::getTypeByName(C, "struct.__tgt_offload_entry");
29 if (!EntryTy)
30 EntryTy = StructType::create(
31 "struct.__tgt_offload_entry", PointerType::getUnqual(C),
32 PointerType::getUnqual(C), M.getDataLayout().getIntPtrType(C),
34 return EntryTy;
35}
36
37// TODO: Rework this interface to be more generic.
38std::pair<Constant *, GlobalVariable *>
41 int32_t Flags, int32_t Data) {
42 llvm::Triple Triple(M.getTargetTriple());
43 Type *Int8PtrTy = PointerType::getUnqual(M.getContext());
44 Type *Int32Ty = Type::getInt32Ty(M.getContext());
45 Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
46
47 Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
48
49 StringRef Prefix =
50 Triple.isNVPTX() ? "$offloading$entry_name" : ".offloading.entry_name";
51
52 // Create the constant string used to look up the symbol in the device.
53 auto *Str =
54 new GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
55 GlobalValue::InternalLinkage, AddrName, Prefix);
56 Str->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
57
58 // Construct the offloading entry.
59 Constant *EntryData[] = {
62 ConstantInt::get(SizeTy, Size),
63 ConstantInt::get(Int32Ty, Flags),
64 ConstantInt::get(Int32Ty, Data),
65 };
66 Constant *EntryInitializer = ConstantStruct::get(getEntryTy(M), EntryData);
67 return {EntryInitializer, Str};
68}
69
71 uint64_t Size, int32_t Flags, int32_t Data,
73 llvm::Triple Triple(M.getTargetTriple());
74
75 auto [EntryInitializer, NameGV] =
77
78 StringRef Prefix =
79 Triple.isNVPTX() ? "$offloading$entry$" : ".offloading.entry.";
80 auto *Entry = new GlobalVariable(
81 M, getEntryTy(M),
82 /*isConstant=*/true, GlobalValue::WeakAnyLinkage, EntryInitializer,
83 Prefix + Name, nullptr, GlobalValue::NotThreadLocal,
84 M.getDataLayout().getDefaultGlobalsAddressSpace());
85
86 // The entry has to be created in the section the linker expects it to be.
88 Entry->setSection((SectionName + "$OE").str());
89 else
90 Entry->setSection(SectionName);
91 Entry->setAlignment(Align(1));
92}
93
94std::pair<GlobalVariable *, GlobalVariable *>
96 llvm::Triple Triple(M.getTargetTriple());
97
98 auto *ZeroInitilaizer =
99 ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
100 auto *EntryInit = Triple.isOSBinFormatCOFF() ? ZeroInitilaizer : nullptr;
101 auto *EntryType = ArrayType::get(getEntryTy(M), 0);
104
105 auto *EntriesB =
106 new GlobalVariable(M, EntryType, /*isConstant=*/true, Linkage, EntryInit,
107 "__start_" + SectionName);
108 EntriesB->setVisibility(GlobalValue::HiddenVisibility);
109 auto *EntriesE =
110 new GlobalVariable(M, EntryType, /*isConstant=*/true, Linkage, EntryInit,
111 "__stop_" + SectionName);
112 EntriesE->setVisibility(GlobalValue::HiddenVisibility);
113
114 if (Triple.isOSBinFormatELF()) {
115 // We assume that external begin/end symbols that we have created above will
116 // be defined by the linker. This is done whenever a section name with a
117 // valid C-identifier is present. We define a dummy variable here to force
118 // the linker to always provide these symbols.
119 auto *DummyEntry = new GlobalVariable(
120 M, ZeroInitilaizer->getType(), true, GlobalVariable::InternalLinkage,
121 ZeroInitilaizer, "__dummy." + SectionName);
122 DummyEntry->setSection(SectionName);
123 appendToCompilerUsed(M, DummyEntry);
124 } else {
125 // The COFF linker will merge sections containing a '$' together into a
126 // single section. The order of entries in this section will be sorted
127 // alphabetically by the characters following the '$' in the name. Set the
128 // sections here to ensure that the beginning and end symbols are sorted.
129 EntriesB->setSection((SectionName + "$OA").str());
130 EntriesE->setSection((SectionName + "$OZ").str());
131 }
132
133 return std::make_pair(EntriesB, EntriesE);
134}
135
137 uint32_t ImageFlags,
138 StringRef EnvTargetID) {
139 using namespace llvm::ELF;
140 StringRef EnvArch = EnvTargetID.split(":").first;
141
142 // Trivial check if the base processors match.
143 if (EnvArch != ImageArch)
144 return false;
145
146 // Check if the image is requesting xnack on or off.
147 switch (ImageFlags & EF_AMDGPU_FEATURE_XNACK_V4) {
148 case EF_AMDGPU_FEATURE_XNACK_OFF_V4:
149 // The image is 'xnack-' so the environment must be 'xnack-'.
150 if (!EnvTargetID.contains("xnack-"))
151 return false;
152 break;
153 case EF_AMDGPU_FEATURE_XNACK_ON_V4:
154 // The image is 'xnack+' so the environment must be 'xnack+'.
155 if (!EnvTargetID.contains("xnack+"))
156 return false;
157 break;
158 case EF_AMDGPU_FEATURE_XNACK_UNSUPPORTED_V4:
159 case EF_AMDGPU_FEATURE_XNACK_ANY_V4:
160 default:
161 break;
162 }
163
164 // Check if the image is requesting sramecc on or off.
165 switch (ImageFlags & EF_AMDGPU_FEATURE_SRAMECC_V4) {
166 case EF_AMDGPU_FEATURE_SRAMECC_OFF_V4:
167 // The image is 'sramecc-' so the environment must be 'sramecc-'.
168 if (!EnvTargetID.contains("sramecc-"))
169 return false;
170 break;
171 case EF_AMDGPU_FEATURE_SRAMECC_ON_V4:
172 // The image is 'sramecc+' so the environment must be 'sramecc+'.
173 if (!EnvTargetID.contains("sramecc+"))
174 return false;
175 break;
176 case EF_AMDGPU_FEATURE_SRAMECC_UNSUPPORTED_V4:
177 case EF_AMDGPU_FEATURE_SRAMECC_ANY_V4:
178 break;
179 }
180
181 return true;
182}
183
184namespace {
185/// Reads the AMDGPU specific per-kernel-metadata from an image.
186class KernelInfoReader {
187public:
189 : KernelInfoMap(KIM) {}
190
191 /// Process ELF note to read AMDGPU metadata from respective information
192 /// fields.
193 Error processNote(const llvm::object::ELF64LE::Note &Note, size_t Align) {
194 if (Note.getName() != "AMDGPU")
195 return Error::success(); // We are not interested in other things
196
197 assert(Note.getType() == ELF::NT_AMDGPU_METADATA &&
198 "Parse AMDGPU MetaData");
199 auto Desc = Note.getDesc(Align);
200 StringRef MsgPackString =
201 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
202 msgpack::Document MsgPackDoc;
203 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
204 return Error::success();
205
207 if (!Verifier.verify(MsgPackDoc.getRoot()))
208 return Error::success();
209
210 auto RootMap = MsgPackDoc.getRoot().getMap(true);
211
212 if (auto Err = iterateAMDKernels(RootMap))
213 return Err;
214
215 return Error::success();
216 }
217
218private:
219 /// Extracts the relevant information via simple string look-up in the msgpack
220 /// document elements.
221 Error
222 extractKernelData(msgpack::MapDocNode::MapTy::value_type V,
223 std::string &KernelName,
225 if (!V.first.isString())
226 return Error::success();
227
228 const auto IsKey = [](const msgpack::DocNode &DK, StringRef SK) {
229 return DK.getString() == SK;
230 };
231
232 const auto GetSequenceOfThreeInts = [](msgpack::DocNode &DN,
233 uint32_t *Vals) {
234 assert(DN.isArray() && "MsgPack DocNode is an array node");
235 auto DNA = DN.getArray();
236 assert(DNA.size() == 3 && "ArrayNode has at most three elements");
237
238 int I = 0;
239 for (auto DNABegin = DNA.begin(), DNAEnd = DNA.end(); DNABegin != DNAEnd;
240 ++DNABegin) {
241 Vals[I++] = DNABegin->getUInt();
242 }
243 };
244
245 if (IsKey(V.first, ".name")) {
246 KernelName = V.second.toString();
247 } else if (IsKey(V.first, ".sgpr_count")) {
248 KernelData.SGPRCount = V.second.getUInt();
249 } else if (IsKey(V.first, ".sgpr_spill_count")) {
250 KernelData.SGPRSpillCount = V.second.getUInt();
251 } else if (IsKey(V.first, ".vgpr_count")) {
252 KernelData.VGPRCount = V.second.getUInt();
253 } else if (IsKey(V.first, ".vgpr_spill_count")) {
254 KernelData.VGPRSpillCount = V.second.getUInt();
255 } else if (IsKey(V.first, ".agpr_count")) {
256 KernelData.AGPRCount = V.second.getUInt();
257 } else if (IsKey(V.first, ".private_segment_fixed_size")) {
258 KernelData.PrivateSegmentSize = V.second.getUInt();
259 } else if (IsKey(V.first, ".group_segment_fixed_size")) {
260 KernelData.GroupSegmentList = V.second.getUInt();
261 } else if (IsKey(V.first, ".reqd_workgroup_size")) {
262 GetSequenceOfThreeInts(V.second, KernelData.RequestedWorkgroupSize);
263 } else if (IsKey(V.first, ".workgroup_size_hint")) {
264 GetSequenceOfThreeInts(V.second, KernelData.WorkgroupSizeHint);
265 } else if (IsKey(V.first, ".wavefront_size")) {
266 KernelData.WavefrontSize = V.second.getUInt();
267 } else if (IsKey(V.first, ".max_flat_workgroup_size")) {
268 KernelData.MaxFlatWorkgroupSize = V.second.getUInt();
269 }
270
271 return Error::success();
272 }
273
274 /// Get the "amdhsa.kernels" element from the msgpack Document
276 auto Res = MDN.find("amdhsa.kernels");
277 if (Res == MDN.end())
279 "Could not find amdhsa.kernels key");
280
281 auto Pair = *Res;
282 assert(Pair.second.isArray() &&
283 "AMDGPU kernel entries are arrays of entries");
284
285 return Pair.second.getArray();
286 }
287
288 /// Iterate all entries for one "amdhsa.kernels" entry. Each entry is a
289 /// MapDocNode that either maps a string to a single value (most of them) or
290 /// to another array of things. Currently, we only handle the case that maps
291 /// to scalar value.
292 Error generateKernelInfo(msgpack::ArrayDocNode::ArrayTy::iterator It) {
294 std::string KernelName;
295 auto Entry = (*It).getMap();
296 for (auto MI = Entry.begin(), E = Entry.end(); MI != E; ++MI)
297 if (auto Err = extractKernelData(*MI, KernelName, KernelData))
298 return Err;
299
300 KernelInfoMap.insert({KernelName, KernelData});
301 return Error::success();
302 }
303
304 /// Go over the list of AMD kernels in the "amdhsa.kernels" entry
305 Error iterateAMDKernels(msgpack::MapDocNode &MDN) {
306 auto KernelsOrErr = getAMDKernelsArray(MDN);
307 if (auto Err = KernelsOrErr.takeError())
308 return Err;
309
310 auto KernelsArr = *KernelsOrErr;
311 for (auto It = KernelsArr.begin(), E = KernelsArr.end(); It != E; ++It) {
312 if (!It->isMap())
313 continue; // we expect <key,value> pairs
314
315 // Obtain the value for the different entries. Each array entry is a
316 // MapDocNode
317 if (auto Err = generateKernelInfo(It))
318 return Err;
319 }
320 return Error::success();
321 }
322
323 // Kernel names are the keys
325};
326} // namespace
327
329 MemoryBufferRef MemBuffer,
331 uint16_t &ELFABIVersion) {
332 Error Err = Error::success(); // Used later as out-parameter
333
334 auto ELFOrError = object::ELF64LEFile::create(MemBuffer.getBuffer());
335 if (auto Err = ELFOrError.takeError())
336 return Err;
337
338 const object::ELF64LEFile ELFObj = ELFOrError.get();
340 if (!Sections)
341 return Sections.takeError();
342 KernelInfoReader Reader(KernelInfoMap);
343
344 // Read the code object version from ELF image header
345 auto Header = ELFObj.getHeader();
346 ELFABIVersion = (uint8_t)(Header.e_ident[ELF::EI_ABIVERSION]);
347 for (const auto &S : *Sections) {
348 if (S.sh_type != ELF::SHT_NOTE)
349 continue;
350
351 for (const auto N : ELFObj.notes(S, Err)) {
352 if (Err)
353 return Err;
354 // Fills the KernelInfoTabel entries in the reader
355 if ((Err = Reader.processNote(N, S.sh_addralign)))
356 return Err;
357 }
358 }
359 return Error::success();
360}
This is a verifier for AMDGPU HSA metadata, which can verify both well-typed metadata and untyped met...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
uint64_t Addr
std::string Name
uint64_t Size
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares a class that exposes a simple in-memory representation of a document of MsgPack ob...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
verify safepoint Safepoint IR Verifier
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1650
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2950
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2242
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1357
This is an important base class in LLVM.
Definition: Constant.h:42
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
StringRef getBuffer() const
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:685
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:409
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition: Type.cpp:620
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:501
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:724
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
Definition: Triple.h:840
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:719
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt32Ty(LLVMContext &C)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
A node in a MsgPack Document.
MapDocNode & getMap(bool Convert=false)
Get a MapDocNode for a map node.
ArrayDocNode & getArray(bool Convert=false)
Get an ArrayDocNode for an array node.
StringRef getString() const
Simple in-memory representation of a document of msgpack objects with ability to find and create arra...
DocNode & getRoot()
Get ref to the document's root element.
bool readFromBlob(StringRef Blob, bool Multi, function_ref< int(DocNode *DestNode, DocNode SrcNode, DocNode MapKey)> Merger=[](DocNode *DestNode, DocNode SrcNode, DocNode MapKey) { return -1;})
Read a document from a binary msgpack blob, merging into anything already in the Document.
A DocNode that is a map.
MapTy::iterator find(DocNode Key)
const Elf_Ehdr & getHeader() const
Definition: ELF.h:278
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:887
iterator_range< Elf_Note_Iterator > notes(const Elf_Phdr &Phdr, Error &Err) const
Get an iterator range over notes of a program header.
Definition: ELF.h:461
Expected< Elf_Shdr_Range > sections() const
Definition: ELF.h:924
@ Entry
Definition: COFF.h:826
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Definition: ELF.h:28
@ SHT_NOTE
Definition: ELF.h:1095
@ EI_ABIVERSION
Definition: ELF.h:57
@ NT_AMDGPU_METADATA
Definition: ELF.h:1910
Error getAMDGPUMetaDataFromImage(MemoryBufferRef MemBuffer, StringMap< AMDGPUKernelMetaData > &KernelInfoMap, uint16_t &ELFABIVersion)
Reads AMDGPU specific metadata from the ELF file and propagates the KernelInfoMap.
Definition: Utility.cpp:328
bool isImageCompatibleWithEnv(StringRef ImageArch, uint32_t ImageFlags, StringRef EnvTargetID)
Check if an image is compatible with current system's environment.
Definition: Utility.cpp:136
std::pair< Constant *, GlobalVariable * > getOffloadingEntryInitializer(Module &M, Constant *Addr, StringRef Name, uint64_t Size, int32_t Flags, int32_t Data)
Create a constant struct initializer used to register this global at runtime.
Definition: Utility.cpp:39
StructType * getEntryTy(Module &M)
Returns the type of the offloading entry we use to store kernels and globals that will be registered ...
Definition: Utility.cpp:25
void emitOffloadingEntry(Module &M, Constant *Addr, StringRef Name, uint64_t Size, int32_t Flags, int32_t Data, StringRef SectionName)
Create an offloading section struct used to register this global at runtime.
Definition: Utility.cpp:70
std::pair< GlobalVariable *, GlobalVariable * > getOffloadEntryArray(Module &M, StringRef SectionName)
Creates a pair of globals used to iterate the array of offloading entries by accessing the section va...
Definition: Utility.cpp:95
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Description of the encoding of one expression Op.
Struct for holding metadata related to AMDGPU kernels, for more information about the metadata and it...
Definition: Utility.h:98
uint32_t SGPRSpillCount
Number of stores from a scalar register to a register allocator created spill location.
Definition: Utility.h:113
uint32_t SGPRCount
Number of scalar registers required by a wavefront.
Definition: Utility.h:108
uint32_t VGPRSpillCount
Number of stores from a vector register to a register allocator created spill location.
Definition: Utility.h:116
uint32_t VGPRCount
Number of vector registers required by each work-item.
Definition: Utility.h:110
uint32_t PrivateSegmentSize
The amount of fixed private address space memory required for a work-item in bytes.
Definition: Utility.h:106
uint32_t GroupSegmentList
The amount of group segment memory required by a work-group in bytes.
Definition: Utility.h:103
uint32_t MaxFlatWorkgroupSize
Maximum flat work-group size supported by the kernel in work-items.
Definition: Utility.h:127
uint32_t WorkgroupSizeHint[3]
Corresponds to the OpenCL work_group_size_hint attribute.
Definition: Utility.h:123
uint32_t AGPRCount
Number of accumulator registers required by each work-item.
Definition: Utility.h:118
uint32_t RequestedWorkgroupSize[3]
Corresponds to the OpenCL reqd_work_group_size attribute.
Definition: Utility.h:120