21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Transforms/Utils/ModuleUtils.h"
33class SelectObjectAttrImpl
34 :
public gpu::OffloadingLLVMTranslationAttrInterface::FallbackModel<
35 SelectObjectAttrImpl> {
37 gpu::ObjectAttr getSelectedObject(gpu::BinaryOp op)
const;
43 LogicalResult embedBinary(Attribute attribute, Operation *operation,
44 llvm::IRBuilderBase &builder,
45 LLVM::ModuleTranslation &moduleTranslation)
const;
50 Operation *launchFuncOperation,
51 Operation *binaryOperation,
52 llvm::IRBuilderBase &builder,
53 LLVM::ModuleTranslation &moduleTranslation)
const;
58SelectObjectAttrImpl::getSelectedObject(gpu::BinaryOp op)
const {
59 ArrayRef<Attribute> objects = op.getObjectsAttr().getValue();
64 cast<gpu::SelectObjectAttr>(op.getOffloadingHandlerAttr())
68 if (
auto indexAttr = mlir::dyn_cast<IntegerAttr>(
target)) {
69 index = indexAttr.getInt();
71 for (
auto [i, attr] : llvm::enumerate(objects)) {
72 auto obj = mlir::dyn_cast<gpu::ObjectAttr>(attr);
73 if (obj.getTarget() ==
target) {
84 if (index < 0 || index >=
static_cast<int64_t
>(objects.size())) {
85 op->emitError(
"the requested target object couldn't be found");
88 return mlir::dyn_cast<gpu::ObjectAttr>(objects[index]);
92 return moduleName +
"_module";
97 gpu::ObjectAttr
object, Module &module) {
102 bool addNull = (
object.getFormat() == gpu::CompilationTarget::Assembly);
103 StringRef serializedStr =
object.getObject().getValue();
105 ConstantDataArray::getString(module.getContext(), serializedStr, addNull);
106 GlobalVariable *serializedObj =
107 new GlobalVariable(module, serializedCst->getType(),
true,
108 GlobalValue::LinkageTypes::InternalLinkage,
109 serializedCst, moduleName +
"_binary");
110 serializedObj->setAlignment(MaybeAlign(8));
111 serializedObj->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
114 auto optLevel = APInt::getZero(32);
116 if (DictionaryAttr objectProps =
object.getProperties()) {
117 if (
auto section = dyn_cast_or_null<StringAttr>(
119 serializedObj->setSection(section.getValue());
122 if (
auto optAttr = dyn_cast_or_null<IntegerAttr>(objectProps.get(
"O")))
123 optLevel = optAttr.getValue();
126 IRBuilder<> builder(module.getContext());
127 auto i32Ty = builder.getInt32Ty();
128 auto i64Ty = builder.getInt64Ty();
129 auto ptrTy = builder.getPtrTy(0);
130 auto voidTy = builder.getVoidTy();
133 auto *modulePtr =
new GlobalVariable(
134 module, ptrTy,
false, GlobalValue::InternalLinkage,
135 ConstantPointerNull::get(ptrTy),
138 auto *loadFn = Function::Create(FunctionType::get(voidTy,
false),
139 GlobalValue::InternalLinkage,
140 moduleName +
"_load", module);
141 loadFn->setSection(
".text.startup");
142 auto *loadBlock = BasicBlock::Create(module.getContext(),
"entry", loadFn);
143 builder.SetInsertPoint(loadBlock);
144 Value *moduleObj = [&] {
145 if (
object.getFormat() == gpu::CompilationTarget::Assembly) {
146 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
147 "mgpuModuleLoadJIT", FunctionType::get(ptrTy, {ptrTy, i32Ty}, false));
148 Constant *optValue = ConstantInt::get(i32Ty, optLevel);
149 return builder.CreateCall(moduleLoadFn, {serializedObj, optValue});
151 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
152 "mgpuModuleLoad", FunctionType::get(ptrTy, {ptrTy, i64Ty}, false));
154 ConstantInt::get(i64Ty, serializedStr.size() + (addNull ? 1 : 0));
155 return builder.CreateCall(moduleLoadFn, {serializedObj, binarySize});
157 builder.CreateStore(moduleObj, modulePtr);
158 builder.CreateRetVoid();
159 appendToGlobalCtors(module, loadFn, 123);
161 auto *unloadFn = Function::Create(
162 FunctionType::get(voidTy,
false),
163 GlobalValue::InternalLinkage, moduleName +
"_unload", module);
164 unloadFn->setSection(
".text.startup");
166 BasicBlock::Create(module.getContext(),
"entry", unloadFn);
167 builder.SetInsertPoint(unloadBlock);
168 FunctionCallee moduleUnloadFn =
module.getOrInsertFunction(
169 "mgpuModuleUnload", FunctionType::get(voidTy, ptrTy, false));
170 builder.CreateCall(moduleUnloadFn, builder.CreateLoad(ptrTy, modulePtr));
171 builder.CreateRetVoid();
172 appendToGlobalDtors(module, unloadFn, 123);
178LogicalResult SelectObjectAttrImpl::embedBinary(
179 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
180 LLVM::ModuleTranslation &moduleTranslation)
const {
181 assert(operation &&
"The binary operation must be non null.");
185 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
187 operation->
emitError(
"operation must be a GPU binary");
191 gpu::ObjectAttr
object = getSelectedObject(op);
203 LaunchKernel(Module &module, IRBuilderBase &builder,
204 mlir::LLVM::ModuleTranslation &moduleTranslation);
206 FunctionCallee getKernelLaunchFn();
209 FunctionCallee getClusterKernelLaunchFn();
212 FunctionCallee getModuleFunctionFn();
215 FunctionCallee getStreamCreateFn();
218 FunctionCallee getStreamDestroyFn();
221 FunctionCallee getStreamSyncFn();
224 Value *getOrCreateFunctionName(StringRef moduleName, StringRef kernelName);
227 Value *createKernelArgArray(mlir::gpu::LaunchFuncOp op);
230 llvm::LogicalResult createKernelLaunch(mlir::gpu::LaunchFuncOp op,
231 mlir::gpu::ObjectAttr
object);
235 IRBuilderBase &builder;
236 mlir::LLVM::ModuleTranslation &moduleTranslation;
241 PointerType *ptrTy{};
246LogicalResult SelectObjectAttrImpl::launchKernel(
247 Attribute attribute, Operation *launchFuncOperation,
248 Operation *binaryOperation, llvm::IRBuilderBase &builder,
249 LLVM::ModuleTranslation &moduleTranslation)
const {
251 assert(launchFuncOperation &&
"The launch func operation must be non null.");
252 if (!launchFuncOperation)
255 auto launchFuncOp = mlir::dyn_cast<gpu::LaunchFuncOp>(launchFuncOperation);
257 launchFuncOperation->
emitError(
"operation must be a GPU launch func Op.");
261 auto binOp = mlir::dyn_cast<gpu::BinaryOp>(binaryOperation);
263 binaryOperation->
emitError(
"operation must be a GPU binary.");
266 gpu::ObjectAttr
object = getSelectedObject(binOp);
270 return llvm::LaunchKernel(*moduleTranslation.
getLLVMModule(), builder,
272 .createKernelLaunch(launchFuncOp,
object);
275llvm::LaunchKernel::LaunchKernel(
276 Module &module, IRBuilderBase &builder,
277 mlir::LLVM::ModuleTranslation &moduleTranslation)
278 : module(module), builder(builder), moduleTranslation(moduleTranslation) {
279 i32Ty = builder.getInt32Ty();
280 i64Ty = builder.getInt64Ty();
281 ptrTy = builder.getPtrTy(0);
282 voidTy = builder.getVoidTy();
283 intPtrTy = builder.getIntPtrTy(module.getDataLayout());
286llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchFn() {
287 return module.getOrInsertFunction(
289 FunctionType::get(voidTy,
290 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy,
291 intPtrTy, intPtrTy, intPtrTy, i32Ty,
292 ptrTy, ptrTy, ptrTy, i64Ty}),
296llvm::FunctionCallee llvm::LaunchKernel::getClusterKernelLaunchFn() {
297 return module.getOrInsertFunction(
298 "mgpuLaunchClusterKernel",
301 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
302 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
303 i32Ty, ptrTy, ptrTy, ptrTy}),
307llvm::FunctionCallee llvm::LaunchKernel::getModuleFunctionFn() {
308 return module.getOrInsertFunction(
309 "mgpuModuleGetFunction",
310 FunctionType::get(ptrTy, ArrayRef<Type *>({ptrTy, ptrTy}), false));
313llvm::FunctionCallee llvm::LaunchKernel::getStreamCreateFn() {
314 return module.getOrInsertFunction("mgpuStreamCreate",
315 FunctionType::get(ptrTy, false));
318llvm::FunctionCallee llvm::LaunchKernel::getStreamDestroyFn() {
319 return module.getOrInsertFunction(
321 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
324llvm::FunctionCallee llvm::LaunchKernel::getStreamSyncFn() {
325 return module.getOrInsertFunction(
326 "mgpuStreamSynchronize",
327 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
332llvm::Value *llvm::LaunchKernel::getOrCreateFunctionName(StringRef moduleName,
333 StringRef kernelName) {
334 std::string globalName =
335 std::string(formatv(
"{0}_{1}_name", moduleName, kernelName));
337 if (GlobalVariable *gv = module.getGlobalVariable(globalName,
true))
340 return builder.CreateGlobalString(kernelName, globalName);
357llvm::LaunchKernel::createKernelArgArray(mlir::gpu::LaunchFuncOp op) {
358 SmallVector<Value *> args =
360 SmallVector<Type *> structTypes(args.size(),
nullptr);
362 for (
auto [i, arg] : llvm::enumerate(args))
363 structTypes[i] = arg->getType();
365 Type *structTy = StructType::create(module.getContext(), structTypes);
366 Value *argStruct = builder.CreateAlloca(structTy, 0u);
367 Value *argArray = builder.CreateAlloca(
368 ptrTy, ConstantInt::get(intPtrTy, structTypes.size()));
371 Value *structMember = builder.CreateStructGEP(structTy, argStruct, i);
372 builder.CreateStore(arg, structMember);
373 Value *arrayMember = builder.CreateConstGEP1_32(ptrTy, argArray, i);
374 builder.CreateStore(structMember, arrayMember);
388llvm::LaunchKernel::createKernelLaunch(mlir::gpu::LaunchFuncOp op,
389 mlir::gpu::ObjectAttr
object) {
390 auto llvmValue = [&](mlir::Value value) -> Value * {
392 assert(v &&
"Value has not been translated.");
397 mlir::gpu::KernelDim3 grid = op.getGridSizeOperandValues();
398 Value *gx = llvmValue(grid.
x), *gy = llvmValue(grid.
y),
399 *gz = llvmValue(grid.
z);
402 mlir::gpu::KernelDim3 block = op.getBlockSizeOperandValues();
403 Value *bx = llvmValue(block.
x), *by = llvmValue(block.
y),
404 *bz = llvmValue(block.
z);
407 Value *dynamicMemorySize =
nullptr;
408 if (mlir::Value dynSz = op.getDynamicSharedMemorySize())
409 dynamicMemorySize = llvmValue(dynSz);
411 dynamicMemorySize = ConstantInt::get(i32Ty, 0);
414 Value *argArray = createKernelArgArray(op);
417 StringRef moduleName = op.getKernelModuleName().getValue();
419 Value *modulePtr =
module.getGlobalVariable(moduleIdentifier.str(), true);
421 return op.emitError() <<
"Couldn't find the binary: " << moduleIdentifier;
422 Value *moduleObj = builder.CreateLoad(ptrTy, modulePtr);
423 Value *functionName = getOrCreateFunctionName(moduleName, op.getKernelName());
424 Value *moduleFunction =
425 builder.CreateCall(getModuleFunctionFn(), {moduleObj, functionName});
429 Value *stream =
nullptr;
431 auto destroyStream = make_scope_exit([&]() {
432 builder.CreateCall(getStreamSyncFn(), {stream});
433 builder.CreateCall(getStreamDestroyFn(), {stream});
435 if (mlir::Value asyncObject = op.getAsyncObject()) {
436 stream = llvmValue(asyncObject);
437 destroyStream.release();
439 stream = builder.CreateCall(getStreamCreateFn(), {});
442 llvm::Constant *paramsCount =
443 llvm::ConstantInt::get(i64Ty, op.getNumKernelOperands());
446 Value *nullPtr = ConstantPointerNull::get(ptrTy);
449 if (op.hasClusterSize()) {
450 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
451 Value *cx = llvmValue(cluster.
x), *cy = llvmValue(cluster.
y),
452 *cz = llvmValue(cluster.
z);
454 getClusterKernelLaunchFn(),
455 ArrayRef<Value *>({moduleFunction, cx, cy, cz, gx, gy, gz, bx, by, bz,
456 dynamicMemorySize, stream, argArray, nullPtr}));
458 builder.CreateCall(getKernelLaunchFn(),
459 ArrayRef<Value *>({moduleFunction, gx, gy, gz, bx, by,
460 bz, dynamicMemorySize, stream,
461 argArray, nullPtr, paramsCount}));
470 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.