[llvm] [offload] use argument pointer array in olLaunchKernel (PR #194333)
via llvm-commits
llvm-commits at lists.llvm.org
Tue May 5 05:21:55 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-backend-amdgpu
Author: Piotr Balcer (pbalcer)
<details>
<summary>Changes</summary>
The existing olLaunchKernel function accepts arguments through a single
contiguous packaged buffer, with an unspecified, implementation-defined,
layout. In practice, the existing AMDGPU and CUDA backend plugins require
the layout to follow C/C++ ABI rules.
This makes for a simple API when the arguments are already packaged in
an existing structure:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs);
```
In practice, this has a number of hard to workaround downsides.
# Limitations of the buffer-based API
## Runtime argument buffer construction
The example above shows the simplest scenario, where the olLaunchKernel
function is invoked directly by a program. In practice, a language
runtime that uses liboffload may need to construct the argument buffer
at runtime. This may involve allocating a variably-sized buffer and
populating it correctly, accounting for alignment and padding,
with user-provided arguments.
Constructing such a buffer may be non-trivial, or even impossible,
in scenarios where the language runtime doesn't have full argument
metadata containing size or alignment information about arguments.
In addition to the above issue, constructing such a buffer, at runtime
during kernel launch, adds an otherwise avoidable host copy before the
plugin's, or driver's, own copy. Each existing (AMDGPU/HSA, CUDA, Level-Zero)
and anticipated (OpenCL) backend already needs to create its own
GPU-accessible copy of the kernel argument buffer, extending its lifetime
past the kernel launch function.
## Unspecified argument buffer ABI
Another issue with an argument buffer is that its layout is currently
implementation-defined. While they may be compatible in practice,
relying on C/C++ ABI rules, the AMDGPU kernarg and NVPTX .param are
two distinct ABIs.
Allowing the layout to be implementation-defined may require the caller
to construct the buffer differently based on the underlying backend.
In most scenarios, liboffload users should not need to be aware of the
choice of the backend, instead relying on the provided abstractions.
Similarily, the compiler can't optimize code that produces the buffer
if the layout can't be determined at compile-time.
A target independent API accepting a buffer would have to define its own
layout compatible with, or at least convertable to, all existing
and future backends. Documenting the layout format would be a non-trivial
endeavour, likely involving collaboration with various other entities,
such as the Khronos Group, if we wanted for that layout to be natively
supported by all the backends.
## Non-straightforward backend implementations
The only two backends that can natively implement the existing method of
passing arguments are CUDA and AMDGPU. For OpenCL and Level-Zero, the
plugins would need to internally translate the contiguous buffer into
either calls to clSetKernelArg / zeKernelSetArgumentValue or, in the case
of Level Zero, an array of pointers to arguments, for use in
zeCommandListAppendLaunchKernelWithArguments
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments).
Doing this translation is non-trivial, since it requires the knowledge
of size and alignment of arguments within the buffer. Information which
is not provided through the olLaunchKernel API. There's currently no API in
Level-Zero or OpenCL that can be reliably used to retrieve argument
metadata from a program. Previously, we've attempted to solve this
by adding explicit argument metadata to olLaunchKernel:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
uint64_t ArgSizes[] = {sizeof(char), sizeof(int *), sizeof(short)};
ol_kernel_launch_prop_t Props[] = {
{OL_KERNEL_LAUNCH_PROP_TYPE_SIZE, ArgSizes},
OL_KERNEL_LAUNCH_PROP_END
};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), …, Props);
```
This makes the API harder to use, and, most importantly, is
insufficient if we want the API to be target independent. The API above,
with just an array of sizes for each argument, does not allow the plugin
to account for padding inside of the buffer. OpenCL and Level-Zero plugins
would need to see a tightly-packed buffer, while CUDA and AMDGPU plugins need
a C/C++ ABI-padded one.
## Difficulty of extracting kernel argument metadata from programs
One solution to retrieving kernel argument metadata could be to read
them from the program image. This is similar to how the AMDGPU plugin
already reads general kernel metadata (readAMDGPUMetaDataFromImage).
However, this would require that the program image format accepted by
liboffload is formalized, and that the OpenCL and Level-Zero plugins
parse and read that format to extract the required metadata. While for
many initial use cases, it may be enough to define the program image
format to be SPIR-V for Level-Zero and OpenCL, it would not allow us to
support creating programs from an existing implementation-specific binary.
Such functionality will be required to support some SYCL features,
such as kernel module interop (where the kernel is created from
an existing backend binary), runtime compilation, and kernel caching.
The equivalent OpenCL API is clCreateProgramWithBinary, where the
documentation states the following:
> The program binary can consist of either or both:
> - Device-specific code and/or,
> - Implementation-specific intermediate representation (IR) which
> will be converted to the device-specific code.
https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/clCreateProgramWithBinary.html
Extracting kernel argument metadata from such binaries would require
the generic OpenCL backend to parse vendor-specific binary formats,
one per implementation it intends to support.
# Solution: Pointer-Based Kernel Argument Passing
This PR changes olLaunchKernel to accept an array of pointers to arguments:
```
void *ArgPtrs[] = {&A, &B, &C};
size_t ArgSizes[] = {sizeof(A), sizeof(B), sizeof(C)};
olLaunchKernel(Queue, Device, Kernel, &LaunchArgs, std::size(ArgPtrs), ArgPtrs, ArgSizes);
```
The newly proposed interface is implementable by existing and anticipated
backends, is familiar to CUDA programmers, eliminates the extraneous
construction of a contiguous arguments buffer, replacing it with constructing
an array of pointers, sidesteps the alignment requirements, does not
require reading program image metadata where it's impractical, and enables
a compliant SYCL implementation to be built on top of it.
The ArgSizes array is required to support OpenCL, which does not have
native support for launching a kernel with an argument pointer array, or
a reliable way of retrieving argument sizes for a kernel.
## Mapping the proposed API to backends
CUDA and Level-Zero both support accepting an array of pointers to
kernel arguments, through `cuLaunchKernel`
(https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15)
and `zeCommandListAppendLaunchKernelWithArguments`
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments)
respectively.
For OpenCL, which requires the kernel arguments to be set separately
from the kernel launch, a potential implementation can extract the
number of arguments from the OpenCL API, and then iterate over the
argument pointer and size arrays:
```
cl_uint num_args = 0;
cl_int err = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS,
sizeof(num_args), &num_args, NULL);
for (cl_uint i = 0; i < num_args; ++i) {
clSetKernelArg(kernel, i, ArgSizes[i], ArgPtrs[i]);
}
```
The AMDGPU plugin needs to construct a contiguous buffer using the array
of argument pointers. To do this conversion, we need to have offsets
at which to place the arguments. Here, luckily, as mentioned before,
the AMD plugin already reads kernel metadata from the program image.
The implementation simply retrieves size and offset for each argument
from the kernel image, and then uses it to populate a buffer.
## Supporting SYCL with the proposed API
SYCL 2020, and Intel's intel/llvm SYCL implementation, uses 6
fundamental kinds of arguments:
1. USM pointers
2. Buffers
3. Images
4. Samplers
5. Values
6. Local Arguments
Which map to 5 kinds of arguments in Unified Runtime:
```
typedef enum ur_exp_kernel_arg_type_t {
UR_EXP_KERNEL_ARG_TYPE_VALUE = 0,
UR_EXP_KERNEL_ARG_TYPE_POINTER = 1,
UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ = 2,
UR_EXP_KERNEL_ARG_TYPE_LOCAL = 3,
UR_EXP_KERNEL_ARG_TYPE_SAMPLER = 4,
...
} ur_exp_kernel_arg_type_t;
```
The following SYCL 2020 program demonstrates their use:
```
#include <sycl/sycl.hpp>
#include <cstdio>
#include <cstdlib>
int main() {
sycl::queue q;
int *usm_ptr = sycl::malloc_host<int>(1, q);
*usm_ptr = -1;
int host_data[1] = {5};
sycl::buffer<int, 1> buf(host_data, sycl::range<1>(1));
sycl::image<2> img(sycl::image_channel_order::rgba,
sycl::image_channel_type::fp32,
sycl::range<2>(4, 4));
sycl::sampler samp(
sycl::coordinate_normalization_mode::unnormalized,
sycl::addressing_mode::clamp,
sycl::filtering_mode::nearest);
int val = 42;
q.submit([&](sycl::handler &h) {
auto buf_acc =
buf.get_access<sycl::access::mode::read_write>(h);
auto img_acc =
img.get_access<sycl::float4,
sycl::access::mode::read>(h);
sycl::local_accessor<int, 1> local_mem(
sycl::range<1>(64), h);
sycl::local_accessor<int, 1> local_mem2(
sycl::range<1>(64), h);
h.parallel_for(sycl::nd_range<1>(1, 1),
[=](sycl::nd_item<1> item) {
local_mem[0] = val;
local_mem2[0] = val + 1;
buf_acc[0] = buf_acc[0] + local_mem[0] + local_mem2[0];
usm_ptr[0] = buf_acc[0];
// just to keep the args
(void)img_acc;
(void)samp;
});
});
q.wait();
int expected = 5 + 42 + 43;
printf("usm_ptr[0] = %d (expected %d)\n", *usm_ptr, expected);
sycl::free(usm_ptr, q);
return 0;
}
```
The kernel launch uses the following UR call (simplified for
legibility):
```
urEnqueueKernelLaunchWithArgsExp(
.hQueue = 0xca2f090,
.hKernel = 0xc7640f0,
.workDim = 1,
.pGlobalWorkOffset = nullptr,
.pGlobalWorkSize = 0xc6e1c38 (1),
.pLocalWorkSize = 0xc6e1c50 (1),
.numArgs = 8,
.pArgs = 0xc754710 {
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 0, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 1, .size = 4,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6e23e8}},
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 2, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 3, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6e60f0, .flags = UR_MEM_FLAG_READ_WRITE}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 4, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6966f0}},
{.type = UR_EXP_KERNEL_ARG_TYPE_POINTER, .index = 5, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.pointer = ...}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 6, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6ebac0, .flags = UR_MEM_FLAG_READ_ONLY}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_SAMPLER, .index = 7, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.sampler = 0xca50750}}
},
...
) -> UR_RESULT_SUCCESS;
```
In order to support a compliant SYCL 2020 specification, liboffload
launch kernel API needs to be able to support all these kinds of
arguments. The proposed API makes this straightforward. To launch the
kernel above, the language runtime could use the liboffload API in the
following way:
```
ol_kernel_launch_size_args_t LaunchArgs;
LaunchArgs.Dimensions = 1;
LaunchArgs.GroupSize = {1, 1, 1};
LaunchArgs.NumGroups = {1, 1, 1};
// CUDA, HSA, Level Zero, and OpenCL have a differing model of
// shared / local memory. The lowest common denominator is setting
// only a single shared memory block to contain all memory required
// by SYCL's local accessors, with the language runtime additionally
// setting offsets into that block as value arguments.
// Level Zero doesn't currently implement this feature.
// The SPIR-V kernel is expected to declare a single SLM argument
// at the last position when this field is set.
LaunchArgs.DynSharedMemory = 512;
SmallVector<void *, 8> ArgPtrs;
SmallVector<size_t, 8> ArgSizes;
// [0] local_mem: first local accessor, offset 0 into the shared
// memory block.
uint32_t LocalOffset0 = 0;
ArgPtrs.push_back(&LocalOffset0);
ArgSizes.push_back(sizeof(uint32_t));
// [1] val: plain value argument (int val = 42).
int Val = 42;
ArgPtrs.push_back(&Val);
ArgSizes.push_back(sizeof(int));
// [2] local_mem2: second local accessor, offset 256 into the shared
// memory block.
uint32_t LocalOffset1 = 256;
ArgPtrs.push_back(&LocalOffset1);
ArgSizes.push_back(sizeof(uint32_t));
// [3] buf_acc: buffer accessor. Buffers are not supported in
// liboffload. The language runtimes can use USM memory instead.
void *BufPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&BufPtr);
ArgSizes.push_back(sizeof(void *));
// [4] buffer accessor metadata, passed by value.
size_t buf_accessor_md = 0;
ArgPtrs.push_back(&buf_accessor_md);
ArgSizes.push_back(sizeof(size_t));
// [5] usm_ptr: USM pointer argument.
void *UsmPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&UsmPtr);
ArgSizes.push_back(sizeof(void *));
// All argument kinds are ultimately just pointers to values,
// including images and samplers.
// [6] img_acc: Images can be opaque handles in
// liboffload. This API doesn't exist yet.
ol_image_handle_t Image = olCreateImage(...);
ArgPtrs.push_back(olImageGetArgPtr(Image));
ArgSizes.push_back(olImageGetArgSize(Image));
// [7] sampler: Samplers can be opaque handles in liboffload.
// This API doesn't exist yet.
ol_sampler_handle_t Sampler = olCreateSampler(...);
ArgPtrs.push_back(olSamplerGetArgPtr(Sampler));
// Sampler size can be different depending on the platform
ArgSizes.push_back(olSamplerGetArgSize(Sampler));
olLaunchKernel(Queue, Device, Kernel, &LaunchArgs,
ArgPtrs.size(), ArgPtrs.data(), ArgSizes.data());
```
This API provides flexibility and target independence, while allowing
efficient kernel dispatch from all backends we expect to support.
---
Patch is 50.11 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/194333.diff
23 Files Affected:
- (modified) llvm/include/llvm/Frontend/Offloading/Utility.h (+14)
- (modified) llvm/lib/Frontend/Offloading/Utility.cpp (+32)
- (modified) llvm/tools/llvm-gpu-loader/llvm-gpu-loader.cpp (+37-7)
- (modified) llvm/tools/llvm-gpu-loader/llvm-gpu-loader.h (+3-2)
- (modified) offload/include/Shared/APITypes.h (+3-2)
- (modified) offload/liboffload/API/Kernel.td (+13-5)
- (modified) offload/liboffload/src/OffloadImpl.cpp (+11-9)
- (modified) offload/plugins-nextgen/amdgpu/src/rtl.cpp (+28-7)
- (modified) offload/plugins-nextgen/common/src/PluginInterface.cpp (+4-3)
- (modified) offload/plugins-nextgen/cuda/src/rtl.cpp (+31-7)
- (modified) offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp (+1)
- (modified) offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h (+12)
- (modified) offload/plugins-nextgen/level_zero/src/L0Kernel.cpp (+83-30)
- (modified) offload/unittests/Conformance/include/mathtest/DeviceContext.hpp (+14-7)
- (modified) offload/unittests/Conformance/lib/DeviceContext.cpp (+6-5)
- (modified) offload/unittests/OffloadAPI/device_code/CMakeLists.txt (+2)
- (added) offload/unittests/OffloadAPI/device_code/composite.cpp (+10)
- (modified) offload/unittests/OffloadAPI/device_code/multiargs.cpp (+3-1)
- (modified) offload/unittests/OffloadAPI/event/olGetEventElapsedTime.cpp (+4-5)
- (modified) offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp (+107-53)
- (modified) offload/unittests/OffloadAPI/memory/olMemcpy.cpp (+6-7)
- (modified) offload/unittests/OffloadAPI/queue/olLaunchHostFunction.cpp (+3-4)
- (modified) offload/unittests/OffloadAPI/queue/olWaitEvents.cpp (+18-21)
``````````diff
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h b/llvm/include/llvm/Frontend/Offloading/Utility.h
index a1a8a02916265..812bbb3234246 100644
--- a/llvm/include/llvm/Frontend/Offloading/Utility.h
+++ b/llvm/include/llvm/Frontend/Offloading/Utility.h
@@ -15,6 +15,7 @@
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Module.h"
@@ -121,6 +122,16 @@ namespace amdgpu {
LLVM_ABI bool isImageCompatibleWithEnv(StringRef ImageArch, uint32_t ImageFlags,
StringRef EnvTargetID);
+/// Struct for holding AMDGPU Kernel Argument Metadata, see:
+/// https://llvm.org/docs/AMDGPUUsage.html#amdgpu-amdhsa-code-object-kernel-argument-metadata-map-table-v3
+struct AMDGPUKernelArgMetaData {
+ /// Kernel argument offset in bytes. The offset must be a multiple
+ /// of the alignment required by the argument.
+ uint32_t Offset = 0;
+ /// Kernel argument size in bytes.
+ uint32_t Size = 0;
+};
+
/// Struct for holding metadata related to AMDGPU kernels, for more information
/// about the metadata and its meaning see:
/// https://llvm.org/docs/AMDGPUUsage.html#code-object-v3
@@ -154,6 +165,9 @@ struct AMDGPUKernelMetaData {
uint32_t WavefrontSize = KInvalidValue;
/// Maximum flat work-group size supported by the kernel in work-items.
uint32_t MaxFlatWorkgroupSize = KInvalidValue;
+ /// Per-argument offset and size, read from the ".args" array in code object
+ /// metadata. Includes only explicit user arguments.
+ SmallVector<AMDGPUKernelArgMetaData, 8> ExplicitArgMDs;
};
/// Reads AMDGPU specific metadata from the ELF file and propagates the
diff --git a/llvm/lib/Frontend/Offloading/Utility.cpp b/llvm/lib/Frontend/Offloading/Utility.cpp
index d689d1bb192d6..8b95cda433d03 100644
--- a/llvm/lib/Frontend/Offloading/Utility.cpp
+++ b/llvm/lib/Frontend/Offloading/Utility.cpp
@@ -315,6 +315,38 @@ class KernelInfoReader {
KernelData.WavefrontSize = V.second.getUInt();
} else if (IsKey(V.first, ".max_flat_workgroup_size")) {
KernelData.MaxFlatWorkgroupSize = V.second.getUInt();
+ } else if (IsKey(V.first, ".args")) {
+ auto ArgsArray = V.second.getArray();
+ for (auto ArgIt = ArgsArray.begin(), ArgEnd = ArgsArray.end();
+ ArgIt != ArgEnd; ++ArgIt) {
+ auto ArgMap = ArgIt->getMap();
+
+ // Skip hidden arguments
+ auto VKIt = ArgMap.find(".value_kind");
+ if (VKIt != ArgMap.end() &&
+ VKIt->second.getString().starts_with("hidden_"))
+ continue;
+
+ auto OffsetIt = ArgMap.find(".offset");
+ // TODO: should these be asserts?
+ // if .offset or .size isn't found, that means the kernel
+ // is malformed.
+ if (OffsetIt == ArgMap.end())
+ return createStringError(
+ inconvertibleErrorCode(),
+ "Missing required .offset key in kernel argument metadata map");
+ auto SizeIt = ArgMap.find(".size");
+ if (SizeIt == ArgMap.end())
+ return createStringError(
+ inconvertibleErrorCode(),
+ "Missing required .size key in kernel argument metadata map");
+
+ amdgpu::AMDGPUKernelArgMetaData ArgMD;
+ ArgMD.Offset = OffsetIt->second.getUInt();
+ ArgMD.Size = SizeIt->second.getUInt();
+
+ KernelData.ExplicitArgMDs.push_back(ArgMD);
+ }
}
return Error::success();
diff --git a/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.cpp b/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.cpp
index e78edf854d17c..b1fd8a0216f28 100644
--- a/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.cpp
+++ b/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.cpp
@@ -183,16 +183,46 @@ ol_device_handle_t getHostDevice() {
return Device;
}
-template <typename Args>
-void launchKernel(ol_queue_handle_t Queue, ol_device_handle_t Device,
- ol_program_handle_t Program, const char *Name,
- ol_kernel_launch_size_args_t LaunchArgs, Args &KernelArgs) {
+static void launchKernelImpl(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_program_handle_t Program, const char *Name,
+ ol_kernel_launch_size_args_t LaunchArgs,
+ size_t NumArgs, void **ArgPtrs,
+ const size_t *ArgSizes) {
ol_symbol_handle_t Kernel;
OFFLOAD_ERR(olGetSymbol(Program, Name, OL_SYMBOL_KIND_KERNEL, &Kernel));
- OFFLOAD_ERR(olLaunchKernel(Queue, Device, Kernel, &KernelArgs,
- std::is_empty_v<Args> ? 0 : sizeof(Args),
- &LaunchArgs));
+ OFFLOAD_ERR(olLaunchKernel(Queue, Device, Kernel, &LaunchArgs, NumArgs,
+ ArgPtrs, ArgSizes));
+}
+
+void launchKernel(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_program_handle_t Program, const char *Name,
+ ol_kernel_launch_size_args_t LaunchArgs,
+ BeginArgs &KernelArgs) {
+ void *ArgPtrs[] = {&KernelArgs.Argc, &KernelArgs.Argv, &KernelArgs.Envp};
+ size_t ArgSizes[] = {sizeof(KernelArgs.Argc), sizeof(KernelArgs.Argv),
+ sizeof(KernelArgs.Envp)};
+ launchKernelImpl(Queue, Device, Program, Name, LaunchArgs, 3, ArgPtrs,
+ ArgSizes);
+}
+
+void launchKernel(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_program_handle_t Program, const char *Name,
+ ol_kernel_launch_size_args_t LaunchArgs,
+ StartArgs &KernelArgs) {
+ void *ArgPtrs[] = {&KernelArgs.Argc, &KernelArgs.Argv, &KernelArgs.Envp,
+ &KernelArgs.Ret};
+ size_t ArgSizes[] = {sizeof(KernelArgs.Argc), sizeof(KernelArgs.Argv),
+ sizeof(KernelArgs.Envp), sizeof(KernelArgs.Ret)};
+ launchKernelImpl(Queue, Device, Program, Name, LaunchArgs, 4, ArgPtrs,
+ ArgSizes);
+}
+
+void launchKernel(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_program_handle_t Program, const char *Name,
+ ol_kernel_launch_size_args_t LaunchArgs, EndArgs &) {
+ launchKernelImpl(Queue, Device, Program, Name, LaunchArgs, 0, nullptr,
+ nullptr);
}
int main(int argc, const char **argv, const char **envp) {
diff --git a/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.h b/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.h
index 8e156768a8aba..f187001667975 100644
--- a/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.h
+++ b/llvm/tools/llvm-gpu-loader/llvm-gpu-loader.h
@@ -123,8 +123,9 @@ ol_result_t (*olGetSymbol)(ol_program_handle_t Program, const char *Name,
ol_result_t (*olLaunchKernel)(
ol_queue_handle_t Queue, ol_device_handle_t Device,
- ol_symbol_handle_t Kernel, const void *ArgumentsData, size_t ArgumentsSize,
- const ol_kernel_launch_size_args_t *LaunchSizeArgs);
+ ol_symbol_handle_t Kernel,
+ const ol_kernel_launch_size_args_t *LaunchSizeArgs, size_t NumArgs,
+ void **ArgPtrs, const size_t *ArgSizes);
ol_result_t (*olCreateQueue)(ol_device_handle_t Device,
ol_queue_handle_t *Queue);
diff --git a/offload/include/Shared/APITypes.h b/offload/include/Shared/APITypes.h
index 5e61bc7c842e7..5b8e957d74677 100644
--- a/offload/include/Shared/APITypes.h
+++ b/offload/include/Shared/APITypes.h
@@ -104,8 +104,9 @@ struct KernelArgsTy {
uint64_t NoWait : 1; // Was this kernel spawned with a `nowait` clause.
uint64_t IsCUDA : 1; // Was this kernel spawned via CUDA.
uint64_t DynCGroupMemFallback : 2; // The fallback for dynamic cgroup mem.
- uint64_t Unused : 60;
- } Flags = {0, 0, 0, 0};
+ uint64_t IsPtrArgs : 1; // Arguments are laid out as an array of pointers.
+ uint64_t Unused : 59;
+ } Flags = {0, 0, 0, 0, 0};
// The number of teams (for x,y,z dimension).
uint32_t NumTeams[3] = {0, 0, 0};
// The number of threads (for x,y,z dimension).
diff --git a/offload/liboffload/API/Kernel.td b/offload/liboffload/API/Kernel.td
index 2f5692a19d712..2ca65e187e10e 100644
--- a/offload/liboffload/API/Kernel.td
+++ b/offload/liboffload/API/Kernel.td
@@ -21,21 +21,29 @@ def ol_kernel_launch_size_args_t : Struct {
}
def olLaunchKernel : Function {
- let desc = "Enqueue a kernel launch with the specified size and parameters.";
+ let desc = "Enqueue a kernel launch with arguments specified as an array of pointers and sizes.";
let details = [
"If a queue is not specified, kernel execution happens synchronously",
- "ArgumentsData may be set to NULL (to indicate no parameters)"
+ "Each element of ArgPtrs points to the value of the corresponding kernel argument",
+ "Each element of ArgSizes specifies the size in bytes of the corresponding argument",
+ "NumArgs must match the number of arguments expected by the kernel",
+ "ArgPtrs and ArgSizes must both be NULL (when NumArgs == 0) or both be non-NULL"
];
let params = [
Param<"ol_queue_handle_t", "Queue", "handle of the queue", PARAM_IN_OPTIONAL>,
Param<"ol_device_handle_t", "Device", "handle of the device to execute on", PARAM_IN>,
Param<"ol_symbol_handle_t", "Kernel", "handle of the kernel", PARAM_IN>,
- Param<"const void*", "ArgumentsData", "pointer to the kernel argument struct", PARAM_IN_OPTIONAL>,
- Param<"size_t", "ArgumentsSize", "size of the kernel argument struct", PARAM_IN>,
Param<"const ol_kernel_launch_size_args_t*", "LaunchSizeArgs", "pointer to the struct containing launch size parameters", PARAM_IN>,
+ Param<"size_t", "NumArgs", "number of kernel arguments", PARAM_IN>,
+ Param<"void**", "ArgPtrs", "array of pointers, each pointing to an argument value", PARAM_IN_OPTIONAL>,
+ Param<"const size_t*", "ArgSizes", "array of argument sizes", PARAM_IN_OPTIONAL>,
];
let returns = [
- Return<"OL_ERRC_INVALID_ARGUMENT", ["`ArgumentsSize > 0 && ArgumentsData == NULL`"]>,
+ Return<"OL_ERRC_INVALID_ARGUMENT", [
+ "`(ArgPtrs == NULL) != (ArgSizes == NULL)`",
+ "`NumArgs > 0 && (ArgPtrs == NULL || ArgSizes == NULL)`",
+ "NumArgs does not match the number of arguments expected by the kernel",
+ ]>,
Return<"OL_ERRC_INVALID_DEVICE", ["If Queue is non-null but does not belong to Device"]>,
Return<"OL_ERRC_SYMBOL_KIND", ["The provided symbol is not a kernel"]>,
];
diff --git a/offload/liboffload/src/OffloadImpl.cpp b/offload/liboffload/src/OffloadImpl.cpp
index 71712c2bc6b45..ef59c5ac75c96 100644
--- a/offload/liboffload/src/OffloadImpl.cpp
+++ b/offload/liboffload/src/OffloadImpl.cpp
@@ -1050,9 +1050,10 @@ Error olCalculateOptimalOccupancy_impl(ol_device_handle_t Device,
}
Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
- ol_symbol_handle_t Kernel, const void *ArgumentsData,
- size_t ArgumentsSize,
- const ol_kernel_launch_size_args_t *LaunchSizeArgs) {
+ ol_symbol_handle_t Kernel,
+ const ol_kernel_launch_size_args_t *LaunchSizeArgs,
+ size_t NumArgs, void **ArgPtrs,
+ const size_t *ArgSizes) {
auto *DeviceImpl = Device->Device;
if (Queue && Device != Queue->Device) {
return createOffloadError(
@@ -1067,6 +1068,8 @@ Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
auto *QueueImpl = Queue ? Queue->AsyncInfo : nullptr;
AsyncInfoWrapperTy AsyncInfoWrapper(*DeviceImpl, QueueImpl);
KernelArgsTy LaunchArgs{};
+ // TODO: change LaunchArgs.NumArgs to size_t to match the API type
+ LaunchArgs.NumArgs = static_cast<uint32_t>(NumArgs);
LaunchArgs.NumTeams[0] = LaunchSizeArgs->NumGroups.x;
LaunchArgs.NumTeams[1] = LaunchSizeArgs->NumGroups.y;
LaunchArgs.NumTeams[2] = LaunchSizeArgs->NumGroups.z;
@@ -1075,12 +1078,11 @@ Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
LaunchArgs.ThreadLimit[2] = LaunchSizeArgs->GroupSize.z;
LaunchArgs.DynCGroupMem = LaunchSizeArgs->DynSharedMemory;
- KernelLaunchParamsTy Params;
- Params.Data = const_cast<void *>(ArgumentsData);
- Params.Size = ArgumentsSize;
- LaunchArgs.ArgPtrs = reinterpret_cast<void **>(&Params);
- // Don't do anything with pointer indirection; use arg data as-is
- LaunchArgs.Flags.IsCUDA = true;
+ LaunchArgs.ArgPtrs = ArgPtrs;
+ // TODO: Either change ArgSizes to const size_t * or add a new variable.
+ LaunchArgs.ArgSizes =
+ reinterpret_cast<int64_t *>(const_cast<size_t *>(ArgSizes));
+ LaunchArgs.Flags.IsPtrArgs = 1;
auto *KernelImpl = std::get<GenericKernelTy *>(Kernel->PluginImpl);
auto Err = KernelImpl->launch(*DeviceImpl, LaunchArgs.ArgPtrs, nullptr,
diff --git a/offload/plugins-nextgen/amdgpu/src/rtl.cpp b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
index f4e81025a285d..ab99c91b02ab5 100644
--- a/offload/plugins-nextgen/amdgpu/src/rtl.cpp
+++ b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
@@ -4144,11 +4144,32 @@ Error AMDGPUKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
if (auto Err = GenericDevice.getDeviceStackSize(StackSize))
return Err;
- // Copy the explicit arguments.
- // TODO: We should expose the args memory manager alloc to the common part as
- // alternative to copying them twice.
- if (LaunchParams.Size)
- std::memcpy(AllArgs, LaunchParams.Data, LaunchParams.Size);
+ // Copy explicit arguments.
+ size_t ExplicitEnd = 0;
+ if (KernelArgs.Flags.IsPtrArgs) {
+ if (KernelArgs.ArgPtrs) { // may be null
+ const auto &ArgMDs = KernelInfo->ExplicitArgMDs;
+
+ if (KernelArgs.NumArgs != ArgMDs.size())
+ return Plugin::error(
+ ErrorCode::INVALID_ARGUMENT,
+ "Number of arguments (%u) does not match the number of arguments "
+ "expected by the kernel (%zu)",
+ KernelArgs.NumArgs, ArgMDs.size());
+
+ for (size_t I = 0; I < ArgMDs.size(); I++)
+ std::memcpy(utils::advancePtr(AllArgs, ArgMDs[I].Offset),
+ KernelArgs.ArgPtrs[I], ArgMDs[I].Size);
+
+ ExplicitEnd = ArgMDs.back().Offset + ArgMDs.back().Size;
+ }
+ } else {
+ // TODO: We should expose the args memory manager alloc to the common part
+ // as alternative to copying them twice.
+ if (LaunchParams.Size)
+ std::memcpy(AllArgs, LaunchParams.Data, LaunchParams.Size);
+ ExplicitEnd = LaunchParams.Size;
+ }
AMDGPUDeviceTy &AMDGPUDevice = static_cast<AMDGPUDeviceTy &>(GenericDevice);
@@ -4156,8 +4177,8 @@ Error AMDGPUKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
if (auto Err = AMDGPUDevice.getStream(AsyncInfoWrapper, Stream))
return Err;
- uint64_t ImplArgsOffset = llvm::alignTo(
- LaunchParams.Size, alignof(hsa_utils::AMDGPUImplicitArgsTy));
+ uint64_t ImplArgsOffset =
+ llvm::alignTo(ExplicitEnd, alignof(hsa_utils::AMDGPUImplicitArgsTy));
if (ArgsSize > ImplArgsOffset) {
hsa_utils::AMDGPUImplicitArgsTy *ImplArgs =
reinterpret_cast<hsa_utils::AMDGPUImplicitArgsTy *>(
diff --git a/offload/plugins-nextgen/common/src/PluginInterface.cpp b/offload/plugins-nextgen/common/src/PluginInterface.cpp
index 12ccebdfbc57a..8fd9fc180ac14 100644
--- a/offload/plugins-nextgen/common/src/PluginInterface.cpp
+++ b/offload/plugins-nextgen/common/src/PluginInterface.cpp
@@ -273,13 +273,14 @@ Error GenericKernelTy::launch(GenericDeviceTy &GenericDevice, void **ArgPtrs,
if (!KernelLaunchEnvOrErr)
return KernelLaunchEnvOrErr.takeError();
- KernelLaunchParamsTy LaunchParams;
-
// Kernel languages don't use indirection.
+ // IsPtrArgs bypasses LaunchParms entirely,
+ // plugins read KernelArgs.ArgPtrs/ArgSizes directly.
+ KernelLaunchParamsTy LaunchParams;
if (KernelArgs.Flags.IsCUDA) {
LaunchParams =
*reinterpret_cast<KernelLaunchParamsTy *>(KernelArgs.ArgPtrs);
- } else {
+ } else if (!KernelArgs.Flags.IsPtrArgs) {
LaunchParams =
prepareArgs(GenericDevice, ArgPtrs, ArgOffsets, KernelArgs.NumArgs,
Args, Ptrs, *KernelLaunchEnvOrErr, KernelArgs.Version);
diff --git a/offload/plugins-nextgen/cuda/src/rtl.cpp b/offload/plugins-nextgen/cuda/src/rtl.cpp
index 05fdcb032bd29..5d0d41012c988 100644
--- a/offload/plugins-nextgen/cuda/src/rtl.cpp
+++ b/offload/plugins-nextgen/cuda/src/rtl.cpp
@@ -165,11 +165,14 @@ struct CUDAKernelTy : public GenericKernelTy {
size_t Arg = 0;
ArgsSize = 0;
+ NumArgs = 0;
// Find the last argument to know the total size of the arguments.
while ((Res = cuFuncGetParamInfo(Func, Arg++, &ArgOffset, &ArgSize)) ==
- CUDA_SUCCESS)
+ CUDA_SUCCESS) {
ArgsSize = ArgOffset + ArgSize;
+ ++NumArgs;
+ }
if (Res != CUDA_ERROR_INVALID_VALUE)
return Plugin::check(Res, "error in cuFuncGetParamInfo: %s");
@@ -184,6 +187,13 @@ struct CUDAKernelTy : public GenericKernelTy {
/// The size of the kernel arguments.
size_t ArgsSize;
+
+ /// The number of kernel arguments.
+ size_t NumArgs = 0;
+
+public:
+ /// Return the number of kernel arguments reported by the driver.
+ size_t getNumArgs() const { return NumArgs; }
};
/// Class wrapping a CUDA stream reference. These are the objects handled by the
@@ -1455,17 +1465,30 @@ Error CUDAKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
AsyncInfoWrapperTy &AsyncInfoWrapper) const {
CUDADeviceTy &CUDADevice = static_cast<CUDADeviceTy &>(GenericDevice);
- // The args size passed in LaunchParams may have tail padding, which is not
- // accepted by the CUDA driver.
- if (ArgsSize > LaunchParams.Size)
- return Plugin::error(ErrorCode::INVALID_ARGUMENT,
- "mismatch in kernel arguments");
+ void **KernelParams = nullptr;
+ if (KernelArgs.Flags.IsPtrArgs) {
+ if (KernelArgs.NumArgs != NumArgs)
+ return Plugin::error(
+ ErrorCode::INVALID_ARGUMENT,
+ "Number of arguments (%u) does not match the number of arguments "
+ "expected by the kernel (%zu)",
+ KernelArgs.NumArgs, NumArgs);
+
+ KernelParams = KernelArgs.ArgPtrs;
+ } else {
+ // The args size passed in LaunchParams may have tail padding,
+ // which is not accepted by the CUDA driver.
+ if (ArgsSize > LaunchParams.Size)
+ return Plugin::error(ErrorCode::INVALID_ARGUMENT,
+ "mismatch in kernel arguments");
+ }
CUstream Stream;
if (auto Err = CUDADevice.getStream(AsyncInfoWrapper, Stream))
return Err;
size_t ConfigArgsSize = ArgsSize;
+ // valid for buffer passed through LaunchParams
void *Config[] = {CU_LAUNCH_PARAM_BUFFER_POINTER, LaunchParams.Data,
CU_LAUNCH_PARAM_BUFFER_SIZE,
reinterpret_cast<void *>(&ConfigArgsSize),
@@ -1489,7 +1512,8 @@ Error CUDAKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
CUresult Res = cuLaunchKernel(Func, NumBlocks[0], NumBlocks[1], NumBlocks[2],
NumThreads[0], NumThreads[1], NumThreads[2],
- DynBlockMemSize, Stream, nullptr, Config);
+ DynBlockMemSize, Stream, KernelParams,
+ KernelParams ? nullptr : Config);
// Register a callback to indicate when the kernel is complete.
if (GenericDevice.getRPCServer())
diff --git a/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp b/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
index 8643897facacd..67cbdca3ab82b 100644
--- a/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
+++ b/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
@@ -29,6 +29,7 @@ DLWRAP(zeModuleDestroy, 1)
DLWRAP(zeCommandListAppendBarrier, 4)
DLWRAP(zeCommandListAppendLaunchKernel, 6)
DLWRAP(zeCommandListAppendLaunchCooperativeKernel, 6)
+DLWRAP(zeCommandListAppendLaunchKernelWithArguments, 9)
DLWRAP(zeCommandListAppendMemoryCopy, 7)
DLWRAP(zeCommandListAppendMemoryCopyRegion, 12)
DLWRAP(zeCommandListAppendMemoryFill, 8)
diff --git a/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h b/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h
...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/194333
More information about the llvm-commits
mailing list