MLIR 24.0.0git
SelectObjectAttr.cpp
Go to the documentation of this file.
1//===- ObjectHandler.cpp - Implements base ObjectManager attributes -------===//
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//
9// This file implements the `OffloadingLLVMTranslationAttrInterface` for the
10// `SelectObject` attribute.
11//
12//===----------------------------------------------------------------------===//
13
19
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"
27
28using namespace mlir;
29
30namespace {
31// Implementation of the `OffloadingLLVMTranslationAttrInterface` model.
32class SelectObjectAttrImpl
33 : public gpu::OffloadingLLVMTranslationAttrInterface::FallbackModel<
34 SelectObjectAttrImpl> {
35 // Returns the selected object for embedding.
36 gpu::ObjectAttr getSelectedObject(gpu::BinaryOp op) const;
37
38public:
39 // Translates a `gpu.binary`, embedding the binary into a host LLVM module as
40 // global binary string which gets loaded/unloaded into a global module
41 // object through a global ctor/dtor.
42 LogicalResult embedBinary(Attribute attribute, Operation *operation,
43 llvm::IRBuilderBase &builder,
44 LLVM::ModuleTranslation &moduleTranslation) const;
45
46 // Translates a `gpu.launch_func` to a sequence of LLVM instructions resulting
47 // in a kernel launch call.
48 LogicalResult launchKernel(Attribute attribute,
49 Operation *launchFuncOperation,
50 Operation *binaryOperation,
51 llvm::IRBuilderBase &builder,
52 LLVM::ModuleTranslation &moduleTranslation) const;
53};
54} // namespace
55
56gpu::ObjectAttr
57SelectObjectAttrImpl::getSelectedObject(gpu::BinaryOp op) const {
58 ArrayRef<Attribute> objects = op.getObjectsAttr().getValue();
59
60 // Obtain the index of the object to select.
61 int64_t index = -1;
62 if (Attribute target =
63 cast<gpu::SelectObjectAttr>(op.getOffloadingHandlerAttr())
64 .getTarget()) {
65 // If the target attribute is a number it is the index. Otherwise compare
66 // the attribute to every target inside the object array to find the index.
67 if (auto indexAttr = mlir::dyn_cast<IntegerAttr>(target)) {
68 index = indexAttr.getInt();
69 } else {
70 for (auto [i, attr] : llvm::enumerate(objects)) {
71 auto obj = mlir::dyn_cast<gpu::ObjectAttr>(attr);
72 if (obj.getTarget() == target) {
73 index = i;
74 }
75 }
76 }
77 } else {
78 // If the target attribute is null then it's selecting the first object in
79 // the object array.
80 index = 0;
81 }
82
83 if (index < 0 || index >= static_cast<int64_t>(objects.size())) {
84 op->emitError("the requested target object couldn't be found");
85 return nullptr;
86 }
87 return mlir::dyn_cast<gpu::ObjectAttr>(objects[index]);
88}
89
90static Twine getModuleIdentifier(StringRef moduleName) {
91 return moduleName + "_module";
92}
93
94namespace llvm {
95static LogicalResult embedBinaryImpl(StringRef moduleName,
96 gpu::ObjectAttr object, int priority,
97 Module &module) {
98
99 // Embed the object as a global string.
100 // Add null for assembly output for JIT paths that expect null-terminated
101 // strings.
102 bool addNull = (object.getFormat() == gpu::CompilationTarget::Assembly);
103 StringRef serializedStr = object.getObject().getValue();
104 Constant *serializedCst =
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);
112
113 // Default JIT optimization level.
114 auto optLevel = APInt::getZero(32);
115
116 if (DictionaryAttr objectProps = object.getProperties()) {
117 if (auto section = dyn_cast_or_null<StringAttr>(
118 objectProps.get(gpu::elfSectionName))) {
119 serializedObj->setSection(section.getValue());
120 }
121 // Check if there's an optimization level embedded in the object.
122 if (auto optAttr = dyn_cast_or_null<IntegerAttr>(objectProps.get("O")))
123 optLevel = optAttr.getValue();
124 }
125
126 IRBuilder<> builder(module);
127 auto *i32Ty = builder.getInt32Ty();
128 auto *i64Ty = builder.getInt64Ty();
129 auto *ptrTy = builder.getPtrTy(0);
130 auto *voidTy = builder.getVoidTy();
131
132 // Embed the module as a global object.
133 auto *modulePtr = new GlobalVariable(
134 module, ptrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
135 /*Initializer=*/ConstantPointerNull::get(ptrTy),
136 getModuleIdentifier(moduleName));
137
138 auto *loadFn = Function::Create(FunctionType::get(voidTy, /*IsVarArg=*/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 Constant *binarySize =
146 ConstantInt::get(i64Ty, serializedStr.size() + (addNull ? 1 : 0));
147 if (object.getFormat() == gpu::CompilationTarget::Assembly) {
148 FunctionCallee moduleLoadFn = module.getOrInsertFunction(
149 "mgpuModuleLoadJIT", FunctionType::get(ptrTy,
150 {
151 ptrTy,
152 i32Ty,
153 i64Ty,
154 },
155 false));
156
157 Constant *optValue = ConstantInt::get(i32Ty, optLevel);
158 return builder.CreateCall(moduleLoadFn,
159 {serializedObj, optValue, binarySize});
160 }
161 FunctionCallee moduleLoadFn = module.getOrInsertFunction(
162 "mgpuModuleLoad", FunctionType::get(ptrTy, {ptrTy, i64Ty}, false));
163 return builder.CreateCall(moduleLoadFn, {serializedObj, binarySize});
164 }();
165 builder.CreateStore(moduleObj, modulePtr);
166 builder.CreateRetVoid();
167 appendToGlobalCtors(module, loadFn, priority);
168
169 auto *unloadFn = Function::Create(
170 FunctionType::get(voidTy, /*IsVarArg=*/false),
171 GlobalValue::InternalLinkage, moduleName + "_unload", module);
172 unloadFn->setSection(".text.startup");
173 auto *unloadBlock =
174 BasicBlock::Create(module.getContext(), "entry", unloadFn);
175 builder.SetInsertPoint(unloadBlock);
176 FunctionCallee moduleUnloadFn = module.getOrInsertFunction(
177 "mgpuModuleUnload", FunctionType::get(voidTy, ptrTy, false));
178 builder.CreateCall(moduleUnloadFn, builder.CreateLoad(ptrTy, modulePtr));
179 builder.CreateRetVoid();
180 appendToGlobalDtors(module, unloadFn, priority);
181
182 return success();
183}
184} // namespace llvm
185
186LogicalResult SelectObjectAttrImpl::embedBinary(
187 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
188 LLVM::ModuleTranslation &moduleTranslation) const {
189 assert(operation && "The binary operation must be non null.");
190 if (!operation)
191 return failure();
192
193 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
194 if (!op) {
195 operation->emitError("operation must be a GPU binary");
196 return failure();
197 }
198
199 gpu::ObjectAttr object = getSelectedObject(op);
200 if (!object)
201 return failure();
202
203 uint16_t priority = cast<gpu::SelectObjectAttr>(attribute).getPriority();
204 return embedBinaryImpl(op.getName(), object, priority,
205 *moduleTranslation.getLLVMModule());
206}
207
208namespace llvm {
209namespace {
210class LaunchKernel {
211public:
212 LaunchKernel(Module &module, IRBuilderBase &builder,
213 mlir::LLVM::ModuleTranslation &moduleTranslation);
214 // Get the kernel launch callee.
215 FunctionCallee getKernelLaunchFn();
216
217 // Get the kernel launch callee.
218 FunctionCallee getClusterKernelLaunchFn();
219
220 // Get the cooperative kernel launch callee.
221 FunctionCallee getKernelLaunchCooperativeFn();
222
223 // Get the module function callee.
224 FunctionCallee getModuleFunctionFn();
225
226 // Get the stream create callee.
227 FunctionCallee getStreamCreateFn();
228
229 // Get the stream destroy callee.
230 FunctionCallee getStreamDestroyFn();
231
232 // Get the stream sync callee.
233 FunctionCallee getStreamSyncFn();
234
235 // Ger or create the function name global string.
236 Value *getOrCreateFunctionName(StringRef moduleName, StringRef kernelName);
237
238 // Create the void* kernel array for passing the arguments.
239 Value *createKernelArgArray(mlir::gpu::LaunchFuncOp op);
240
241 // Create the full kernel launch.
242 llvm::LogicalResult createKernelLaunch(mlir::gpu::LaunchFuncOp op,
243 mlir::gpu::ObjectAttr object);
244
245private:
246 Module &module;
247 IRBuilderBase &builder;
248 mlir::LLVM::ModuleTranslation &moduleTranslation;
249 Type *i32Ty{};
250 Type *i64Ty{};
251 Type *voidTy{};
252 Type *intPtrTy{};
253 PointerType *ptrTy{};
254};
255} // namespace
256} // namespace llvm
257
258LogicalResult SelectObjectAttrImpl::launchKernel(
259 Attribute attribute, Operation *launchFuncOperation,
260 Operation *binaryOperation, llvm::IRBuilderBase &builder,
261 LLVM::ModuleTranslation &moduleTranslation) const {
262
263 assert(launchFuncOperation && "The launch func operation must be non null.");
264 if (!launchFuncOperation)
265 return failure();
266
267 auto launchFuncOp = mlir::dyn_cast<gpu::LaunchFuncOp>(launchFuncOperation);
268 if (!launchFuncOp) {
269 launchFuncOperation->emitError("operation must be a GPU launch func Op.");
270 return failure();
271 }
272
273 auto binOp = mlir::dyn_cast<gpu::BinaryOp>(binaryOperation);
274 if (!binOp) {
275 binaryOperation->emitError("operation must be a GPU binary.");
276 return failure();
277 }
278 gpu::ObjectAttr object = getSelectedObject(binOp);
279 if (!object)
280 return failure();
281
282 return llvm::LaunchKernel(*moduleTranslation.getLLVMModule(), builder,
283 moduleTranslation)
284 .createKernelLaunch(launchFuncOp, object);
285}
286
287llvm::LaunchKernel::LaunchKernel(
288 Module &module, IRBuilderBase &builder,
289 mlir::LLVM::ModuleTranslation &moduleTranslation)
290 : module(module), builder(builder), moduleTranslation(moduleTranslation) {
291 i32Ty = builder.getInt32Ty();
292 i64Ty = builder.getInt64Ty();
293 ptrTy = builder.getPtrTy(0);
294 voidTy = builder.getVoidTy();
295 intPtrTy = builder.getIntPtrTy(module.getDataLayout());
296}
297
298llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchFn() {
299 return module.getOrInsertFunction(
300 "mgpuLaunchKernel",
301 FunctionType::get(voidTy,
302 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy,
303 intPtrTy, intPtrTy, intPtrTy, i32Ty,
304 ptrTy, ptrTy, ptrTy, i64Ty}),
305 false));
306}
307
308llvm::FunctionCallee llvm::LaunchKernel::getClusterKernelLaunchFn() {
309 return module.getOrInsertFunction(
310 "mgpuLaunchClusterKernel",
311 FunctionType::get(
312 voidTy,
313 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
314 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
315 i32Ty, ptrTy, ptrTy, ptrTy}),
316 false));
317}
318
319llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchCooperativeFn() {
320 return module.getOrInsertFunction(
321 "mgpuLaunchKernelCooperative",
322 FunctionType::get(
323 voidTy,
324 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
325 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
326 i32Ty, ptrTy, ptrTy, ptrTy}),
327 false));
328}
329
330llvm::FunctionCallee llvm::LaunchKernel::getModuleFunctionFn() {
331 return module.getOrInsertFunction(
332 "mgpuModuleGetFunction",
333 FunctionType::get(ptrTy, ArrayRef<Type *>({ptrTy, ptrTy}), false));
334}
335
336llvm::FunctionCallee llvm::LaunchKernel::getStreamCreateFn() {
337 return module.getOrInsertFunction("mgpuStreamCreate",
338 FunctionType::get(ptrTy, false));
339}
340
341llvm::FunctionCallee llvm::LaunchKernel::getStreamDestroyFn() {
342 return module.getOrInsertFunction(
343 "mgpuStreamDestroy",
344 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
345}
346
347llvm::FunctionCallee llvm::LaunchKernel::getStreamSyncFn() {
348 return module.getOrInsertFunction(
349 "mgpuStreamSynchronize",
350 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
351}
352
353// Generates an LLVM IR dialect global that contains the name of the given
354// kernel function as a C string, and returns a pointer to its beginning.
355llvm::Value *llvm::LaunchKernel::getOrCreateFunctionName(StringRef moduleName,
356 StringRef kernelName) {
357 std::string globalName =
358 std::string(formatv("{0}_{1}_name", moduleName, kernelName));
359
360 if (GlobalVariable *gv = module.getGlobalVariable(globalName, true))
361 return gv;
362
363 return builder.CreateGlobalString(kernelName, globalName);
364}
365
366// Creates a struct containing all kernel parameters on the stack and returns
367// an array of type-erased pointers to the fields of the struct. The array can
368// then be passed to the CUDA / ROCm (HIP) kernel launch calls.
369// The generated code is essentially as follows:
370//
371// %struct = alloca(sizeof(struct { Parameters... }))
372// %array = alloca(NumParameters * sizeof(void *))
373// for (i : [0, NumParameters))
374// %fieldPtr = llvm.getelementptr %struct[0, i]
375// llvm.store parameters[i], %fieldPtr
376// %elementPtr = llvm.getelementptr %array[i]
377// llvm.store %fieldPtr, %elementPtr
378// return %array
379llvm::Value *
380llvm::LaunchKernel::createKernelArgArray(mlir::gpu::LaunchFuncOp op) {
381 SmallVector<Value *> args =
382 moduleTranslation.lookupValues(op.getKernelOperands());
383 SmallVector<Type *> structTypes(args.size(), nullptr);
384
385 for (auto [i, arg] : llvm::enumerate(args))
386 structTypes[i] = arg->getType();
387
388 Type *structTy = StructType::create(module.getContext(), structTypes);
389 Value *argStruct = builder.CreateAlloca(structTy, 0u);
390 Value *argArray = builder.CreateAlloca(
391 ptrTy, ConstantInt::get(intPtrTy, structTypes.size()));
392
393 for (auto [i, arg] : enumerate(args)) {
394 Value *structMember = builder.CreateStructGEP(structTy, argStruct, i);
395 builder.CreateStore(arg, structMember);
396 Value *arrayMember = builder.CreateConstGEP1_32(ptrTy, argArray, i);
397 builder.CreateStore(structMember, arrayMember);
398 }
399 return argArray;
400}
401
402// Emits LLVM IR to launch a kernel function:
403// %0 = call @llvm.stacksave()
404// %1 = load %global_module_object
405// %2 = call @mgpuModuleGetFunction(%1, %global_kernel_name)
406// %3 = call @mgpuStreamCreate()
407// %4 = <see createKernelArgArray()>
408// call @mgpuLaunchKernel(%2, ..., %3, %4, ...)
409// call @llvm.stackrestore(%0)
410// call @mgpuStreamSynchronize(%3)
411// call @mgpuStreamDestroy(%3)
412llvm::LogicalResult
413llvm::LaunchKernel::createKernelLaunch(mlir::gpu::LaunchFuncOp op,
414 mlir::gpu::ObjectAttr object) {
415 auto llvmValue = [&](mlir::Value value) -> Value * {
416 Value *v = moduleTranslation.lookupValue(value);
417 assert(v && "Value has not been translated.");
418 return v;
419 };
420
421 // Get grid dimensions.
422 mlir::gpu::KernelDim3 grid = op.getGridSizeOperandValues();
423 Value *gx = llvmValue(grid.x), *gy = llvmValue(grid.y),
424 *gz = llvmValue(grid.z);
425
426 // Get block dimensions.
427 mlir::gpu::KernelDim3 block = op.getBlockSizeOperandValues();
428 Value *bx = llvmValue(block.x), *by = llvmValue(block.y),
429 *bz = llvmValue(block.z);
430
431 // Get dynamic shared memory size.
432 Value *dynamicMemorySize = nullptr;
433 if (mlir::Value dynSz = op.getDynamicSharedMemorySize())
434 dynamicMemorySize = llvmValue(dynSz);
435 else
436 dynamicMemorySize = ConstantInt::get(i32Ty, 0);
437
438 // Create the argument array. Its storage is allocated here, at the launch,
439 // and the stack is restored after the launch call, so that a launch in a
440 // loop does not grow the stack on every iteration.
441 Value *stack = builder.CreateStackSave();
442 Value *argArray = createKernelArgArray(op);
443
444 // Load the kernel function.
445 StringRef moduleName = op.getKernelModuleName().getValue();
446 Twine moduleIdentifier = getModuleIdentifier(moduleName);
447 Value *modulePtr = module.getGlobalVariable(moduleIdentifier.str(), true);
448 if (!modulePtr)
449 return op.emitError() << "Couldn't find the binary: " << moduleIdentifier;
450 Value *moduleObj = builder.CreateLoad(ptrTy, modulePtr);
451 Value *functionName = getOrCreateFunctionName(moduleName, op.getKernelName());
452 Value *moduleFunction =
453 builder.CreateCall(getModuleFunctionFn(), {moduleObj, functionName});
454
455 // Get the stream to use for execution. If there's no async object then create
456 // a stream to make a synchronous kernel launch.
457 Value *stream = nullptr;
458 // Sync & destroy the stream, for synchronous launches.
459 llvm::scope_exit destroyStream([&]() {
460 builder.CreateCall(getStreamSyncFn(), {stream});
461 builder.CreateCall(getStreamDestroyFn(), {stream});
462 });
463 if (mlir::Value asyncObject = op.getAsyncObject()) {
464 stream = llvmValue(asyncObject);
465 destroyStream.release();
466 } else {
467 stream = builder.CreateCall(getStreamCreateFn(), {});
468 }
469
470 llvm::Constant *paramsCount =
471 llvm::ConstantInt::get(i64Ty, op.getNumKernelOperands());
472
473 // Create the launch call.
474 Value *nullPtr = ConstantPointerNull::get(ptrTy);
475
476 // Cooperative launches go through mgpuLaunchKernelCooperative, which also
477 // handles an optional cluster. Cluster-only (non-cooperative) launches keep
478 // their existing path through mgpuLaunchClusterKernel. Plain launches go
479 // through mgpuLaunchKernel.
480 if (op.getCooperative()) {
481 Value *cx = ConstantInt::get(intPtrTy, 0);
482 Value *cy = ConstantInt::get(intPtrTy, 0);
483 Value *cz = ConstantInt::get(intPtrTy, 0);
484 if (op.hasClusterSize()) {
485 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
486 cx = llvmValue(cluster.x);
487 cy = llvmValue(cluster.y);
488 cz = llvmValue(cluster.z);
489 }
490 builder.CreateCall(
491 getKernelLaunchCooperativeFn(),
492 ArrayRef<Value *>({moduleFunction, gx, gy, gz, cx, cy, cz, bx, by, bz,
493 dynamicMemorySize, stream, argArray, nullPtr}));
494 } else if (op.hasClusterSize()) {
495 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
496 Value *cx = llvmValue(cluster.x), *cy = llvmValue(cluster.y),
497 *cz = llvmValue(cluster.z);
498 builder.CreateCall(
499 getClusterKernelLaunchFn(),
500 ArrayRef<Value *>({moduleFunction, cx, cy, cz, gx, gy, gz, bx, by, bz,
501 dynamicMemorySize, stream, argArray, nullPtr}));
502 } else {
503 builder.CreateCall(getKernelLaunchFn(),
504 ArrayRef<Value *>({moduleFunction, gx, gy, gz, bx, by,
505 bz, dynamicMemorySize, stream,
506 argArray, nullPtr, paramsCount}));
507 }
508
509 builder.CreateStackRestore(stack);
510
511 return success();
512}
513
515 DialectRegistry &registry) {
516 registry.addExtension(+[](MLIRContext *ctx, gpu::GPUDialect *dialect) {
517 SelectObjectAttr::attachInterface<SelectObjectAttrImpl>(*ctx);
518 });
519}
return success()
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.
Definition MLIRContext.h:71
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...
Definition Value.h:96
static LogicalResult embedBinaryImpl(StringRef moduleName, gpu::ObjectAttr object, int priority, Module &module)
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition Matchers.h:344
constexpr StringLiteral elfSectionName
void registerOffloadingLLVMTranslationInterfaceExternalModels(mlir::DialectRegistry &registry)
Registers the offloading LLVM translation interfaces for gpu.select_object.
Include the generated interface declarations.
@ Constant
Constant integer.
Definition AffineExpr.h:57