Skip to content

[MLIR][GPU-LLVM] Add in-pass signature update option for opencl kernels #105664

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mlir/include/mlir/Conversion/Passes.td
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,9 @@ def ConvertGpuOpsToLLVMSPVOps : Pass<"convert-gpu-to-llvm-spv", "gpu::GPUModuleO
Option<"indexBitwidth", "index-bitwidth", "unsigned",
/*default=kDeriveIndexBitwidthFromDataLayout*/"0",
"Bitwidth of the index type, 0 to use size of machine word">,
Option<"forceOpenclAddressSpaces", "force-opencl-address-spaces",
"bool", /*default=*/"false",
"Force kernel argument pointers to have address space global.">,
];
}

Expand Down
59 changes: 59 additions & 0 deletions mlir/lib/Conversion/GPUToLLVMSPV/GPUToLLVMSPV.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,51 @@ struct GPUShuffleConversion final : ConvertOpToLLVMPattern<gpu::ShuffleOp> {
}
};

class MemorySpaceToOpenCLMemorySpaceConverter : public TypeConverter {
public:
explicit MemorySpaceToOpenCLMemorySpaceConverter() {
addConversion([](Type t) { return t; });
addConversion(
[this](BaseMemRefType memRefType) -> std::optional<Type> {
std::optional<gpu::AddressSpace> addrSpace =
memorySpaceMap(memRefType.getMemorySpace());
if (!addrSpace) {
LLVM_DEBUG(
llvm::dbgs()
<< "cannot convert " << memRefType
<< " due to being unable to find address space in the map\n");
return std::nullopt;
}
auto addrSpaceAttr =
gpu::AddressSpaceAttr::get(memRefType.getContext(), *addrSpace);
if (auto rankedType = dyn_cast<MemRefType>(memRefType)) {
return MemRefType::get(memRefType.getShape(),
memRefType.getElementType(),
rankedType.getLayout(), addrSpaceAttr);
}
return UnrankedMemRefType::get(memRefType.getElementType(),
addrSpaceAttr);
});
addConversion([this](FunctionType type) {
auto inputs = llvm::map_to_vector(
type.getInputs(), [this](Type ty) { return convertType(ty); });
auto results = llvm::map_to_vector(
type.getResults(), [this](Type ty) { return convertType(ty); });
return FunctionType::get(type.getContext(), inputs, results);
});
}

private:
std::optional<gpu::AddressSpace> memorySpaceMap(Attribute memSpaceAttr) {
if (!memSpaceAttr)
return gpu::AddressSpace::Global;
auto gpuAddrSpace = dyn_cast<gpu::AddressSpaceAttr>(memSpaceAttr);
if (!gpuAddrSpace)
return std::nullopt;
return gpuAddrSpace.getValue();
}
};

//===----------------------------------------------------------------------===//
// GPU To LLVM-SPV Pass.
//===----------------------------------------------------------------------===//
Expand All @@ -325,6 +370,20 @@ struct GPUToLLVMSPVConversionPass final
LLVMTypeConverter converter(context, options);
LLVMConversionTarget target(*context);

if (forceOpenclAddressSpaces) {
MemorySpaceToOpenCLMemorySpaceConverter converter;
AttrTypeReplacer replacer;
replacer.addReplacement([&converter](BaseMemRefType origType)
-> std::optional<BaseMemRefType> {
return converter.convertType<BaseMemRefType>(origType);
});

replacer.recursivelyReplaceElementsIn(getOperation(),
/*replaceAttrs=*/true,
/*replaceLocs=*/false,
/*replaceTypes=*/true);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an overkill, isn't there another way?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried a natural way - putting additional conversion to the llvm converter but it didn't work out. First, it expects a legal value as the output, so I can't just add a memref. I tried to run converter.convertType(<newMemRefTypeWithAttribute>) for this. It does the job for memrefs in the function body but not for its signature. I could not access the signature type by adding a conversion (the type never reaches the hook). And even though the internal signature conversion calls type converter recursively the pattern is never called. I think it should work since I'm adding the conversion after all the default ones, so it should be called first. Yet, that doesn't happen somehow.

So instead, I added this. It doesn't have to think about legality and all since it's not an llvm converter.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a look into this once more. It seems like if I were to reuse LLVMTypeConverter I'd need to rewrite the convertFunctionSignature to specialize to the case. That drags out some implementation code as well as changes to the converter. This looks worse to me. If you have any better idea please let me know :).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, conversion to LLVM assumes memspace None maps to the default address space in several places. It'd be complex to change that.

target.addIllegalOp<gpu::BarrierOp, gpu::BlockDimOp, gpu::BlockIdOp,
gpu::GPUFuncOp, gpu::GlobalIdOp, gpu::GridDimOp,
gpu::ReturnOp, gpu::ShuffleOp, gpu::ThreadIdOp>();
Expand Down
14 changes: 14 additions & 0 deletions mlir/test/Conversion/GPUToLLVMSPV/gpu-to-llvm-spv.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// RUN: | FileCheck --check-prefixes=CHECK-64,CHECK %s
// RUN: mlir-opt -pass-pipeline="builtin.module(gpu.module(convert-gpu-to-llvm-spv{index-bitwidth=32}))" -split-input-file -verify-diagnostics %s \
// RUN: | FileCheck --check-prefixes=CHECK-32,CHECK %s
// RUN: mlir-opt -pass-pipeline="builtin.module(gpu.module(convert-gpu-to-llvm-spv{force-opencl-address-spaces}))" -split-input-file -verify-diagnostics %s \
// RUN: | FileCheck --check-prefixes=OPENCL %s

gpu.module @builtins {
// CHECK-64: llvm.func spir_funccc @_Z14get_num_groupsj(i32) -> i64 attributes {
Expand Down Expand Up @@ -515,3 +517,15 @@ gpu.module @kernels {
gpu.return
}
}

// -----

gpu.module @kernels {
// OPENCL-LABEL: llvm.func spir_funccc @no_address_spaces(
// OPENCL-SAME: %{{[a-zA-Z_][a-zA-Z0-9_]*}}: !llvm.ptr<1>
// OPENCL-SAME: %{{[a-zA-Z_][a-zA-Z0-9_]*}}: !llvm.ptr<1>
// OPENCL-SAME: %{{[a-zA-Z_][a-zA-Z0-9_]*}}: !llvm.ptr<1>
gpu.func @no_address_spaces(%arg0: memref<f32>, %arg1: memref<f32, #gpu.address_space<global>>, %arg2: memref<f32>) {
gpu.return
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add additional and more complex tests?
For example, adding a device function inside the module and calling it from the kernel. Loading one of the arguments, etc...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added an example. I had to add func to llvm and finalize memref to llvm into the pass so that the signature and loads/stores are lowered correctly.

The function should have a spir_func attribute though. I think it'd be easiest to just go through all of them after func to llvm and attach it to those that don't have it. Kernels will have those set correctly, so we can always assume it's not a kernel.