MLIR 24.0.0git
ConvertLaunchFuncToLLVMCalls.cpp
Go to the documentation of this file.
1//===- ConvertLaunchFuncToLLVMCalls.cpp - MLIR GPU launch to LLVM pass ----===//
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 passes to convert `gpu.launch_func` op into a sequence
10// of LLVM calls that emulate the host and device sides.
11//
12//===----------------------------------------------------------------------===//
13
29#include "mlir/IR/BuiltinOps.h"
30#include "mlir/IR/SymbolTable.h"
31#include "mlir/Pass/Pass.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/FormatVariadic.h"
36
37namespace mlir {
38#define GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS
39#include "mlir/Conversion/Passes.h.inc"
40} // namespace mlir
41
42using namespace mlir;
43
44static constexpr const char kSPIRVModule[] = "__spv__";
45
46//===----------------------------------------------------------------------===//
47// Utility functions
48//===----------------------------------------------------------------------===//
49
50/// Calculates the index of the kernel's operand that is represented by the
51/// given global variable with the `bind` attribute. We assume that the index of
52/// each kernel's operand is mapped to (descriptorSet, binding) by the map:
53/// i -> (0, i)
54/// which is implemented under `LowerABIAttributesPass`.
55static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op) {
56 return *op.getBinding();
57}
58
59/// Copies the given number of bytes from src to dst pointers.
60static void copy(Location loc, Value dst, Value src, Value size,
61 OpBuilder &builder) {
62 LLVM::MemcpyOp::create(builder, loc, dst, src, size, /*isVolatile=*/false);
63}
64
65/// Encodes the binding and descriptor set numbers into a new symbolic name.
66/// The name is specified by
67/// {kernel_module_name}_{variable_name}_descriptor_set{ds}_binding{b}
68/// to avoid symbolic conflicts, where 'ds' and 'b' are descriptor set and
69/// binding numbers.
70static std::string
71createGlobalVariableWithBindName(spirv::GlobalVariableOp op,
72 StringRef kernelModuleName) {
73 return llvm::formatv("{0}_{1}_descriptor_set{2}_binding{3}",
74 kernelModuleName.str(), op.getSymName().str(),
75 std::to_string(*op.getDescriptorSet()),
76 std::to_string(*op.getBinding()));
77}
78
79/// Returns true if the given global variable has both a descriptor set number
80/// and a binding number.
81static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op) {
82 return op.getDescriptorSetAttr() && op.getBindingAttr();
83}
84
85/// Fills `globalVariableMap` with SPIR-V global variables that represent kernel
86/// arguments from the given SPIR-V module. We assume that the module contains a
87/// single entry point function. Hence, all `spirv.GlobalVariable`s with a bind
88/// attribute are kernel arguments.
89static LogicalResult getKernelGlobalVariables(
90 spirv::ModuleOp moduleOp,
92 auto entryPoints = moduleOp.getOps<spirv::EntryPointOp>();
93 if (!llvm::hasSingleElement(entryPoints)) {
94 return moduleOp.emitError(
95 "The module must contain exactly one entry point function");
96 }
97 auto globalVariables = moduleOp.getOps<spirv::GlobalVariableOp>();
98 for (auto globalOp : globalVariables) {
99 if (hasDescriptorSetAndBinding(globalOp))
100 globalVariableMap[calculateGlobalIndex(globalOp)] = globalOp;
101 }
102 return success();
103}
104
105/// Encodes the SPIR-V module's symbolic name into the name of the entry point
106/// function.
107static LogicalResult encodeKernelName(spirv::ModuleOp moduleOp) {
108 StringRef spvModuleName = moduleOp.getSymName().value_or(kSPIRVModule);
109 // We already know that the module contains exactly one entry point function
110 // based on `getKernelGlobalVariables()` call. Update this function's name
111 // to:
112 // {spv_module_name}_{function_name}
113 auto entryPoints = moduleOp.getOps<spirv::EntryPointOp>();
114 if (!llvm::hasSingleElement(entryPoints)) {
115 return moduleOp.emitError(
116 "The module must contain exactly one entry point function");
117 }
118 spirv::EntryPointOp entryPoint = *entryPoints.begin();
119 StringRef funcName = entryPoint.getFn();
120 auto funcOp = moduleOp.lookupSymbol<spirv::FuncOp>(entryPoint.getFnAttr());
121 StringAttr newFuncName =
122 StringAttr::get(moduleOp->getContext(), spvModuleName + "_" + funcName);
123 if (failed(SymbolTable::replaceAllSymbolUses(funcOp, newFuncName, moduleOp)))
124 return failure();
125 SymbolTable::setSymbolName(funcOp, newFuncName);
126 return success();
127}
128
129//===----------------------------------------------------------------------===//
130// Conversion patterns
131//===----------------------------------------------------------------------===//
132
133namespace {
134
135/// Structure to group information about the variables being copied.
136struct CopyInfo {
137 Value dst;
138 Value src;
139 Value size;
140};
141
142/// This pattern emulates a call to the kernel in LLVM dialect. For that, we
143/// copy the data to the global variable (emulating device side), call the
144/// kernel as a normal void LLVM function, and copy the data back (emulating the
145/// host side).
146class GPULaunchLowering : public ConvertOpToLLVMPattern<gpu::LaunchFuncOp> {
147 using ConvertOpToLLVMPattern<gpu::LaunchFuncOp>::ConvertOpToLLVMPattern;
148
149 LogicalResult
150 matchAndRewrite(gpu::LaunchFuncOp launchOp, OpAdaptor adaptor,
151 ConversionPatternRewriter &rewriter) const override {
152 auto *op = launchOp.getOperation();
153 MLIRContext *context = rewriter.getContext();
154 auto moduleOp = launchOp->getParentOfType<ModuleOp>();
155
156 // Get the SPIR-V module that represents the gpu kernel module. The module
157 // is named:
158 // __spv__{kernel_module_name}
159 // based on GPU to SPIR-V conversion.
160 StringRef kernelModuleName = launchOp.getKernelModuleName().getValue();
161 std::string spvModuleName = kSPIRVModule + kernelModuleName.str();
162 auto spvModule = moduleOp.lookupSymbol<spirv::ModuleOp>(
163 StringAttr::get(context, spvModuleName));
164 if (!spvModule) {
165 return launchOp.emitOpError("SPIR-V kernel module '")
166 << spvModuleName << "' is not found";
167 }
168
169 // Declare kernel function in the main module so that it later can be linked
170 // with its definition from the kernel module. We know that the kernel
171 // function would have no arguments and the data is passed via global
172 // variables. The name of the kernel will be
173 // {spv_module_name}_{kernel_function_name}
174 // to avoid symbolic name conflicts.
175 StringRef kernelFuncName = launchOp.getKernelName().getValue();
176 std::string newKernelFuncName = spvModuleName + "_" + kernelFuncName.str();
177 auto kernelFunc = moduleOp.lookupSymbol<LLVM::LLVMFuncOp>(
178 StringAttr::get(context, newKernelFuncName));
179 if (!kernelFunc) {
180 OpBuilder::InsertionGuard guard(rewriter);
181 rewriter.setInsertionPointToStart(moduleOp.getBody());
182 kernelFunc = LLVM::LLVMFuncOp::create(
183 rewriter, rewriter.getUnknownLoc(), newKernelFuncName,
184 LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(context),
185 ArrayRef<Type>()));
186 rewriter.setInsertionPoint(launchOp);
187 }
188
189 // Get all global variables associated with the kernel operands.
190 DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;
191 if (failed(getKernelGlobalVariables(spvModule, globalVariableMap)))
192 return failure();
193
194 // Traverse kernel operands that were converted to MemRefDescriptors. For
195 // each operand, create a global variable and copy data from operand to it.
196 Location loc = launchOp.getLoc();
197 SmallVector<CopyInfo, 4> copyInfo;
198 auto numKernelOperands = launchOp.getNumKernelOperands();
199 auto kernelOperands = adaptor.getOperands().take_back(numKernelOperands);
200 for (const auto &operand : llvm::enumerate(kernelOperands)) {
201 // Check if the kernel's operand is a ranked memref.
202 auto memRefType = dyn_cast<MemRefType>(
203 launchOp.getKernelOperand(operand.index()).getType());
204 if (!memRefType)
205 return failure();
206
207 // Calculate the size of the memref and get the pointer to the allocated
208 // buffer.
209 SmallVector<Value, 4> sizes;
210 SmallVector<Value, 4> strides;
211 Value sizeBytes;
212 getMemRefDescriptorSizes(loc, memRefType, {}, rewriter, sizes, strides,
213 sizeBytes);
214 MemRefDescriptor descriptor(operand.value());
215 Value src = descriptor.allocatedPtr(rewriter, loc);
216
217 // Get the global variable in the SPIR-V module that is associated with
218 // the kernel operand. Construct its new name and create a corresponding
219 // LLVM dialect global variable.
220 spirv::GlobalVariableOp spirvGlobal = globalVariableMap[operand.index()];
221 auto ptrType = dyn_cast<spirv::PointerType>(spirvGlobal.getType());
222 if (!ptrType)
223 return failure();
224 auto dstGlobalType = typeConverter->convertType(ptrType.getPointeeType());
225 if (!dstGlobalType)
226 return failure();
227 std::string name =
228 createGlobalVariableWithBindName(spirvGlobal, spvModuleName);
229 // Check if this variable has already been created.
230 auto dstGlobal = moduleOp.lookupSymbol<LLVM::GlobalOp>(name);
231 if (!dstGlobal) {
232 OpBuilder::InsertionGuard guard(rewriter);
233 rewriter.setInsertionPointToStart(moduleOp.getBody());
234 dstGlobal = LLVM::GlobalOp::create(
235 rewriter, loc, dstGlobalType,
236 /*isConstant=*/false, LLVM::Linkage::Linkonce, name, Attribute(),
237 /*alignment=*/0);
238 rewriter.setInsertionPoint(launchOp);
239 }
240
241 // Copy the data from src operand pointer to dst global variable. Save
242 // src, dst and size so that we can copy data back after emulating the
243 // kernel call.
244 Value dst = LLVM::AddressOfOp::create(
245 rewriter, loc, typeConverter->convertType(spirvGlobal.getType()),
246 dstGlobal.getSymName());
247 copy(loc, dst, src, sizeBytes, rewriter);
248
249 CopyInfo info;
250 info.dst = dst;
251 info.src = src;
252 info.size = sizeBytes;
253 copyInfo.push_back(info);
254 }
255 // Create a call to the kernel and copy the data back.
256 rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, kernelFunc,
257 ArrayRef<Value>());
258 for (CopyInfo info : copyInfo)
259 copy(loc, info.src, info.dst, info.size, rewriter);
260 return success();
261 }
262};
263
264class LowerHostCodeToLLVM
265 : public impl::LowerHostCodeToLLVMPassBase<LowerHostCodeToLLVM> {
266public:
267 using Base::Base;
268
269 void runOnOperation() override {
270 ModuleOp moduleOp = getOperation();
271
272 // Erase the GPU module.
273 for (auto gpuModule :
274 llvm::make_early_inc_range(moduleOp.getOps<gpu::GPUModuleOp>()))
275 gpuModule.erase();
276
277 // Request C wrapper emission.
278 for (auto func : moduleOp.getOps<func::FuncOp>()) {
279 func->setDiscardableAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
280 UnitAttr::get(&getContext()));
281 }
282
283 // Specify options to lower to LLVM and pull in the conversion patterns.
284 LowerToLLVMOptions options(moduleOp.getContext());
285
286 auto *context = moduleOp.getContext();
287 RewritePatternSet patterns(context);
288 LLVMTypeConverter typeConverter(context, options);
290 populateFinalizeMemRefToLLVMConversionPatterns(typeConverter, patterns);
291 populateFuncToLLVMConversionPatterns(typeConverter, patterns);
292 patterns.add<GPULaunchLowering>(typeConverter);
293
294 // Pull in SPIR-V type conversion patterns to convert SPIR-V global
295 // variable's type to LLVM dialect type.
297
298 ConversionTarget target(*context);
299 target.addLegalDialect<LLVM::LLVMDialect>();
300 if (failed(applyPartialConversion(moduleOp, target, std::move(patterns))))
301 signalPassFailure();
302
303 // Finally, modify the kernel function in SPIR-V modules to avoid symbolic
304 // conflicts.
305 for (auto spvModule : moduleOp.getOps<spirv::ModuleOp>()) {
306 if (failed(encodeKernelName(spvModule))) {
307 signalPassFailure();
308 return;
309 }
310 }
311 }
312};
313} // namespace
return success()
static LogicalResult getKernelGlobalVariables(spirv::ModuleOp moduleOp, DenseMap< uint32_t, spirv::GlobalVariableOp > &globalVariableMap)
Fills globalVariableMap with SPIR-V global variables that represent kernel arguments from the given S...
static LogicalResult encodeKernelName(spirv::ModuleOp moduleOp)
Encodes the SPIR-V module's symbolic name into the name of the entry point function.
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static constexpr const char kSPIRVModule[]
static std::string createGlobalVariableWithBindName(spirv::GlobalVariableOp op, StringRef kernelModuleName)
Encodes the binding and descriptor set numbers into a new symbolic name.
static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op)
Calculates the index of the kernel's operand that is represented by the given global variable with th...
static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op)
Returns true if the given global variable has both a descriptor set number and a binding number.
static constexpr const char kSPIRVModule[]
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition Pattern.h:233
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
static LogicalResult replaceAllSymbolUses(StringAttr oldSymbol, StringAttr newSymbol, Operation *from)
Attempt to replace all uses of the given symbol 'oldSymbol' with the provided symbol 'newSymbol' that...
static void setSymbolName(Operation *symbol, StringAttr name)
Sets the name of the given symbol operation.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void populateArithToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
void populateSPIRVToLLVMTypeConversion(LLVMTypeConverter &typeConverter, spirv::ClientAPI clientAPIForAddressSpaceMapping=spirv::ClientAPI::Unknown)
Populates type conversions with additional SPIR-V types.
void populateFuncToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect the patterns to convert from the Func dialect to LLVM.
void populateFinalizeMemRefToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect a set of patterns to convert memory-related operations from the MemRef dialect to the LLVM di...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123