20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/FormatVariadic.h"
26#include "llvm/Transforms/Utils/ModuleUtils.h"
32class SelectObjectAttrImpl
33 :
public gpu::OffloadingLLVMTranslationAttrInterface::FallbackModel<
34 SelectObjectAttrImpl> {
36 gpu::ObjectAttr getSelectedObject(gpu::BinaryOp op)
const;
42 LogicalResult embedBinary(Attribute attribute, Operation *operation,
43 llvm::IRBuilderBase &builder,
44 LLVM::ModuleTranslation &moduleTranslation)
const;
49 Operation *launchFuncOperation,
50 Operation *binaryOperation,
51 llvm::IRBuilderBase &builder,
52 LLVM::ModuleTranslation &moduleTranslation)
const;
57SelectObjectAttrImpl::getSelectedObject(gpu::BinaryOp op)
const {
58 ArrayRef<Attribute> objects = op.getObjectsAttr().getValue();
63 cast<gpu::SelectObjectAttr>(op.getOffloadingHandlerAttr())
67 if (
auto indexAttr = mlir::dyn_cast<IntegerAttr>(
target)) {
68 index = indexAttr.getInt();
70 for (
auto [i, attr] : llvm::enumerate(objects)) {
71 auto obj = mlir::dyn_cast<gpu::ObjectAttr>(attr);
72 if (obj.getTarget() ==
target) {
83 if (index < 0 || index >=
static_cast<int64_t
>(objects.size())) {
84 op->emitError(
"the requested target object couldn't be found");
87 return mlir::dyn_cast<gpu::ObjectAttr>(objects[index]);
91 return moduleName +
"_module";
96 gpu::ObjectAttr
object, Module &module) {
101 bool addNull = (
object.getFormat() == gpu::CompilationTarget::Assembly);
102 StringRef serializedStr =
object.getObject().getValue();
104 ConstantDataArray::getString(module.getContext(), serializedStr, addNull);
105 GlobalVariable *serializedObj =
106 new GlobalVariable(module, serializedCst->getType(),
true,
107 GlobalValue::LinkageTypes::InternalLinkage,
108 serializedCst, moduleName +
"_binary");
109 serializedObj->setAlignment(MaybeAlign(8));
110 serializedObj->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
113 auto optLevel = APInt::getZero(32);
115 if (DictionaryAttr objectProps =
object.getProperties()) {
116 if (
auto section = dyn_cast_or_null<StringAttr>(
118 serializedObj->setSection(section.getValue());
121 if (
auto optAttr = dyn_cast_or_null<IntegerAttr>(objectProps.get(
"O")))
122 optLevel = optAttr.getValue();
125 IRBuilder<> builder(module.getContext());
126 auto *i32Ty = builder.getInt32Ty();
127 auto *i64Ty = builder.getInt64Ty();
128 auto *ptrTy = builder.getPtrTy(0);
129 auto *voidTy = builder.getVoidTy();
132 auto *modulePtr =
new GlobalVariable(
133 module, ptrTy,
false, GlobalValue::InternalLinkage,
134 ConstantPointerNull::get(ptrTy),
137 auto *loadFn = Function::Create(FunctionType::get(voidTy,
false),
138 GlobalValue::InternalLinkage,
139 moduleName +
"_load", module);
140 loadFn->setSection(
".text.startup");
141 auto *loadBlock = BasicBlock::Create(module.getContext(),
"entry", loadFn);
142 builder.SetInsertPoint(loadBlock);
143 Value *moduleObj = [&] {
145 ConstantInt::get(i64Ty, serializedStr.size() + (addNull ? 1 : 0));
146 if (
object.getFormat() == gpu::CompilationTarget::Assembly) {
147 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
148 "mgpuModuleLoadJIT", FunctionType::get(ptrTy,
156 Constant *optValue = ConstantInt::get(i32Ty, optLevel);
157 return builder.CreateCall(moduleLoadFn,
158 {serializedObj, optValue, binarySize});
160 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
161 "mgpuModuleLoad", FunctionType::get(ptrTy, {ptrTy, i64Ty}, false));
162 return builder.CreateCall(moduleLoadFn, {serializedObj, binarySize});
164 builder.CreateStore(moduleObj, modulePtr);
165 builder.CreateRetVoid();
166 appendToGlobalCtors(module, loadFn, 123);
168 auto *unloadFn = Function::Create(
169 FunctionType::get(voidTy,
false),
170 GlobalValue::InternalLinkage, moduleName +
"_unload", module);
171 unloadFn->setSection(
".text.startup");
173 BasicBlock::Create(module.getContext(),
"entry", unloadFn);
174 builder.SetInsertPoint(unloadBlock);
175 FunctionCallee moduleUnloadFn =
module.getOrInsertFunction(
176 "mgpuModuleUnload", FunctionType::get(voidTy, ptrTy, false));
177 builder.CreateCall(moduleUnloadFn, builder.CreateLoad(ptrTy, modulePtr));
178 builder.CreateRetVoid();
179 appendToGlobalDtors(module, unloadFn, 123);
185LogicalResult SelectObjectAttrImpl::embedBinary(
186 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
187 LLVM::ModuleTranslation &moduleTranslation)
const {
188 assert(operation &&
"The binary operation must be non null.");
192 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
194 operation->
emitError(
"operation must be a GPU binary");
198 gpu::ObjectAttr
object = getSelectedObject(op);
210 LaunchKernel(Module &module, IRBuilderBase &builder,
211 mlir::LLVM::ModuleTranslation &moduleTranslation);
213 FunctionCallee getKernelLaunchFn();
216 FunctionCallee getClusterKernelLaunchFn();
219 FunctionCallee getModuleFunctionFn();
222 FunctionCallee getStreamCreateFn();
225 FunctionCallee getStreamDestroyFn();
228 FunctionCallee getStreamSyncFn();
231 Value *getOrCreateFunctionName(StringRef moduleName, StringRef kernelName);
234 Value *createKernelArgArray(mlir::gpu::LaunchFuncOp op);
237 llvm::LogicalResult createKernelLaunch(mlir::gpu::LaunchFuncOp op,
238 mlir::gpu::ObjectAttr
object);
242 IRBuilderBase &builder;
243 mlir::LLVM::ModuleTranslation &moduleTranslation;
248 PointerType *ptrTy{};
253LogicalResult SelectObjectAttrImpl::launchKernel(
254 Attribute attribute, Operation *launchFuncOperation,
255 Operation *binaryOperation, llvm::IRBuilderBase &builder,
256 LLVM::ModuleTranslation &moduleTranslation)
const {
258 assert(launchFuncOperation &&
"The launch func operation must be non null.");
259 if (!launchFuncOperation)
262 auto launchFuncOp = mlir::dyn_cast<gpu::LaunchFuncOp>(launchFuncOperation);
264 launchFuncOperation->
emitError(
"operation must be a GPU launch func Op.");
268 auto binOp = mlir::dyn_cast<gpu::BinaryOp>(binaryOperation);
270 binaryOperation->
emitError(
"operation must be a GPU binary.");
273 gpu::ObjectAttr
object = getSelectedObject(binOp);
277 return llvm::LaunchKernel(*moduleTranslation.
getLLVMModule(), builder,
279 .createKernelLaunch(launchFuncOp,
object);
282llvm::LaunchKernel::LaunchKernel(
283 Module &module, IRBuilderBase &builder,
284 mlir::LLVM::ModuleTranslation &moduleTranslation)
285 : module(module), builder(builder), moduleTranslation(moduleTranslation) {
286 i32Ty = builder.getInt32Ty();
287 i64Ty = builder.getInt64Ty();
288 ptrTy = builder.getPtrTy(0);
289 voidTy = builder.getVoidTy();
290 intPtrTy = builder.getIntPtrTy(module.getDataLayout());
293llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchFn() {
294 return module.getOrInsertFunction(
296 FunctionType::get(voidTy,
297 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy,
298 intPtrTy, intPtrTy, intPtrTy, i32Ty,
299 ptrTy, ptrTy, ptrTy, i64Ty}),
303llvm::FunctionCallee llvm::LaunchKernel::getClusterKernelLaunchFn() {
304 return module.getOrInsertFunction(
305 "mgpuLaunchClusterKernel",
308 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
309 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
310 i32Ty, ptrTy, ptrTy, ptrTy}),
314llvm::FunctionCallee llvm::LaunchKernel::getModuleFunctionFn() {
315 return module.getOrInsertFunction(
316 "mgpuModuleGetFunction",
317 FunctionType::get(ptrTy, ArrayRef<Type *>({ptrTy, ptrTy}), false));
320llvm::FunctionCallee llvm::LaunchKernel::getStreamCreateFn() {
321 return module.getOrInsertFunction("mgpuStreamCreate",
322 FunctionType::get(ptrTy, false));
325llvm::FunctionCallee llvm::LaunchKernel::getStreamDestroyFn() {
326 return module.getOrInsertFunction(
328 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
331llvm::FunctionCallee llvm::LaunchKernel::getStreamSyncFn() {
332 return module.getOrInsertFunction(
333 "mgpuStreamSynchronize",
334 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
339llvm::Value *llvm::LaunchKernel::getOrCreateFunctionName(StringRef moduleName,
340 StringRef kernelName) {
341 std::string globalName =
342 std::string(formatv(
"{0}_{1}_name", moduleName, kernelName));
344 if (GlobalVariable *gv = module.getGlobalVariable(globalName,
true))
347 return builder.CreateGlobalString(kernelName, globalName);
364llvm::LaunchKernel::createKernelArgArray(mlir::gpu::LaunchFuncOp op) {
365 SmallVector<Value *> args =
367 SmallVector<Type *> structTypes(args.size(),
nullptr);
369 for (
auto [i, arg] : llvm::enumerate(args))
370 structTypes[i] = arg->getType();
372 Type *structTy = StructType::create(module.getContext(), structTypes);
373 Value *argStruct = builder.CreateAlloca(structTy, 0u);
374 Value *argArray = builder.CreateAlloca(
375 ptrTy, ConstantInt::get(intPtrTy, structTypes.size()));
378 Value *structMember = builder.CreateStructGEP(structTy, argStruct, i);
379 builder.CreateStore(arg, structMember);
380 Value *arrayMember = builder.CreateConstGEP1_32(ptrTy, argArray, i);
381 builder.CreateStore(structMember, arrayMember);
395llvm::LaunchKernel::createKernelLaunch(mlir::gpu::LaunchFuncOp op,
396 mlir::gpu::ObjectAttr
object) {
397 auto llvmValue = [&](mlir::Value value) -> Value * {
399 assert(v &&
"Value has not been translated.");
404 mlir::gpu::KernelDim3 grid = op.getGridSizeOperandValues();
405 Value *gx = llvmValue(grid.
x), *gy = llvmValue(grid.
y),
406 *gz = llvmValue(grid.
z);
409 mlir::gpu::KernelDim3 block = op.getBlockSizeOperandValues();
410 Value *bx = llvmValue(block.
x), *by = llvmValue(block.
y),
411 *bz = llvmValue(block.
z);
414 Value *dynamicMemorySize =
nullptr;
415 if (mlir::Value dynSz = op.getDynamicSharedMemorySize())
416 dynamicMemorySize = llvmValue(dynSz);
418 dynamicMemorySize = ConstantInt::get(i32Ty, 0);
421 Value *argArray = createKernelArgArray(op);
424 StringRef moduleName = op.getKernelModuleName().getValue();
426 Value *modulePtr =
module.getGlobalVariable(moduleIdentifier.str(), true);
428 return op.emitError() <<
"Couldn't find the binary: " << moduleIdentifier;
429 Value *moduleObj = builder.CreateLoad(ptrTy, modulePtr);
430 Value *functionName = getOrCreateFunctionName(moduleName, op.getKernelName());
431 Value *moduleFunction =
432 builder.CreateCall(getModuleFunctionFn(), {moduleObj, functionName});
436 Value *stream =
nullptr;
438 llvm::scope_exit destroyStream([&]() {
439 builder.CreateCall(getStreamSyncFn(), {stream});
440 builder.CreateCall(getStreamDestroyFn(), {stream});
442 if (mlir::Value asyncObject = op.getAsyncObject()) {
443 stream = llvmValue(asyncObject);
444 destroyStream.release();
446 stream = builder.CreateCall(getStreamCreateFn(), {});
449 llvm::Constant *paramsCount =
450 llvm::ConstantInt::get(i64Ty, op.getNumKernelOperands());
453 Value *nullPtr = ConstantPointerNull::get(ptrTy);
456 if (op.hasClusterSize()) {
457 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
458 Value *cx = llvmValue(cluster.
x), *cy = llvmValue(cluster.
y),
459 *cz = llvmValue(cluster.
z);
461 getClusterKernelLaunchFn(),
462 ArrayRef<Value *>({moduleFunction, cx, cy, cz, gx, gy, gz, bx, by, bz,
463 dynamicMemorySize, stream, argArray, nullPtr}));
465 builder.CreateCall(getKernelLaunchFn(),
466 ArrayRef<Value *>({moduleFunction, gx, gy, gz, bx, by,
467 bz, dynamicMemorySize, stream,
468 argArray, nullPtr, paramsCount}));
477 SelectObjectAttr::attachInterface<SelectObjectAttrImpl>(*ctx);
static Twine getModuleIdentifier(StringRef moduleName)
static void launchKernel(sycl::queue *queue, sycl::kernel *kernel, size_t gridX, size_t gridY, size_t gridZ, size_t blockX, size_t blockY, size_t blockZ, size_t sharedMemBytes, void **params, size_t paramsCount)
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
MLIRContext is the top-level object for a collection of MLIR operations.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
static LogicalResult embedBinaryImpl(StringRef moduleName, gpu::ObjectAttr object, Module &module)
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
constexpr StringLiteral elfSectionName
void registerOffloadingLLVMTranslationInterfaceExternalModels(mlir::DialectRegistry ®istry)
Registers the offloading LLVM translation interfaces for gpu.select_object.
Include the generated interface declarations.
@ Constant
Constant integer.