LLVM 19.0.0git
OffloadWrapper.cpp
Go to the documentation of this file.
1//===- OffloadWrapper.cpp ---------------------------------------*- C++ -*-===//
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
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/IR/Constants.h"
15#include "llvm/IR/IRBuilder.h"
16#include "llvm/IR/LLVMContext.h"
17#include "llvm/IR/Module.h"
19#include "llvm/Support/Error.h"
22
23using namespace llvm;
24using namespace llvm::offloading;
25
26namespace {
27/// Magic number that begins the section containing the CUDA fatbinary.
28constexpr unsigned CudaFatMagic = 0x466243b1;
29constexpr unsigned HIPFatMagic = 0x48495046;
30
32 return M.getDataLayout().getIntPtrType(M.getContext());
33}
34
35// struct __tgt_device_image {
36// void *ImageStart;
37// void *ImageEnd;
38// __tgt_offload_entry *EntriesBegin;
39// __tgt_offload_entry *EntriesEnd;
40// };
41StructType *getDeviceImageTy(Module &M) {
42 LLVMContext &C = M.getContext();
43 StructType *ImageTy = StructType::getTypeByName(C, "__tgt_device_image");
44 if (!ImageTy)
45 ImageTy =
46 StructType::create("__tgt_device_image", PointerType::getUnqual(C),
47 PointerType::getUnqual(C), PointerType::getUnqual(C),
48 PointerType::getUnqual(C));
49 return ImageTy;
50}
51
52PointerType *getDeviceImagePtrTy(Module &M) {
53 return PointerType::getUnqual(getDeviceImageTy(M));
54}
55
56// struct __tgt_bin_desc {
57// int32_t NumDeviceImages;
58// __tgt_device_image *DeviceImages;
59// __tgt_offload_entry *HostEntriesBegin;
60// __tgt_offload_entry *HostEntriesEnd;
61// };
62StructType *getBinDescTy(Module &M) {
63 LLVMContext &C = M.getContext();
64 StructType *DescTy = StructType::getTypeByName(C, "__tgt_bin_desc");
65 if (!DescTy)
66 DescTy = StructType::create(
67 "__tgt_bin_desc", Type::getInt32Ty(C), getDeviceImagePtrTy(M),
68 PointerType::getUnqual(C), PointerType::getUnqual(C));
69 return DescTy;
70}
71
72PointerType *getBinDescPtrTy(Module &M) {
73 return PointerType::getUnqual(getBinDescTy(M));
74}
75
76/// Creates binary descriptor for the given device images. Binary descriptor
77/// is an object that is passed to the offloading runtime at program startup
78/// and it describes all device images available in the executable or shared
79/// library. It is defined as follows
80///
81/// __attribute__((visibility("hidden")))
82/// extern __tgt_offload_entry *__start_omp_offloading_entries;
83/// __attribute__((visibility("hidden")))
84/// extern __tgt_offload_entry *__stop_omp_offloading_entries;
85///
86/// static const char Image0[] = { <Bufs.front() contents> };
87/// ...
88/// static const char ImageN[] = { <Bufs.back() contents> };
89///
90/// static const __tgt_device_image Images[] = {
91/// {
92/// Image0, /*ImageStart*/
93/// Image0 + sizeof(Image0), /*ImageEnd*/
94/// __start_omp_offloading_entries, /*EntriesBegin*/
95/// __stop_omp_offloading_entries /*EntriesEnd*/
96/// },
97/// ...
98/// {
99/// ImageN, /*ImageStart*/
100/// ImageN + sizeof(ImageN), /*ImageEnd*/
101/// __start_omp_offloading_entries, /*EntriesBegin*/
102/// __stop_omp_offloading_entries /*EntriesEnd*/
103/// }
104/// };
105///
106/// static const __tgt_bin_desc BinDesc = {
107/// sizeof(Images) / sizeof(Images[0]), /*NumDeviceImages*/
108/// Images, /*DeviceImages*/
109/// __start_omp_offloading_entries, /*HostEntriesBegin*/
110/// __stop_omp_offloading_entries /*HostEntriesEnd*/
111/// };
112///
113/// Global variable that represents BinDesc is returned.
114GlobalVariable *createBinDesc(Module &M, ArrayRef<ArrayRef<char>> Bufs,
115 EntryArrayTy EntryArray, StringRef Suffix,
116 bool Relocatable) {
117 LLVMContext &C = M.getContext();
118 auto [EntriesB, EntriesE] = EntryArray;
119
120 auto *Zero = ConstantInt::get(getSizeTTy(M), 0u);
121 Constant *ZeroZero[] = {Zero, Zero};
122
123 // Create initializer for the images array.
124 SmallVector<Constant *, 4u> ImagesInits;
125 ImagesInits.reserve(Bufs.size());
126 for (ArrayRef<char> Buf : Bufs) {
127 // We embed the full offloading entry so the binary utilities can parse it.
128 auto *Data = ConstantDataArray::get(C, Buf);
129 auto *Image = new GlobalVariable(M, Data->getType(), /*isConstant=*/true,
130 GlobalVariable::InternalLinkage, Data,
131 ".omp_offloading.device_image" + Suffix);
132 Image->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
133 Image->setSection(Relocatable ? ".llvm.offloading.relocatable"
134 : ".llvm.offloading");
136
137 StringRef Binary(Buf.data(), Buf.size());
139 "Invalid binary format");
140
141 // The device image struct contains the pointer to the beginning and end of
142 // the image stored inside of the offload binary. There should only be one
143 // of these for each buffer so we parse it out manually.
144 const auto *Header =
145 reinterpret_cast<const object::OffloadBinary::Header *>(
146 Binary.bytes_begin());
147 const auto *Entry = reinterpret_cast<const object::OffloadBinary::Entry *>(
148 Binary.bytes_begin() + Header->EntryOffset);
149
150 auto *Begin = ConstantInt::get(getSizeTTy(M), Entry->ImageOffset);
151 auto *Size =
152 ConstantInt::get(getSizeTTy(M), Entry->ImageOffset + Entry->ImageSize);
153 Constant *ZeroBegin[] = {Zero, Begin};
154 Constant *ZeroSize[] = {Zero, Size};
155
156 auto *ImageB =
157 ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroBegin);
158 auto *ImageE =
159 ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroSize);
160
161 ImagesInits.push_back(ConstantStruct::get(getDeviceImageTy(M), ImageB,
162 ImageE, EntriesB, EntriesE));
163 }
164
165 // Then create images array.
166 auto *ImagesData = ConstantArray::get(
167 ArrayType::get(getDeviceImageTy(M), ImagesInits.size()), ImagesInits);
168
169 auto *Images =
170 new GlobalVariable(M, ImagesData->getType(), /*isConstant*/ true,
172 ".omp_offloading.device_images" + Suffix);
173 Images->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
174
175 auto *ImagesB =
176 ConstantExpr::getGetElementPtr(Images->getValueType(), Images, ZeroZero);
177
178 // And finally create the binary descriptor object.
179 auto *DescInit = ConstantStruct::get(
180 getBinDescTy(M),
181 ConstantInt::get(Type::getInt32Ty(C), ImagesInits.size()), ImagesB,
182 EntriesB, EntriesE);
183
184 return new GlobalVariable(M, DescInit->getType(), /*isConstant*/ true,
186 ".omp_offloading.descriptor" + Suffix);
187}
188
189Function *createUnregisterFunction(Module &M, GlobalVariable *BinDesc,
190 StringRef Suffix) {
191 LLVMContext &C = M.getContext();
192 auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
193 auto *Func =
195 ".omp_offloading.descriptor_unreg" + Suffix, &M);
196 Func->setSection(".text.startup");
197
198 // Get __tgt_unregister_lib function declaration.
199 auto *UnRegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),
200 /*isVarArg*/ false);
201 FunctionCallee UnRegFuncC =
202 M.getOrInsertFunction("__tgt_unregister_lib", UnRegFuncTy);
203
204 // Construct function body
205 IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
206 Builder.CreateCall(UnRegFuncC, BinDesc);
207 Builder.CreateRetVoid();
208
209 return Func;
210}
211
212void createRegisterFunction(Module &M, GlobalVariable *BinDesc,
213 StringRef Suffix) {
214 LLVMContext &C = M.getContext();
215 auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
217 ".omp_offloading.descriptor_reg" + Suffix, &M);
218 Func->setSection(".text.startup");
219
220 // Get __tgt_register_lib function declaration.
221 auto *RegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),
222 /*isVarArg*/ false);
223 FunctionCallee RegFuncC =
224 M.getOrInsertFunction("__tgt_register_lib", RegFuncTy);
225
226 auto *AtExitTy = FunctionType::get(
227 Type::getInt32Ty(C), PointerType::getUnqual(C), /*isVarArg=*/false);
228 FunctionCallee AtExit = M.getOrInsertFunction("atexit", AtExitTy);
229
230 Function *UnregFunc = createUnregisterFunction(M, BinDesc, Suffix);
231
232 // Construct function body
233 IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
234
235 // Register the destructors with 'atexit'. This is expected by the CUDA
236 // runtime and ensures that we clean up before dynamic objects are destroyed.
237 // This needs to be done before the runtime is called and registers its own.
238 Builder.CreateCall(AtExit, UnregFunc);
239
240 Builder.CreateCall(RegFuncC, BinDesc);
241 Builder.CreateRetVoid();
242
243 // Add this function to constructors.
244 appendToGlobalCtors(M, Func, /*Priority=*/101);
245}
246
247// struct fatbin_wrapper {
248// int32_t magic;
249// int32_t version;
250// void *image;
251// void *reserved;
252//};
253StructType *getFatbinWrapperTy(Module &M) {
254 LLVMContext &C = M.getContext();
255 StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
256 if (!FatbinTy)
257 FatbinTy = StructType::create(
258 "fatbin_wrapper", Type::getInt32Ty(C), Type::getInt32Ty(C),
259 PointerType::getUnqual(C), PointerType::getUnqual(C));
260 return FatbinTy;
261}
262
263/// Embed the image \p Image into the module \p M so it can be found by the
264/// runtime.
265GlobalVariable *createFatbinDesc(Module &M, ArrayRef<char> Image, bool IsHIP,
266 StringRef Suffix) {
267 LLVMContext &C = M.getContext();
268 llvm::Type *Int8PtrTy = PointerType::getUnqual(C);
269 llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
270
271 // Create the global string containing the fatbinary.
272 StringRef FatbinConstantSection =
273 IsHIP ? ".hip_fatbin"
274 : (Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin");
275 auto *Data = ConstantDataArray::get(C, Image);
276 auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
277 GlobalVariable::InternalLinkage, Data,
278 ".fatbin_image" + Suffix);
279 Fatbin->setSection(FatbinConstantSection);
280
281 // Create the fatbinary wrapper
282 StringRef FatbinWrapperSection = IsHIP ? ".hipFatBinSegment"
283 : Triple.isMacOSX() ? "__NV_CUDA,__fatbin"
284 : ".nvFatBinSegment";
285 Constant *FatbinWrapper[] = {
286 ConstantInt::get(Type::getInt32Ty(C), IsHIP ? HIPFatMagic : CudaFatMagic),
287 ConstantInt::get(Type::getInt32Ty(C), 1),
289 ConstantPointerNull::get(PointerType::getUnqual(C))};
290
291 Constant *FatbinInitializer =
292 ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
293
294 auto *FatbinDesc =
295 new GlobalVariable(M, getFatbinWrapperTy(M),
296 /*isConstant*/ true, GlobalValue::InternalLinkage,
297 FatbinInitializer, ".fatbin_wrapper" + Suffix);
298 FatbinDesc->setSection(FatbinWrapperSection);
299 FatbinDesc->setAlignment(Align(8));
300
301 return FatbinDesc;
302}
303
304/// Create the register globals function. We will iterate all of the offloading
305/// entries stored at the begin / end symbols and register them according to
306/// their type. This creates the following function in IR:
307///
308/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
309/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
310///
311/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
312/// void *, void *, void *, void *, int *);
313/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
314/// int64_t, int32_t, int32_t);
315///
316/// void __cudaRegisterTest(void **fatbinHandle) {
317/// for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
318/// entry != &__stop_cuda_offloading_entries; ++entry) {
319/// if (!entry->size)
320/// __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
321/// entry->name, -1, 0, 0, 0, 0, 0);
322/// else
323/// __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,
324/// 0, entry->size, 0, 0);
325/// }
326/// }
327Function *createRegisterGlobalsFunction(Module &M, bool IsHIP,
328 EntryArrayTy EntryArray,
329 StringRef Suffix,
330 bool EmitSurfacesAndTextures) {
331 LLVMContext &C = M.getContext();
332 auto [EntriesB, EntriesE] = EntryArray;
333
334 // Get the __cudaRegisterFunction function declaration.
335 PointerType *Int8PtrTy = PointerType::get(C, 0);
336 PointerType *Int8PtrPtrTy = PointerType::get(C, 0);
337 PointerType *Int32PtrTy = PointerType::get(C, 0);
338 auto *RegFuncTy = FunctionType::get(
340 {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
341 Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32PtrTy},
342 /*isVarArg*/ false);
343 FunctionCallee RegFunc = M.getOrInsertFunction(
344 IsHIP ? "__hipRegisterFunction" : "__cudaRegisterFunction", RegFuncTy);
345
346 // Get the __cudaRegisterVar function declaration.
347 auto *RegVarTy = FunctionType::get(
349 {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
351 /*isVarArg*/ false);
352 FunctionCallee RegVar = M.getOrInsertFunction(
353 IsHIP ? "__hipRegisterVar" : "__cudaRegisterVar", RegVarTy);
354
355 // Get the __cudaRegisterSurface function declaration.
356 FunctionType *RegSurfaceTy =
357 FunctionType::get(Type::getVoidTy(C),
358 {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy,
360 /*isVarArg=*/false);
361 FunctionCallee RegSurface = M.getOrInsertFunction(
362 IsHIP ? "__hipRegisterSurface" : "__cudaRegisterSurface", RegSurfaceTy);
363
364 // Get the __cudaRegisterTexture function declaration.
365 FunctionType *RegTextureTy = FunctionType::get(
367 {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
369 /*isVarArg=*/false);
370 FunctionCallee RegTexture = M.getOrInsertFunction(
371 IsHIP ? "__hipRegisterTexture" : "__cudaRegisterTexture", RegTextureTy);
372
373 auto *RegGlobalsTy = FunctionType::get(Type::getVoidTy(C), Int8PtrPtrTy,
374 /*isVarArg*/ false);
375 auto *RegGlobalsFn =
377 IsHIP ? ".hip.globals_reg" : ".cuda.globals_reg", &M);
378 RegGlobalsFn->setSection(".text.startup");
379
380 // Create the loop to register all the entries.
381 IRBuilder<> Builder(BasicBlock::Create(C, "entry", RegGlobalsFn));
382 auto *EntryBB = BasicBlock::Create(C, "while.entry", RegGlobalsFn);
383 auto *IfThenBB = BasicBlock::Create(C, "if.then", RegGlobalsFn);
384 auto *IfElseBB = BasicBlock::Create(C, "if.else", RegGlobalsFn);
385 auto *SwGlobalBB = BasicBlock::Create(C, "sw.global", RegGlobalsFn);
386 auto *SwManagedBB = BasicBlock::Create(C, "sw.managed", RegGlobalsFn);
387 auto *SwSurfaceBB = BasicBlock::Create(C, "sw.surface", RegGlobalsFn);
388 auto *SwTextureBB = BasicBlock::Create(C, "sw.texture", RegGlobalsFn);
389 auto *IfEndBB = BasicBlock::Create(C, "if.end", RegGlobalsFn);
390 auto *ExitBB = BasicBlock::Create(C, "while.end", RegGlobalsFn);
391
392 auto *EntryCmp = Builder.CreateICmpNE(EntriesB, EntriesE);
393 Builder.CreateCondBr(EntryCmp, EntryBB, ExitBB);
394 Builder.SetInsertPoint(EntryBB);
395 auto *Entry = Builder.CreatePHI(PointerType::getUnqual(C), 2, "entry");
396 auto *AddrPtr =
397 Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
398 {ConstantInt::get(getSizeTTy(M), 0),
399 ConstantInt::get(Type::getInt32Ty(C), 0)});
400 auto *Addr = Builder.CreateLoad(Int8PtrTy, AddrPtr, "addr");
401 auto *NamePtr =
402 Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
403 {ConstantInt::get(getSizeTTy(M), 0),
404 ConstantInt::get(Type::getInt32Ty(C), 1)});
405 auto *Name = Builder.CreateLoad(Int8PtrTy, NamePtr, "name");
406 auto *SizePtr =
407 Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
408 {ConstantInt::get(getSizeTTy(M), 0),
409 ConstantInt::get(Type::getInt32Ty(C), 2)});
410 auto *Size = Builder.CreateLoad(getSizeTTy(M), SizePtr, "size");
411 auto *FlagsPtr =
412 Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
413 {ConstantInt::get(getSizeTTy(M), 0),
414 ConstantInt::get(Type::getInt32Ty(C), 3)});
415 auto *Flags = Builder.CreateLoad(Type::getInt32Ty(C), FlagsPtr, "flags");
416 auto *DataPtr =
417 Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
418 {ConstantInt::get(getSizeTTy(M), 0),
419 ConstantInt::get(Type::getInt32Ty(C), 4)});
420 auto *Data = Builder.CreateLoad(Type::getInt32Ty(C), DataPtr, "textype");
421 auto *Kind = Builder.CreateAnd(
422 Flags, ConstantInt::get(Type::getInt32Ty(C), 0x7), "type");
423
424 // Extract the flags stored in the bit-field and convert them to C booleans.
425 auto *ExternBit = Builder.CreateAnd(
426 Flags, ConstantInt::get(Type::getInt32Ty(C),
428 auto *Extern = Builder.CreateLShr(
429 ExternBit, ConstantInt::get(Type::getInt32Ty(C), 3), "extern");
430 auto *ConstantBit = Builder.CreateAnd(
431 Flags, ConstantInt::get(Type::getInt32Ty(C),
433 auto *Const = Builder.CreateLShr(
434 ConstantBit, ConstantInt::get(Type::getInt32Ty(C), 4), "constant");
435 auto *NormalizedBit = Builder.CreateAnd(
436 Flags, ConstantInt::get(Type::getInt32Ty(C),
438 auto *Normalized = Builder.CreateLShr(
439 NormalizedBit, ConstantInt::get(Type::getInt32Ty(C), 5), "normalized");
440 auto *FnCond =
441 Builder.CreateICmpEQ(Size, ConstantInt::getNullValue(getSizeTTy(M)));
442 Builder.CreateCondBr(FnCond, IfThenBB, IfElseBB);
443
444 // Create kernel registration code.
445 Builder.SetInsertPoint(IfThenBB);
446 Builder.CreateCall(RegFunc, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
447 ConstantInt::get(Type::getInt32Ty(C), -1),
448 ConstantPointerNull::get(Int8PtrTy),
449 ConstantPointerNull::get(Int8PtrTy),
450 ConstantPointerNull::get(Int8PtrTy),
451 ConstantPointerNull::get(Int8PtrTy),
452 ConstantPointerNull::get(Int32PtrTy)});
453 Builder.CreateBr(IfEndBB);
454 Builder.SetInsertPoint(IfElseBB);
455
456 auto *Switch = Builder.CreateSwitch(Kind, IfEndBB);
457 // Create global variable registration code.
458 Builder.SetInsertPoint(SwGlobalBB);
459 Builder.CreateCall(RegVar,
460 {RegGlobalsFn->arg_begin(), Addr, Name, Name, Extern, Size,
461 Const, ConstantInt::get(Type::getInt32Ty(C), 0)});
462 Builder.CreateBr(IfEndBB);
463 Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalEntry),
464 SwGlobalBB);
465
466 // Create managed variable registration code.
467 Builder.SetInsertPoint(SwManagedBB);
468 Builder.CreateBr(IfEndBB);
469 Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalManagedEntry),
470 SwManagedBB);
471 // Create surface variable registration code.
472 Builder.SetInsertPoint(SwSurfaceBB);
473 if (EmitSurfacesAndTextures)
474 Builder.CreateCall(RegSurface, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
475 Data, Extern});
476 Builder.CreateBr(IfEndBB);
477 Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalSurfaceEntry),
478 SwSurfaceBB);
479
480 // Create texture variable registration code.
481 Builder.SetInsertPoint(SwTextureBB);
482 if (EmitSurfacesAndTextures)
483 Builder.CreateCall(RegTexture, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
484 Data, Normalized, Extern});
485 Builder.CreateBr(IfEndBB);
486 Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalTextureEntry),
487 SwTextureBB);
488
489 Builder.SetInsertPoint(IfEndBB);
490 auto *NewEntry = Builder.CreateInBoundsGEP(
491 offloading::getEntryTy(M), Entry, ConstantInt::get(getSizeTTy(M), 1));
492 auto *Cmp = Builder.CreateICmpEQ(
493 NewEntry,
495 ArrayType::get(offloading::getEntryTy(M), 0), EntriesE,
496 ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),
497 ConstantInt::get(getSizeTTy(M), 0)})));
498 Entry->addIncoming(
500 ArrayType::get(offloading::getEntryTy(M), 0), EntriesB,
501 ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),
502 ConstantInt::get(getSizeTTy(M), 0)})),
503 &RegGlobalsFn->getEntryBlock());
504 Entry->addIncoming(NewEntry, IfEndBB);
505 Builder.CreateCondBr(Cmp, ExitBB, EntryBB);
506 Builder.SetInsertPoint(ExitBB);
507 Builder.CreateRetVoid();
508
509 return RegGlobalsFn;
510}
511
512// Create the constructor and destructor to register the fatbinary with the CUDA
513// runtime.
514void createRegisterFatbinFunction(Module &M, GlobalVariable *FatbinDesc,
515 bool IsHIP, EntryArrayTy EntryArray,
516 StringRef Suffix,
517 bool EmitSurfacesAndTextures) {
518 LLVMContext &C = M.getContext();
519 auto *CtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
520 auto *CtorFunc = Function::Create(
522 (IsHIP ? ".hip.fatbin_reg" : ".cuda.fatbin_reg") + Suffix, &M);
523 CtorFunc->setSection(".text.startup");
524
525 auto *DtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
526 auto *DtorFunc = Function::Create(
528 (IsHIP ? ".hip.fatbin_unreg" : ".cuda.fatbin_unreg") + Suffix, &M);
529 DtorFunc->setSection(".text.startup");
530
531 auto *PtrTy = PointerType::getUnqual(C);
532
533 // Get the __cudaRegisterFatBinary function declaration.
534 auto *RegFatTy = FunctionType::get(PtrTy, PtrTy, /*isVarArg=*/false);
535 FunctionCallee RegFatbin = M.getOrInsertFunction(
536 IsHIP ? "__hipRegisterFatBinary" : "__cudaRegisterFatBinary", RegFatTy);
537 // Get the __cudaRegisterFatBinaryEnd function declaration.
538 auto *RegFatEndTy =
539 FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);
540 FunctionCallee RegFatbinEnd =
541 M.getOrInsertFunction("__cudaRegisterFatBinaryEnd", RegFatEndTy);
542 // Get the __cudaUnregisterFatBinary function declaration.
543 auto *UnregFatTy =
544 FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);
545 FunctionCallee UnregFatbin = M.getOrInsertFunction(
546 IsHIP ? "__hipUnregisterFatBinary" : "__cudaUnregisterFatBinary",
547 UnregFatTy);
548
549 auto *AtExitTy =
550 FunctionType::get(Type::getInt32Ty(C), PtrTy, /*isVarArg=*/false);
551 FunctionCallee AtExit = M.getOrInsertFunction("atexit", AtExitTy);
552
553 auto *BinaryHandleGlobal = new llvm::GlobalVariable(
554 M, PtrTy, false, llvm::GlobalValue::InternalLinkage,
556 (IsHIP ? ".hip.binary_handle" : ".cuda.binary_handle") + Suffix);
557
558 // Create the constructor to register this image with the runtime.
559 IRBuilder<> CtorBuilder(BasicBlock::Create(C, "entry", CtorFunc));
560 CallInst *Handle = CtorBuilder.CreateCall(
561 RegFatbin,
563 CtorBuilder.CreateAlignedStore(
564 Handle, BinaryHandleGlobal,
565 Align(M.getDataLayout().getPointerTypeSize(PtrTy)));
566 CtorBuilder.CreateCall(createRegisterGlobalsFunction(M, IsHIP, EntryArray,
567 Suffix,
568 EmitSurfacesAndTextures),
569 Handle);
570 if (!IsHIP)
571 CtorBuilder.CreateCall(RegFatbinEnd, Handle);
572 CtorBuilder.CreateCall(AtExit, DtorFunc);
573 CtorBuilder.CreateRetVoid();
574
575 // Create the destructor to unregister the image with the runtime. We cannot
576 // use a standard global destructor after CUDA 9.2 so this must be called by
577 // `atexit()` intead.
578 IRBuilder<> DtorBuilder(BasicBlock::Create(C, "entry", DtorFunc));
579 LoadInst *BinaryHandle = DtorBuilder.CreateAlignedLoad(
580 PtrTy, BinaryHandleGlobal,
581 Align(M.getDataLayout().getPointerTypeSize(PtrTy)));
582 DtorBuilder.CreateCall(UnregFatbin, BinaryHandle);
583 DtorBuilder.CreateRetVoid();
584
585 // Add this function to constructors.
586 appendToGlobalCtors(M, CtorFunc, /*Priority=*/101);
587}
588} // namespace
589
591 EntryArrayTy EntryArray,
592 llvm::StringRef Suffix, bool Relocatable) {
594 createBinDesc(M, Images, EntryArray, Suffix, Relocatable);
595 if (!Desc)
597 "No binary descriptors created.");
598 createRegisterFunction(M, Desc, Suffix);
599 return Error::success();
600}
601
603 EntryArrayTy EntryArray,
604 llvm::StringRef Suffix,
605 bool EmitSurfacesAndTextures) {
606 GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/false, Suffix);
607 if (!Desc)
609 "No fatbin section created.");
610
611 createRegisterFatbinFunction(M, Desc, /*IsHip=*/false, EntryArray, Suffix,
612 EmitSurfacesAndTextures);
613 return Error::success();
614}
615
617 EntryArrayTy EntryArray, llvm::StringRef Suffix,
618 bool EmitSurfacesAndTextures) {
619 GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/true, Suffix);
620 if (!Desc)
622 "No fatbin section created.");
623
624 createRegisterFatbinFunction(M, Desc, /*IsHip=*/true, EntryArray, Suffix,
625 EmitSurfacesAndTextures);
626 return Error::success();
627}
static IntegerType * getSizeTTy(IRBuilderBase &B, const TargetLibraryInfo *TLI)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
uint64_t Addr
std::string Name
uint64_t Size
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
@ ConstantBit
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1291
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:705
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1226
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2087
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1200
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1775
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1356
This is an important base class in LLVM.
Definition: Constant.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:164
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
Class to represent integer types.
Definition: DerivedTypes.h:40
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
size_t size() const
Definition: SmallVector.h:91
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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:632
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:513
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isMacOSX() const
Is this a Mac OS X triple.
Definition: Triple.h:517
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
static uint64_t getAlignment()
Definition: OffloadBinary.h:84
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
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:19
@ OffloadGlobalSurfaceEntry
Mark the entry as a surface variable.
Definition: Utility.h:27
@ OffloadGlobalTextureEntry
Mark the entry as a texture variable.
Definition: Utility.h:29
@ OffloadGlobalNormalized
Mark the entry as being a normalized surface.
Definition: Utility.h:35
@ OffloadGlobalEntry
Mark the entry as a global entry.
Definition: Utility.h:23
@ OffloadGlobalManagedEntry
Mark the entry as a managed global variable.
Definition: Utility.h:25
@ OffloadGlobalExtern
Mark the entry as being extern.
Definition: Utility.h:31
@ OffloadGlobalConstant
Mark the entry as being constant.
Definition: Utility.h:33
llvm::Error wrapOpenMPBinaries(llvm::Module &M, llvm::ArrayRef< llvm::ArrayRef< char > > Images, EntryArrayTy EntryArray, llvm::StringRef Suffix="", bool Relocatable=false)
Wraps the input device images into the module M as global symbols and registers the images with the O...
std::pair< GlobalVariable *, GlobalVariable * > EntryArrayTy
llvm::Error wrapHIPBinary(llvm::Module &M, llvm::ArrayRef< char > Images, EntryArrayTy EntryArray, llvm::StringRef Suffix="", bool EmitSurfacesAndTextures=true)
Wraps the input bundled image into the module M as global symbols and registers the images with the H...
llvm::Error wrapCudaBinary(llvm::Module &M, llvm::ArrayRef< char > Images, EntryArrayTy EntryArray, llvm::StringRef Suffix="", bool EmitSurfacesAndTextures=true)
Wraps the input fatbinary image into the module M as global symbols and registers the images with the...
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:90
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1258
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:73
@ Extern
Replace returns with jump to thunk, don't emit thunk.
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.
@ offload_binary
LLVM offload object file.
Definition: Magic.h:57