MLIR 24.0.0git
OpenACCToLLVMIRTranslation.cpp
Go to the documentation of this file.
1//===- OpenACCToLLVMIRTranslation.cpp - Translate OpenACC to LLVM IR ------===//
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 OpenACC to LLVM IR translation.
10//
11//===----------------------------------------------------------------------===//
12
14
22#include "mlir/IR/Operation.h"
23#include "mlir/Support/LLVM.h"
26
27#include "llvm/ADT/TypeSwitch.h"
28#include "llvm/Frontend/Offloading/Utility.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/Object/OffloadBinary.h"
34#include "llvm/Transforms/Utils/ModuleUtils.h"
35
36using namespace mlir;
37
38namespace {
39/// The extracted generic information for a target specific offload attribute.
40struct OffloadTargetInfo {
41 StringRef triple;
42 StringRef arch;
43};
44
45/// Returns the offloading information of a GPU target attribute, or
46/// `std::nullopt` if the target is not supported.
47static std::optional<OffloadTargetInfo> getOffloadTargetInfo(Attribute target) {
49 .Case([](NVVM::NVVMTargetAttr nvvm) {
50 return OffloadTargetInfo{nvvm.getTriple(), nvvm.getChip()};
51 })
52 .Case([](ROCDL::ROCDLTargetAttr rocdl) {
53 return OffloadTargetInfo{rocdl.getTriple(), rocdl.getChip()};
54 })
55 .Case([](xevm::XeVMTargetAttr xevm) {
56 return OffloadTargetInfo{xevm.getTriple(), xevm.getChip()};
57 })
58 .Default([](Attribute) { return std::nullopt; });
59}
60
61/// Implementation of the `OffloadingLLVMTranslationAttrInterface` model for
62/// `#acc.offload_packager`.
63class OffloadPackagerAttrImpl
64 : public gpu::OffloadingLLVMTranslationAttrInterface::FallbackModel<
65 OffloadPackagerAttrImpl> {
66public:
67 /// Embeds the objects of a `gpu.binary` in the host module as offloading
68 /// binaries placed in the `.llvm.offloading` section.
69 LogicalResult embedBinary(Attribute attribute, Operation *operation,
70 llvm::IRBuilderBase &builder,
71 LLVM::ModuleTranslation &moduleTranslation) const;
72
73 LogicalResult launchKernel(Attribute attribute,
74 Operation *launchFuncOperation,
75 Operation *binaryOperation,
76 llvm::IRBuilderBase &builder,
77 LLVM::ModuleTranslation &moduleTranslation) const;
78};
79} // namespace
80
81LogicalResult OffloadPackagerAttrImpl::embedBinary(
82 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
83 LLVM::ModuleTranslation &moduleTranslation) const {
84 assert(operation && "The binary operation must be non null.");
85 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
86 if (!op) {
87 operation->emitError("operation must be a GPU binary");
88 return failure();
89 }
90
91 using namespace llvm::object;
92
93 SmallVector<char> binaryData;
94 llvm::raw_svector_ostream os(binaryData);
95 for (Attribute attr : op.getObjectsAttr().getValue()) {
96 auto object = dyn_cast<gpu::ObjectAttr>(attr);
97 if (!object)
98 return op.emitError("expected a gpu.object");
99
100 // The section is chosen by the offloading binary, so a requested one would
101 // be ignored.
102 if (DictionaryAttr properties = object.getProperties())
103 if (properties.get(gpu::elfSectionName))
104 return op.emitError("the offload packager does not support custom "
105 "sections");
106
107 std::optional<OffloadTargetInfo> target =
108 getOffloadTargetInfo(object.getTarget());
109 if (!target)
110 return op.emitError("the offload packager does not support the target ")
111 << object.getTarget();
112
113 OffloadBinary::OffloadingImage image;
114 bool requiresNullTerminator = false;
115 switch (object.getFormat()) {
116 case gpu::CompilationTarget::Offload:
117 image.TheImageKind = IMG_Bitcode;
118 requiresNullTerminator = true;
119 break;
120 case gpu::CompilationTarget::Binary:
121 image.TheImageKind = IMG_Object;
122 requiresNullTerminator = false;
123 break;
124 case gpu::CompilationTarget::Assembly:
125 case gpu::CompilationTarget::Fatbin:
126 return op.emitError("the offloading linker wrapper cannot link the "
127 "assembly or fatbin formats");
128 }
129
130 StringRef serialized = object.getObject().getValue();
131 image.Image = llvm::MemoryBuffer::getMemBuffer(
132 serialized, /*BufferName=*/"", requiresNullTerminator);
133 image.TheOffloadKind = OFK_OpenACC;
134 image.StringData["arch"] = target->arch;
135 image.StringData["triple"] = target->triple;
136
137 llvm::SmallString<0> buffer = OffloadBinary::write(image);
138 if (buffer.size() % OffloadBinary::getAlignment() != 0)
139 return op.emitError("offload binary has invalid size alignment");
140 os << buffer;
141 }
142
143 llvm::Module &m = *moduleTranslation.getLLVMModule();
144 llvm::Constant *serializedCst = llvm::ConstantDataArray::getString(
145 m.getContext(), os.str(), /*AddNull=*/false);
146 auto *serializedObj =
147 new llvm::GlobalVariable(m, serializedCst->getType(), /*isConstant=*/true,
148 llvm::GlobalValue::InternalLinkage,
149 serializedCst, op.getName() + "_binary");
150 serializedObj->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
151 serializedObj->setSection(".llvm.offloading");
152 serializedObj->setAlignment(llvm::Align(OffloadBinary::getAlignment()));
153 llvm::appendToUsed(m, {serializedObj});
154 return success();
155}
156
157LogicalResult
158OffloadPackagerAttrImpl::launchKernel(Attribute, Operation *launchFuncOperation,
159 Operation *, llvm::IRBuilderBase &,
160 LLVM::ModuleTranslation &) const {
161 return launchFuncOperation->emitError("unexpected kernel launch");
162}
163
164/// Registers the host function or variable `op` as an offloading entry of kind
165/// OpenACC.
166static LogicalResult
168 llvm::Module *m = moduleTranslation.getLLVMModule();
169 llvm::GlobalValue *global = nullptr;
170 uint64_t size = 0;
171 if (auto func = dyn_cast<LLVM::LLVMFuncOp>(op)) {
172 global = moduleTranslation.lookupFunction(func.getName());
173 assert(global && "could not find the translated host symbol");
174 } else if (auto variable = dyn_cast<LLVM::GlobalOp>(op)) {
175 global = moduleTranslation.lookupGlobal(variable);
176 assert(global && "could not find the translated host symbol");
177 auto *llvmVariable = cast<llvm::GlobalVariable>(global);
178 size = m->getDataLayout().getTypeStoreSize(llvmVariable->getValueType());
179 } else {
180 return op->emitError("unsupported operation for '")
182 }
183
184 StringRef symbolName = global->getName();
185 llvm::offloading::emitOffloadingEntry(*m, llvm::object::OFK_OpenACC, global,
186 symbolName, size,
187 /*Flags=*/0, /*Data=*/0);
188 return success();
189}
190
191namespace {
192class OpenACCDialectLLVMIRTranslationInterface
193 : public LLVMTranslationDialectInterface {
194public:
195 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
196
197 LogicalResult
198 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
199 NamedAttribute attribute,
200 LLVM::ModuleTranslation &moduleTranslation) const override {
201 if (attribute.getName() == acc::getOffloadEntryAttrName())
202 return convertOffloadEntry(op, moduleTranslation);
203 return success();
204 }
205};
206} // namespace
207
209 registry.insert<acc::OpenACCDialect>();
210 registry.addExtension(+[](MLIRContext *ctx, acc::OpenACCDialect *dialect) {
211 dialect->addInterfaces<OpenACCDialectLLVMIRTranslationInterface>();
212 acc::OffloadPackagerAttr::attachInterface<OffloadPackagerAttrImpl>(*ctx);
213 });
214}
215
return success()
static LogicalResult convertOffloadEntry(Operation *op, LLVM::ModuleTranslation &moduleTranslation)
Registers the host function or variable op as an offloading entry of kind OpenACC.
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)
Attributes are known-constant values of operations.
Definition Attributes.h:25
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.
Implementation class for module translation.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
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
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
StringAttr getName() const
Return the name of the attribute.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
static constexpr StringLiteral getOffloadEntryAttrName()
Attribute on global symbols that are associated with device-side symbols of the same name.
Definition OpenACC.h:222
constexpr StringLiteral elfSectionName
Include the generated interface declarations.
void registerOpenACCDialectTranslation(DialectRegistry &registry)
Register the OpenACC dialect and the translation from it to the LLVM IR in the given registry.