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 
14 #include "../PassDetail.h"
15 #include "mlir/Conversion/LLVMCommon/LoweringOptions.h"
16 #include "mlir/Conversion/LLVMCommon/Pattern.h"
17 #include "mlir/Conversion/LLVMCommon/TypeConverter.h"
18 #include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h"
19 #include "mlir/Conversion/SPIRVToLLVM/SPIRVToLLVM.h"
20 #include "mlir/Conversion/SPIRVToLLVM/SPIRVToLLVMPass.h"
21 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
22 #include "mlir/Dialect/GPU/GPUDialect.h"
23 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
24 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
25 #include "mlir/Dialect/StandardOps/IR/Ops.h"
26 #include "mlir/IR/BuiltinOps.h"
27 #include "mlir/IR/SymbolTable.h"
28 #include "mlir/Transforms/DialectConversion.h"
29 
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/FormatVariadic.h"
33 
34 using namespace mlir;
35 
36 static constexpr const char kSPIRVModule[] = "__spv__";
37 
38 //===----------------------------------------------------------------------===//
39 // Utility functions
40 //===----------------------------------------------------------------------===//
41 
42 /// Returns the string name of the `DescriptorSet` decoration.
43 static std::string descriptorSetName() {
44   return llvm::convertToSnakeFromCamelCase(
45       stringifyDecoration(spirv::Decoration::DescriptorSet));
46 }
47 
48 /// Returns the string name of the `Binding` decoration.
49 static std::string bindingName() {
50   return llvm::convertToSnakeFromCamelCase(
51       stringifyDecoration(spirv::Decoration::Binding));
52 }
53 
54 /// Calculates the index of the kernel's operand that is represented by the
55 /// given global variable with the `bind` attribute. We assume that the index of
56 /// each kernel's operand is mapped to (descriptorSet, binding) by the map:
57 ///   i -> (0, i)
58 /// which is implemented under `LowerABIAttributesPass`.
59 static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op) {
60   IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
61   return binding.getInt();
62 }
63 
64 /// Copies the given number of bytes from src to dst pointers.
65 static void copy(Location loc, Value dst, Value src, Value size,
66                  OpBuilder &builder) {
67   MLIRContext *context = builder.getContext();
68   auto llvmI1Type = IntegerType::get(context, 1);
69   Value isVolatile = builder.create<LLVM::ConstantOp>(
70       loc, llvmI1Type, builder.getBoolAttr(false));
71   builder.create<LLVM::MemcpyOp>(loc, dst, src, size, isVolatile);
72 }
73 
74 /// Encodes the binding and descriptor set numbers into a new symbolic name.
75 /// The name is specified by
76 ///   {kernel_module_name}_{variable_name}_descriptor_set{ds}_binding{b}
77 /// to avoid symbolic conflicts, where 'ds' and 'b' are descriptor set and
78 /// binding numbers.
79 static std::string
80 createGlobalVariableWithBindName(spirv::GlobalVariableOp op,
81                                  StringRef kernelModuleName) {
82   IntegerAttr descriptorSet =
83       op->getAttrOfType<IntegerAttr>(descriptorSetName());
84   IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
85   return llvm::formatv("{0}_{1}_descriptor_set{2}_binding{3}",
86                        kernelModuleName.str(), op.sym_name().str(),
87                        std::to_string(descriptorSet.getInt()),
88                        std::to_string(binding.getInt()));
89 }
90 
91 /// Returns true if the given global variable has both a descriptor set number
92 /// and a binding number.
93 static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op) {
94   IntegerAttr descriptorSet =
95       op->getAttrOfType<IntegerAttr>(descriptorSetName());
96   IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
97   return descriptorSet && binding;
98 }
99 
100 /// Fills `globalVariableMap` with SPIR-V global variables that represent kernel
101 /// arguments from the given SPIR-V module. We assume that the module contains a
102 /// single entry point function. Hence, all `spv.GlobalVariable`s with a bind
103 /// attribute are kernel arguments.
104 static LogicalResult getKernelGlobalVariables(
105     spirv::ModuleOp module,
106     DenseMap<uint32_t, spirv::GlobalVariableOp> &globalVariableMap) {
107   auto entryPoints = module.getOps<spirv::EntryPointOp>();
108   if (!llvm::hasSingleElement(entryPoints)) {
109     return module.emitError(
110         "The module must contain exactly one entry point function");
111   }
112   auto globalVariables = module.getOps<spirv::GlobalVariableOp>();
113   for (auto globalOp : globalVariables) {
114     if (hasDescriptorSetAndBinding(globalOp))
115       globalVariableMap[calculateGlobalIndex(globalOp)] = globalOp;
116   }
117   return success();
118 }
119 
120 /// Encodes the SPIR-V module's symbolic name into the name of the entry point
121 /// function.
122 static LogicalResult encodeKernelName(spirv::ModuleOp module) {
123   StringRef spvModuleName = module.sym_name().getValue();
124   // We already know that the module contains exactly one entry point function
125   // based on `getKernelGlobalVariables()` call. Update this function's name
126   // to:
127   //   {spv_module_name}_{function_name}
128   auto entryPoint = *module.getOps<spirv::EntryPointOp>().begin();
129   StringRef funcName = entryPoint.fn();
130   auto funcOp = module.lookupSymbol<spirv::FuncOp>(funcName);
131   std::string newFuncName = spvModuleName.str() + "_" + funcName.str();
132   if (failed(SymbolTable::replaceAllSymbolUses(funcOp, newFuncName, module)))
133     return failure();
134   SymbolTable::setSymbolName(funcOp, newFuncName);
135   return success();
136 }
137 
138 //===----------------------------------------------------------------------===//
139 // Conversion patterns
140 //===----------------------------------------------------------------------===//
141 
142 namespace {
143 
144 /// Structure to group information about the variables being copied.
145 struct CopyInfo {
146   Value dst;
147   Value src;
148   Value size;
149 };
150 
151 /// This pattern emulates a call to the kernel in LLVM dialect. For that, we
152 /// copy the data to the global variable (emulating device side), call the
153 /// kernel as a normal void LLVM function, and copy the data back (emulating the
154 /// host side).
155 class GPULaunchLowering : public ConvertOpToLLVMPattern<gpu::LaunchFuncOp> {
156   using ConvertOpToLLVMPattern<gpu::LaunchFuncOp>::ConvertOpToLLVMPattern;
157 
158   LogicalResult
159   matchAndRewrite(gpu::LaunchFuncOp launchOp, ArrayRef<Value> operands,
160                   ConversionPatternRewriter &rewriter) const override {
161     auto *op = launchOp.getOperation();
162     MLIRContext *context = rewriter.getContext();
163     auto module = launchOp->getParentOfType<ModuleOp>();
164 
165     // Get the SPIR-V module that represents the gpu kernel module. The module
166     // is named:
167     //   __spv__{kernel_module_name}
168     // based on GPU to SPIR-V conversion.
169     StringRef kernelModuleName = launchOp.getKernelModuleName();
170     std::string spvModuleName = kSPIRVModule + kernelModuleName.str();
171     auto spvModule = module.lookupSymbol<spirv::ModuleOp>(spvModuleName);
172     if (!spvModule) {
173       return launchOp.emitOpError("SPIR-V kernel module '")
174              << spvModuleName << "' is not found";
175     }
176 
177     // Declare kernel function in the main module so that it later can be linked
178     // with its definition from the kernel module. We know that the kernel
179     // function would have no arguments and the data is passed via global
180     // variables. The name of the kernel will be
181     //   {spv_module_name}_{kernel_function_name}
182     // to avoid symbolic name conflicts.
183     StringRef kernelFuncName = launchOp.getKernelName();
184     std::string newKernelFuncName = spvModuleName + "_" + kernelFuncName.str();
185     auto kernelFunc = module.lookupSymbol<LLVM::LLVMFuncOp>(newKernelFuncName);
186     if (!kernelFunc) {
187       OpBuilder::InsertionGuard guard(rewriter);
188       rewriter.setInsertionPointToStart(module.getBody());
189       kernelFunc = rewriter.create<LLVM::LLVMFuncOp>(
190           rewriter.getUnknownLoc(), newKernelFuncName,
191           LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(context),
192                                       ArrayRef<Type>()));
193       rewriter.setInsertionPoint(launchOp);
194     }
195 
196     // Get all global variables associated with the kernel operands.
197     DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;
198     if (failed(getKernelGlobalVariables(spvModule, globalVariableMap)))
199       return failure();
200 
201     // Traverse kernel operands that were converted to MemRefDescriptors. For
202     // each operand, create a global variable and copy data from operand to it.
203     Location loc = launchOp.getLoc();
204     SmallVector<CopyInfo, 4> copyInfo;
205     auto numKernelOperands = launchOp.getNumKernelOperands();
206     auto kernelOperands = operands.take_back(numKernelOperands);
207     for (auto operand : llvm::enumerate(kernelOperands)) {
208       // Check if the kernel's operand is a ranked memref.
209       auto memRefType = launchOp.getKernelOperand(operand.index())
210                             .getType()
211                             .dyn_cast<MemRefType>();
212       if (!memRefType)
213         return failure();
214 
215       // Calculate the size of the memref and get the pointer to the allocated
216       // buffer.
217       SmallVector<Value, 4> sizes;
218       SmallVector<Value, 4> strides;
219       Value sizeBytes;
220       getMemRefDescriptorSizes(loc, memRefType, {}, rewriter, sizes, strides,
221                                sizeBytes);
222       MemRefDescriptor descriptor(operand.value());
223       Value src = descriptor.allocatedPtr(rewriter, loc);
224 
225       // Get the global variable in the SPIR-V module that is associated with
226       // the kernel operand. Construct its new name and create a corresponding
227       // LLVM dialect global variable.
228       spirv::GlobalVariableOp spirvGlobal = globalVariableMap[operand.index()];
229       auto pointeeType =
230           spirvGlobal.type().cast<spirv::PointerType>().getPointeeType();
231       auto dstGlobalType = typeConverter->convertType(pointeeType);
232       if (!dstGlobalType)
233         return failure();
234       std::string name =
235           createGlobalVariableWithBindName(spirvGlobal, spvModuleName);
236       // Check if this variable has already been created.
237       auto dstGlobal = module.lookupSymbol<LLVM::GlobalOp>(name);
238       if (!dstGlobal) {
239         OpBuilder::InsertionGuard guard(rewriter);
240         rewriter.setInsertionPointToStart(module.getBody());
241         dstGlobal = rewriter.create<LLVM::GlobalOp>(
242             loc, dstGlobalType,
243             /*isConstant=*/false, LLVM::Linkage::Linkonce, name, Attribute(),
244             /*alignment=*/0);
245         rewriter.setInsertionPoint(launchOp);
246       }
247 
248       // Copy the data from src operand pointer to dst global variable. Save
249       // src, dst and size so that we can copy data back after emulating the
250       // kernel call.
251       Value dst = rewriter.create<LLVM::AddressOfOp>(loc, dstGlobal);
252       copy(loc, dst, src, sizeBytes, rewriter);
253 
254       CopyInfo info;
255       info.dst = dst;
256       info.src = src;
257       info.size = sizeBytes;
258       copyInfo.push_back(info);
259     }
260     // Create a call to the kernel and copy the data back.
261     rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, kernelFunc,
262                                               ArrayRef<Value>());
263     for (CopyInfo info : copyInfo)
264       copy(loc, info.src, info.dst, info.size, rewriter);
265     return success();
266   }
267 };
268 
269 class LowerHostCodeToLLVM
270     : public LowerHostCodeToLLVMBase<LowerHostCodeToLLVM> {
271 public:
272   void runOnOperation() override {
273     ModuleOp module = getOperation();
274 
275     // Erase the GPU module.
276     for (auto gpuModule :
277          llvm::make_early_inc_range(module.getOps<gpu::GPUModuleOp>()))
278       gpuModule.erase();
279 
280     // Specify options to lower Standard to LLVM and pull in the conversion
281     // patterns.
282     LowerToLLVMOptions options(module.getContext());
283     options.emitCWrappers = true;
284     auto *context = module.getContext();
285     RewritePatternSet patterns(context);
286     LLVMTypeConverter typeConverter(context, options);
287     populateMemRefToLLVMConversionPatterns(typeConverter, patterns);
288     populateStdToLLVMConversionPatterns(typeConverter, patterns);
289     patterns.add<GPULaunchLowering>(typeConverter);
290 
291     // Pull in SPIR-V type conversion patterns to convert SPIR-V global
292     // variable's type to LLVM dialect type.
293     populateSPIRVToLLVMTypeConversion(typeConverter);
294 
295     ConversionTarget target(*context);
296     target.addLegalDialect<LLVM::LLVMDialect>();
297     if (failed(applyPartialConversion(module, target, std::move(patterns))))
298       signalPassFailure();
299 
300     // Finally, modify the kernel function in SPIR-V modules to avoid symbolic
301     // conflicts.
302     for (auto spvModule : module.getOps<spirv::ModuleOp>())
303       (void)encodeKernelName(spvModule);
304   }
305 };
306 } // namespace
307 
308 std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
309 mlir::createLowerHostCodeToLLVMPass() {
310   return std::make_unique<LowerHostCodeToLLVM>();
311 }
312