Path: blob/main/contrib/llvm-project/llvm/lib/Frontend/Offloading/OffloadWrapper.cpp
35271 views
//===- OffloadWrapper.cpp ---------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/Frontend/Offloading/OffloadWrapper.h"9#include "llvm/ADT/ArrayRef.h"10#include "llvm/BinaryFormat/Magic.h"11#include "llvm/Frontend/Offloading/Utility.h"12#include "llvm/IR/Constants.h"13#include "llvm/IR/GlobalVariable.h"14#include "llvm/IR/IRBuilder.h"15#include "llvm/IR/LLVMContext.h"16#include "llvm/IR/Module.h"17#include "llvm/Object/OffloadBinary.h"18#include "llvm/Support/Error.h"19#include "llvm/TargetParser/Triple.h"20#include "llvm/Transforms/Utils/ModuleUtils.h"2122using namespace llvm;23using namespace llvm::offloading;2425namespace {26/// Magic number that begins the section containing the CUDA fatbinary.27constexpr unsigned CudaFatMagic = 0x466243b1;28constexpr unsigned HIPFatMagic = 0x48495046;2930IntegerType *getSizeTTy(Module &M) {31return M.getDataLayout().getIntPtrType(M.getContext());32}3334// struct __tgt_device_image {35// void *ImageStart;36// void *ImageEnd;37// __tgt_offload_entry *EntriesBegin;38// __tgt_offload_entry *EntriesEnd;39// };40StructType *getDeviceImageTy(Module &M) {41LLVMContext &C = M.getContext();42StructType *ImageTy = StructType::getTypeByName(C, "__tgt_device_image");43if (!ImageTy)44ImageTy =45StructType::create("__tgt_device_image", PointerType::getUnqual(C),46PointerType::getUnqual(C), PointerType::getUnqual(C),47PointerType::getUnqual(C));48return ImageTy;49}5051PointerType *getDeviceImagePtrTy(Module &M) {52return PointerType::getUnqual(getDeviceImageTy(M));53}5455// struct __tgt_bin_desc {56// int32_t NumDeviceImages;57// __tgt_device_image *DeviceImages;58// __tgt_offload_entry *HostEntriesBegin;59// __tgt_offload_entry *HostEntriesEnd;60// };61StructType *getBinDescTy(Module &M) {62LLVMContext &C = M.getContext();63StructType *DescTy = StructType::getTypeByName(C, "__tgt_bin_desc");64if (!DescTy)65DescTy = StructType::create(66"__tgt_bin_desc", Type::getInt32Ty(C), getDeviceImagePtrTy(M),67PointerType::getUnqual(C), PointerType::getUnqual(C));68return DescTy;69}7071PointerType *getBinDescPtrTy(Module &M) {72return PointerType::getUnqual(getBinDescTy(M));73}7475/// Creates binary descriptor for the given device images. Binary descriptor76/// is an object that is passed to the offloading runtime at program startup77/// and it describes all device images available in the executable or shared78/// library. It is defined as follows79///80/// __attribute__((visibility("hidden")))81/// extern __tgt_offload_entry *__start_omp_offloading_entries;82/// __attribute__((visibility("hidden")))83/// extern __tgt_offload_entry *__stop_omp_offloading_entries;84///85/// static const char Image0[] = { <Bufs.front() contents> };86/// ...87/// static const char ImageN[] = { <Bufs.back() contents> };88///89/// static const __tgt_device_image Images[] = {90/// {91/// Image0, /*ImageStart*/92/// Image0 + sizeof(Image0), /*ImageEnd*/93/// __start_omp_offloading_entries, /*EntriesBegin*/94/// __stop_omp_offloading_entries /*EntriesEnd*/95/// },96/// ...97/// {98/// ImageN, /*ImageStart*/99/// ImageN + sizeof(ImageN), /*ImageEnd*/100/// __start_omp_offloading_entries, /*EntriesBegin*/101/// __stop_omp_offloading_entries /*EntriesEnd*/102/// }103/// };104///105/// static const __tgt_bin_desc BinDesc = {106/// sizeof(Images) / sizeof(Images[0]), /*NumDeviceImages*/107/// Images, /*DeviceImages*/108/// __start_omp_offloading_entries, /*HostEntriesBegin*/109/// __stop_omp_offloading_entries /*HostEntriesEnd*/110/// };111///112/// Global variable that represents BinDesc is returned.113GlobalVariable *createBinDesc(Module &M, ArrayRef<ArrayRef<char>> Bufs,114EntryArrayTy EntryArray, StringRef Suffix,115bool Relocatable) {116LLVMContext &C = M.getContext();117auto [EntriesB, EntriesE] = EntryArray;118119auto *Zero = ConstantInt::get(getSizeTTy(M), 0u);120Constant *ZeroZero[] = {Zero, Zero};121122// Create initializer for the images array.123SmallVector<Constant *, 4u> ImagesInits;124ImagesInits.reserve(Bufs.size());125for (ArrayRef<char> Buf : Bufs) {126// We embed the full offloading entry so the binary utilities can parse it.127auto *Data = ConstantDataArray::get(C, Buf);128auto *Image = new GlobalVariable(M, Data->getType(), /*isConstant=*/true,129GlobalVariable::InternalLinkage, Data,130".omp_offloading.device_image" + Suffix);131Image->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);132Image->setSection(Relocatable ? ".llvm.offloading.relocatable"133: ".llvm.offloading");134Image->setAlignment(Align(object::OffloadBinary::getAlignment()));135136StringRef Binary(Buf.data(), Buf.size());137assert(identify_magic(Binary) == file_magic::offload_binary &&138"Invalid binary format");139140// The device image struct contains the pointer to the beginning and end of141// the image stored inside of the offload binary. There should only be one142// of these for each buffer so we parse it out manually.143const auto *Header =144reinterpret_cast<const object::OffloadBinary::Header *>(145Binary.bytes_begin());146const auto *Entry = reinterpret_cast<const object::OffloadBinary::Entry *>(147Binary.bytes_begin() + Header->EntryOffset);148149auto *Begin = ConstantInt::get(getSizeTTy(M), Entry->ImageOffset);150auto *Size =151ConstantInt::get(getSizeTTy(M), Entry->ImageOffset + Entry->ImageSize);152Constant *ZeroBegin[] = {Zero, Begin};153Constant *ZeroSize[] = {Zero, Size};154155auto *ImageB =156ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroBegin);157auto *ImageE =158ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroSize);159160ImagesInits.push_back(ConstantStruct::get(getDeviceImageTy(M), ImageB,161ImageE, EntriesB, EntriesE));162}163164// Then create images array.165auto *ImagesData = ConstantArray::get(166ArrayType::get(getDeviceImageTy(M), ImagesInits.size()), ImagesInits);167168auto *Images =169new GlobalVariable(M, ImagesData->getType(), /*isConstant*/ true,170GlobalValue::InternalLinkage, ImagesData,171".omp_offloading.device_images" + Suffix);172Images->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);173174auto *ImagesB =175ConstantExpr::getGetElementPtr(Images->getValueType(), Images, ZeroZero);176177// And finally create the binary descriptor object.178auto *DescInit = ConstantStruct::get(179getBinDescTy(M),180ConstantInt::get(Type::getInt32Ty(C), ImagesInits.size()), ImagesB,181EntriesB, EntriesE);182183return new GlobalVariable(M, DescInit->getType(), /*isConstant*/ true,184GlobalValue::InternalLinkage, DescInit,185".omp_offloading.descriptor" + Suffix);186}187188Function *createUnregisterFunction(Module &M, GlobalVariable *BinDesc,189StringRef Suffix) {190LLVMContext &C = M.getContext();191auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);192auto *Func =193Function::Create(FuncTy, GlobalValue::InternalLinkage,194".omp_offloading.descriptor_unreg" + Suffix, &M);195Func->setSection(".text.startup");196197// Get __tgt_unregister_lib function declaration.198auto *UnRegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),199/*isVarArg*/ false);200FunctionCallee UnRegFuncC =201M.getOrInsertFunction("__tgt_unregister_lib", UnRegFuncTy);202203// Construct function body204IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));205Builder.CreateCall(UnRegFuncC, BinDesc);206Builder.CreateRetVoid();207208return Func;209}210211void createRegisterFunction(Module &M, GlobalVariable *BinDesc,212StringRef Suffix) {213LLVMContext &C = M.getContext();214auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);215auto *Func = Function::Create(FuncTy, GlobalValue::InternalLinkage,216".omp_offloading.descriptor_reg" + Suffix, &M);217Func->setSection(".text.startup");218219// Get __tgt_register_lib function declaration.220auto *RegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),221/*isVarArg*/ false);222FunctionCallee RegFuncC =223M.getOrInsertFunction("__tgt_register_lib", RegFuncTy);224225auto *AtExitTy = FunctionType::get(226Type::getInt32Ty(C), PointerType::getUnqual(C), /*isVarArg=*/false);227FunctionCallee AtExit = M.getOrInsertFunction("atexit", AtExitTy);228229Function *UnregFunc = createUnregisterFunction(M, BinDesc, Suffix);230231// Construct function body232IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));233234Builder.CreateCall(RegFuncC, BinDesc);235236// Register the destructors with 'atexit'. This is expected by the CUDA237// runtime and ensures that we clean up before dynamic objects are destroyed.238// This needs to be done after plugin initialization to ensure that it is239// called before the plugin runtime is destroyed.240Builder.CreateCall(AtExit, UnregFunc);241Builder.CreateRetVoid();242243// Add this function to constructors.244appendToGlobalCtors(M, Func, /*Priority=*/101);245}246247// struct fatbin_wrapper {248// int32_t magic;249// int32_t version;250// void *image;251// void *reserved;252//};253StructType *getFatbinWrapperTy(Module &M) {254LLVMContext &C = M.getContext();255StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");256if (!FatbinTy)257FatbinTy = StructType::create(258"fatbin_wrapper", Type::getInt32Ty(C), Type::getInt32Ty(C),259PointerType::getUnqual(C), PointerType::getUnqual(C));260return FatbinTy;261}262263/// Embed the image \p Image into the module \p M so it can be found by the264/// runtime.265GlobalVariable *createFatbinDesc(Module &M, ArrayRef<char> Image, bool IsHIP,266StringRef Suffix) {267LLVMContext &C = M.getContext();268llvm::Type *Int8PtrTy = PointerType::getUnqual(C);269llvm::Triple Triple = llvm::Triple(M.getTargetTriple());270271// Create the global string containing the fatbinary.272StringRef FatbinConstantSection =273IsHIP ? ".hip_fatbin"274: (Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin");275auto *Data = ConstantDataArray::get(C, Image);276auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,277GlobalVariable::InternalLinkage, Data,278".fatbin_image" + Suffix);279Fatbin->setSection(FatbinConstantSection);280281// Create the fatbinary wrapper282StringRef FatbinWrapperSection = IsHIP ? ".hipFatBinSegment"283: Triple.isMacOSX() ? "__NV_CUDA,__fatbin"284: ".nvFatBinSegment";285Constant *FatbinWrapper[] = {286ConstantInt::get(Type::getInt32Ty(C), IsHIP ? HIPFatMagic : CudaFatMagic),287ConstantInt::get(Type::getInt32Ty(C), 1),288ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),289ConstantPointerNull::get(PointerType::getUnqual(C))};290291Constant *FatbinInitializer =292ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);293294auto *FatbinDesc =295new GlobalVariable(M, getFatbinWrapperTy(M),296/*isConstant*/ true, GlobalValue::InternalLinkage,297FatbinInitializer, ".fatbin_wrapper" + Suffix);298FatbinDesc->setSection(FatbinWrapperSection);299FatbinDesc->setAlignment(Align(8));300301return FatbinDesc;302}303304/// Create the register globals function. We will iterate all of the offloading305/// entries stored at the begin / end symbols and register them according to306/// 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/// else323/// __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,324/// 0, entry->size, 0, 0);325/// }326/// }327Function *createRegisterGlobalsFunction(Module &M, bool IsHIP,328EntryArrayTy EntryArray,329StringRef Suffix,330bool EmitSurfacesAndTextures) {331LLVMContext &C = M.getContext();332auto [EntriesB, EntriesE] = EntryArray;333334// Get the __cudaRegisterFunction function declaration.335PointerType *Int8PtrTy = PointerType::get(C, 0);336PointerType *Int8PtrPtrTy = PointerType::get(C, 0);337PointerType *Int32PtrTy = PointerType::get(C, 0);338auto *RegFuncTy = FunctionType::get(339Type::getInt32Ty(C),340{Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),341Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32PtrTy},342/*isVarArg*/ false);343FunctionCallee RegFunc = M.getOrInsertFunction(344IsHIP ? "__hipRegisterFunction" : "__cudaRegisterFunction", RegFuncTy);345346// Get the __cudaRegisterVar function declaration.347auto *RegVarTy = FunctionType::get(348Type::getVoidTy(C),349{Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),350getSizeTTy(M), Type::getInt32Ty(C), Type::getInt32Ty(C)},351/*isVarArg*/ false);352FunctionCallee RegVar = M.getOrInsertFunction(353IsHIP ? "__hipRegisterVar" : "__cudaRegisterVar", RegVarTy);354355// Get the __cudaRegisterSurface function declaration.356FunctionType *RegSurfaceTy =357FunctionType::get(Type::getVoidTy(C),358{Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy,359Type::getInt32Ty(C), Type::getInt32Ty(C)},360/*isVarArg=*/false);361FunctionCallee RegSurface = M.getOrInsertFunction(362IsHIP ? "__hipRegisterSurface" : "__cudaRegisterSurface", RegSurfaceTy);363364// Get the __cudaRegisterTexture function declaration.365FunctionType *RegTextureTy = FunctionType::get(366Type::getVoidTy(C),367{Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),368Type::getInt32Ty(C), Type::getInt32Ty(C)},369/*isVarArg=*/false);370FunctionCallee RegTexture = M.getOrInsertFunction(371IsHIP ? "__hipRegisterTexture" : "__cudaRegisterTexture", RegTextureTy);372373auto *RegGlobalsTy = FunctionType::get(Type::getVoidTy(C), Int8PtrPtrTy,374/*isVarArg*/ false);375auto *RegGlobalsFn =376Function::Create(RegGlobalsTy, GlobalValue::InternalLinkage,377IsHIP ? ".hip.globals_reg" : ".cuda.globals_reg", &M);378RegGlobalsFn->setSection(".text.startup");379380// Create the loop to register all the entries.381IRBuilder<> Builder(BasicBlock::Create(C, "entry", RegGlobalsFn));382auto *EntryBB = BasicBlock::Create(C, "while.entry", RegGlobalsFn);383auto *IfThenBB = BasicBlock::Create(C, "if.then", RegGlobalsFn);384auto *IfElseBB = BasicBlock::Create(C, "if.else", RegGlobalsFn);385auto *SwGlobalBB = BasicBlock::Create(C, "sw.global", RegGlobalsFn);386auto *SwManagedBB = BasicBlock::Create(C, "sw.managed", RegGlobalsFn);387auto *SwSurfaceBB = BasicBlock::Create(C, "sw.surface", RegGlobalsFn);388auto *SwTextureBB = BasicBlock::Create(C, "sw.texture", RegGlobalsFn);389auto *IfEndBB = BasicBlock::Create(C, "if.end", RegGlobalsFn);390auto *ExitBB = BasicBlock::Create(C, "while.end", RegGlobalsFn);391392auto *EntryCmp = Builder.CreateICmpNE(EntriesB, EntriesE);393Builder.CreateCondBr(EntryCmp, EntryBB, ExitBB);394Builder.SetInsertPoint(EntryBB);395auto *Entry = Builder.CreatePHI(PointerType::getUnqual(C), 2, "entry");396auto *AddrPtr =397Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,398{ConstantInt::get(getSizeTTy(M), 0),399ConstantInt::get(Type::getInt32Ty(C), 0)});400auto *Addr = Builder.CreateLoad(Int8PtrTy, AddrPtr, "addr");401auto *NamePtr =402Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,403{ConstantInt::get(getSizeTTy(M), 0),404ConstantInt::get(Type::getInt32Ty(C), 1)});405auto *Name = Builder.CreateLoad(Int8PtrTy, NamePtr, "name");406auto *SizePtr =407Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,408{ConstantInt::get(getSizeTTy(M), 0),409ConstantInt::get(Type::getInt32Ty(C), 2)});410auto *Size = Builder.CreateLoad(getSizeTTy(M), SizePtr, "size");411auto *FlagsPtr =412Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,413{ConstantInt::get(getSizeTTy(M), 0),414ConstantInt::get(Type::getInt32Ty(C), 3)});415auto *Flags = Builder.CreateLoad(Type::getInt32Ty(C), FlagsPtr, "flags");416auto *DataPtr =417Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,418{ConstantInt::get(getSizeTTy(M), 0),419ConstantInt::get(Type::getInt32Ty(C), 4)});420auto *Data = Builder.CreateLoad(Type::getInt32Ty(C), DataPtr, "textype");421auto *Kind = Builder.CreateAnd(422Flags, ConstantInt::get(Type::getInt32Ty(C), 0x7), "type");423424// Extract the flags stored in the bit-field and convert them to C booleans.425auto *ExternBit = Builder.CreateAnd(426Flags, ConstantInt::get(Type::getInt32Ty(C),427llvm::offloading::OffloadGlobalExtern));428auto *Extern = Builder.CreateLShr(429ExternBit, ConstantInt::get(Type::getInt32Ty(C), 3), "extern");430auto *ConstantBit = Builder.CreateAnd(431Flags, ConstantInt::get(Type::getInt32Ty(C),432llvm::offloading::OffloadGlobalConstant));433auto *Const = Builder.CreateLShr(434ConstantBit, ConstantInt::get(Type::getInt32Ty(C), 4), "constant");435auto *NormalizedBit = Builder.CreateAnd(436Flags, ConstantInt::get(Type::getInt32Ty(C),437llvm::offloading::OffloadGlobalNormalized));438auto *Normalized = Builder.CreateLShr(439NormalizedBit, ConstantInt::get(Type::getInt32Ty(C), 5), "normalized");440auto *FnCond =441Builder.CreateICmpEQ(Size, ConstantInt::getNullValue(getSizeTTy(M)));442Builder.CreateCondBr(FnCond, IfThenBB, IfElseBB);443444// Create kernel registration code.445Builder.SetInsertPoint(IfThenBB);446Builder.CreateCall(RegFunc, {RegGlobalsFn->arg_begin(), Addr, Name, Name,447ConstantInt::get(Type::getInt32Ty(C), -1),448ConstantPointerNull::get(Int8PtrTy),449ConstantPointerNull::get(Int8PtrTy),450ConstantPointerNull::get(Int8PtrTy),451ConstantPointerNull::get(Int8PtrTy),452ConstantPointerNull::get(Int32PtrTy)});453Builder.CreateBr(IfEndBB);454Builder.SetInsertPoint(IfElseBB);455456auto *Switch = Builder.CreateSwitch(Kind, IfEndBB);457// Create global variable registration code.458Builder.SetInsertPoint(SwGlobalBB);459Builder.CreateCall(RegVar,460{RegGlobalsFn->arg_begin(), Addr, Name, Name, Extern, Size,461Const, ConstantInt::get(Type::getInt32Ty(C), 0)});462Builder.CreateBr(IfEndBB);463Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalEntry),464SwGlobalBB);465466// Create managed variable registration code.467Builder.SetInsertPoint(SwManagedBB);468Builder.CreateBr(IfEndBB);469Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalManagedEntry),470SwManagedBB);471// Create surface variable registration code.472Builder.SetInsertPoint(SwSurfaceBB);473if (EmitSurfacesAndTextures)474Builder.CreateCall(RegSurface, {RegGlobalsFn->arg_begin(), Addr, Name, Name,475Data, Extern});476Builder.CreateBr(IfEndBB);477Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalSurfaceEntry),478SwSurfaceBB);479480// Create texture variable registration code.481Builder.SetInsertPoint(SwTextureBB);482if (EmitSurfacesAndTextures)483Builder.CreateCall(RegTexture, {RegGlobalsFn->arg_begin(), Addr, Name, Name,484Data, Normalized, Extern});485Builder.CreateBr(IfEndBB);486Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalTextureEntry),487SwTextureBB);488489Builder.SetInsertPoint(IfEndBB);490auto *NewEntry = Builder.CreateInBoundsGEP(491offloading::getEntryTy(M), Entry, ConstantInt::get(getSizeTTy(M), 1));492auto *Cmp = Builder.CreateICmpEQ(493NewEntry,494ConstantExpr::getInBoundsGetElementPtr(495ArrayType::get(offloading::getEntryTy(M), 0), EntriesE,496ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),497ConstantInt::get(getSizeTTy(M), 0)})));498Entry->addIncoming(499ConstantExpr::getInBoundsGetElementPtr(500ArrayType::get(offloading::getEntryTy(M), 0), EntriesB,501ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),502ConstantInt::get(getSizeTTy(M), 0)})),503&RegGlobalsFn->getEntryBlock());504Entry->addIncoming(NewEntry, IfEndBB);505Builder.CreateCondBr(Cmp, ExitBB, EntryBB);506Builder.SetInsertPoint(ExitBB);507Builder.CreateRetVoid();508509return RegGlobalsFn;510}511512// Create the constructor and destructor to register the fatbinary with the CUDA513// runtime.514void createRegisterFatbinFunction(Module &M, GlobalVariable *FatbinDesc,515bool IsHIP, EntryArrayTy EntryArray,516StringRef Suffix,517bool EmitSurfacesAndTextures) {518LLVMContext &C = M.getContext();519auto *CtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);520auto *CtorFunc = Function::Create(521CtorFuncTy, GlobalValue::InternalLinkage,522(IsHIP ? ".hip.fatbin_reg" : ".cuda.fatbin_reg") + Suffix, &M);523CtorFunc->setSection(".text.startup");524525auto *DtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);526auto *DtorFunc = Function::Create(527DtorFuncTy, GlobalValue::InternalLinkage,528(IsHIP ? ".hip.fatbin_unreg" : ".cuda.fatbin_unreg") + Suffix, &M);529DtorFunc->setSection(".text.startup");530531auto *PtrTy = PointerType::getUnqual(C);532533// Get the __cudaRegisterFatBinary function declaration.534auto *RegFatTy = FunctionType::get(PtrTy, PtrTy, /*isVarArg=*/false);535FunctionCallee RegFatbin = M.getOrInsertFunction(536IsHIP ? "__hipRegisterFatBinary" : "__cudaRegisterFatBinary", RegFatTy);537// Get the __cudaRegisterFatBinaryEnd function declaration.538auto *RegFatEndTy =539FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);540FunctionCallee RegFatbinEnd =541M.getOrInsertFunction("__cudaRegisterFatBinaryEnd", RegFatEndTy);542// Get the __cudaUnregisterFatBinary function declaration.543auto *UnregFatTy =544FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);545FunctionCallee UnregFatbin = M.getOrInsertFunction(546IsHIP ? "__hipUnregisterFatBinary" : "__cudaUnregisterFatBinary",547UnregFatTy);548549auto *AtExitTy =550FunctionType::get(Type::getInt32Ty(C), PtrTy, /*isVarArg=*/false);551FunctionCallee AtExit = M.getOrInsertFunction("atexit", AtExitTy);552553auto *BinaryHandleGlobal = new llvm::GlobalVariable(554M, PtrTy, false, llvm::GlobalValue::InternalLinkage,555llvm::ConstantPointerNull::get(PtrTy),556(IsHIP ? ".hip.binary_handle" : ".cuda.binary_handle") + Suffix);557558// Create the constructor to register this image with the runtime.559IRBuilder<> CtorBuilder(BasicBlock::Create(C, "entry", CtorFunc));560CallInst *Handle = CtorBuilder.CreateCall(561RegFatbin,562ConstantExpr::getPointerBitCastOrAddrSpaceCast(FatbinDesc, PtrTy));563CtorBuilder.CreateAlignedStore(564Handle, BinaryHandleGlobal,565Align(M.getDataLayout().getPointerTypeSize(PtrTy)));566CtorBuilder.CreateCall(createRegisterGlobalsFunction(M, IsHIP, EntryArray,567Suffix,568EmitSurfacesAndTextures),569Handle);570if (!IsHIP)571CtorBuilder.CreateCall(RegFatbinEnd, Handle);572CtorBuilder.CreateCall(AtExit, DtorFunc);573CtorBuilder.CreateRetVoid();574575// Create the destructor to unregister the image with the runtime. We cannot576// use a standard global destructor after CUDA 9.2 so this must be called by577// `atexit()` intead.578IRBuilder<> DtorBuilder(BasicBlock::Create(C, "entry", DtorFunc));579LoadInst *BinaryHandle = DtorBuilder.CreateAlignedLoad(580PtrTy, BinaryHandleGlobal,581Align(M.getDataLayout().getPointerTypeSize(PtrTy)));582DtorBuilder.CreateCall(UnregFatbin, BinaryHandle);583DtorBuilder.CreateRetVoid();584585// Add this function to constructors.586appendToGlobalCtors(M, CtorFunc, /*Priority=*/101);587}588} // namespace589590Error offloading::wrapOpenMPBinaries(Module &M, ArrayRef<ArrayRef<char>> Images,591EntryArrayTy EntryArray,592llvm::StringRef Suffix, bool Relocatable) {593GlobalVariable *Desc =594createBinDesc(M, Images, EntryArray, Suffix, Relocatable);595if (!Desc)596return createStringError(inconvertibleErrorCode(),597"No binary descriptors created.");598createRegisterFunction(M, Desc, Suffix);599return Error::success();600}601602Error offloading::wrapCudaBinary(Module &M, ArrayRef<char> Image,603EntryArrayTy EntryArray,604llvm::StringRef Suffix,605bool EmitSurfacesAndTextures) {606GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/false, Suffix);607if (!Desc)608return createStringError(inconvertibleErrorCode(),609"No fatbin section created.");610611createRegisterFatbinFunction(M, Desc, /*IsHip=*/false, EntryArray, Suffix,612EmitSurfacesAndTextures);613return Error::success();614}615616Error offloading::wrapHIPBinary(Module &M, ArrayRef<char> Image,617EntryArrayTy EntryArray, llvm::StringRef Suffix,618bool EmitSurfacesAndTextures) {619GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/true, Suffix);620if (!Desc)621return createStringError(inconvertibleErrorCode(),622"No fatbin section created.");623624createRegisterFatbinFunction(M, Desc, /*IsHip=*/true, EntryArray, Suffix,625EmitSurfacesAndTextures);626return Error::success();627}628629630